Skip to content

Instantly share code, notes, and snippets.

@sonirico
Last active December 25, 2016 07:01
Show Gist options
  • Save sonirico/09d7e15ec91c411bb73f619acf8b537b to your computer and use it in GitHub Desktop.
Save sonirico/09d7e15ec91c411bb73f619acf8b537b to your computer and use it in GitHub Desktop.
ScriptSystem, ECS pattern (artemis-odb).
package com.katodia.istariquest.systems;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.PooledComponent;
import com.artemis.World;
import com.artemis.systems.IteratingSystem;
import java.util.HashMap;
import java.util.Map;
public class ScriptSystem extends IteratingSystem {
private ComponentMapper<ScriptComponent> scriptMap;
public ScriptSystem () {
super(Aspect.all(ScriptComponent.class));
}
public void current (int entityId, Class<? extends Script> scriptClass) {
ScriptComponent sc = scriptMap.get(entityId);
// Cleanup operations
sc.getCurrentScript().end(entityId);
Script current = sc.getScripts().get(scriptClass);
sc.setCurrentScript(current);
// Initializing operations
current.begin(entityId);
}
@Override
protected void process(int entityId) {
ScriptComponent sc = scriptMap.get(entityId);
// Check for fresh added scripts
sc.getScripts().forEach((scriptClass, script) -> {
if (! script.initialized) {
script.inject(world);
}
});
sc.process(entityId);
}
public static class ScriptComponent extends PooledComponent {
private Map<Class<? extends Script>, Script> scripts;
private Script currentScript;
public ScriptComponent () {
scripts = new HashMap<>();
}
public ScriptComponent add (Script sc) {
this.scripts.put(sc.getClass(), sc);
return this;
}
public void current (Class<? extends Script> scriptClass) {
this.currentScript = scripts.get(scriptClass);
}
public void setCurrentScript (Script s) {
this.currentScript = s;
}
public Script getCurrentScript () {
return this.currentScript;
}
public Map<Class<? extends Script>, Script> getScripts () {
return this.scripts;
}
public void process (int entityId) {
this.currentScript.process(entityId);
}
@Override
protected void reset() {
scripts.clear();
}
}
public static abstract class Script {
protected World world;
protected boolean initialized = false;
public Script inject (World world) {
if (initialized) {
if (this.world.equals(world)) {
throw new RuntimeException("World is already injected");
} else {
return this;
}
}
this.world = world;
this.initialized = true;
return this;
}
public abstract void begin (int entityId);
public abstract void process (int entityId);
public abstract void end (int entityId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment