[PI] Hyperion GameEngine - Cycle - EventCore - Saving Cycle
Hey guys ill be leaving the files here to adding the following scripts from hyperion
that have been converted to PI
This took a while so i hope you guys enjoy ^^
Name it CleanupEvent.java
Code:
import server.world.World;
import server.core.event.Event;
import server.core.engine.CleanupTask;
public class CleanupEvent extends Event {
/**
* An event which runs periodically and performs tasks such as garbage
* collection.
* @author Graham Edgecombe
*
*/
/**
* The delay in milliseconds between consecutive cleanups.
*/
public static final int CLEANUP_CYCLE_TIME = 300000;
/**
* Creates the cleanup event to run every 5 minutes.
*/
public CleanupEvent() {
super(CLEANUP_CYCLE_TIME);
}
@Override
public void execute() {
World.getWorld().submit(new CleanupTask());
}
}
Name This SavingEvent.Java
Code:
package server.core.event.impl;
import server.world.World;
import server.core.event.Event;
import server.core.engine.SavePlayers;
import server.model.players.PlayerHandler;
public class SavingEvent extends Event {
public SavingEvent() {
super(120000);
}
@Override
public void execute() {
if (PlayerHandler.playerCount <= 0) {
return;
}
//World.getWorld().submit(new SavePlayers());
}
}
Call it Event.java
Code:
package server.core.event;
public abstract class Event {
/**
* Represents a task that is executed in the future, once or periodically.
* @author Graham Edgecombe
*
*/
/**
* The delay, in milliseconds.
*/
private long delay;
/**
* The running flag.
*/
private boolean running = true;
/**
* Creates an event with the specified delay.
* @param delay The delay.
*/
public Event(long delay) {
this.delay = delay;
}
/**
* Gets the event delay.
* @return The delay, in milliseconds.
*/
public long getDelay() {
return delay;
}
/**
* Sets the event delay.
* @param delay The delay to set.
* @throws IllegalArgumentException if the delay is negative.
*/
public void setDelay(long delay) {
if(delay < 0) {
throw new IllegalArgumentException("Delay must be positive.");
}
this.delay = delay;
}
/**
* Checks if the event is running.
* @return <code>true</code> if the event is still running, <code>false</code> if not.
*/
public boolean isRunning() {
return running;
}
/**
* Stops the event from running in the future.
*/
public void stop() {
running = false;
}
/**
* The execute method is called when the event is run. The general contract
* of the execute method is that it may take any action whatsoever.
*/
public abstract void execute();
}
EventManager.java
Code:
package server.core.event;
import java.util.concurrent.TimeUnit;
import server.core.CycleEngine;
public class EventManager {
/**
* The <code>GameEngine</code> to manager events for.
*/
private CycleEngine engine;
/**
* Creates an <code>EventManager</code> for the specified
* <code>GameEngine</code>.
* @param engine The game engine the manager is managing events for.
*/
public EventManager(CycleEngine engine) {
this.engine = engine;
}
/**
* Submits a new event to the <code>GameEngine</code>.
* @param event The event to submit.
*/
public void submit(final Event event) {
submit(event, event.getDelay());
}
/**
* Schedules an event to run after the specified delay.
* @param event The event.
* @param delay The delay.
*/
private void submit(final Event event, final long delay) {
if (event.isRunning()) {
engine.scheduleLogic(new Runnable() {
@Override
public void run() {
long start = System.nanoTime() / 1000000L;
if(event.isRunning()) {
try {
event.execute();
} catch(Exception e) {
e.printStackTrace();
}
} else {
return;
}
long elapsed = System.nanoTime() / 1000000L - start;
long remaining = event.getDelay() - elapsed;
if(remaining <= 0) {
remaining = 0;
}
try {
submit(event, remaining);
} catch(Exception e) {
e.printStackTrace();
}
}
}, delay, TimeUnit.MILLISECONDS);
}
}
}
CycleEngine.java
Code:
package server.core;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import server.core.engine.Task;
import server.util.BlockingExecutorService;
import server.world.World;
public class CycleEngine implements Runnable {
/**
* The 'core' class of the server which processes all the logic tasks in one
* single logic <code>ExecutorService</code>. This service is scheduled which
* means <code>Event</code>s are also submitted to it.
* @author Graham Edgecombe
*
*/
/**
* A queue of pending tasks.
*/
private final BlockingQueue<Task> tasks = new LinkedBlockingQueue<Task>();
/**
* The logic service.
*/
private final ScheduledExecutorService logicService = Executors.newScheduledThreadPool(1);
/**
* The task service, used by <code>ParallelTask</code>s.
*/
private final BlockingExecutorService taskService = new BlockingExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
/**
* The work service, generally for file I/O and other blocking operations.
*/
private final ExecutorService workService = Executors.newSingleThreadExecutor();
/**
* Running flag.
*/
private boolean running = false;
/**
* Thread instance.
*/
private Thread thread;
/**
* Submits a new task which is processed on the logic thread as soon as
* possible.
* @param task The task to submit.
*/
public void pushTask(Task task) {
tasks.offer(task);
}
/**
* Checks if this <code>GameEngine</code> is running.
* @return <code>true</code> if so, <code>false</code> if not.
*/
public boolean isRunning() {
return running;
}
/**
* Starts the <code>GameEngine</code>'s thread.
*/
public void start() {
if(running) {
throw new IllegalStateException("The engine is already running.");
}
running = true;
thread = new Thread(this);
thread.start();
}
/**
* Stops the <code>GameEngine</code>'s thread.
*/
public void stop() {
if(!running) {
throw new IllegalStateException("The engine is already stopped.");
}
running = false;
thread.interrupt();
}
@Override
public void run() {
try {
while(running) {
try {
final Task task = tasks.take();
submitLogic(new Runnable() {
@Override
public void run() {
task.execute(CycleEngine.this);
}
});
} catch(InterruptedException e) {
continue;
}
}
} finally {
logicService.shutdown();
taskService.shutdown();
workService.shutdown();
}
}
/**
* Schedules a task to run in the logic service.
* @param runnable The runnable.
* @param delay The delay.
* @param unit The time unit.
* @return The <code>ScheduledFuture</code> of the scheduled logic.
*/
public ScheduledFuture<?> scheduleLogic(final Runnable runnable, long delay, TimeUnit unit) {
return logicService.schedule(new Runnable() {
public void run() {
try {
runnable.run();
} catch(Throwable t) {
World.getWorld().handleError(t);
}
}
}, delay, unit);
}
/**
* Submits a task to run in the parallel task service.
* @param runnable The runnable.
*/
public void submitTask(final Runnable runnable) {
taskService.submit(new Runnable() {
public void run() {
try {
runnable.run();
} catch(Throwable t) {
World.getWorld().handleError(t);
}
}
});
}
/**
* Submits a task to run in the work service.
* @param runnable The runnable.
*/
public void submitWork(final Runnable runnable) {
workService.submit(new Runnable() {
public void run() {
try {
runnable.run();
} catch(Throwable t) {
World.getWorld().handleError(t);
}
}
});
}
/**
* Submits a task to run in the logic service.
* @param runnable The runnable.
*/
public void submitLogic(final Runnable runnable) {
logicService.submit(new Runnable() {
public void run() {
try {
runnable.run();
} catch(Throwable t) {
World.getWorld().handleError(t);
}
}
});
}
/**
* Waits for pending parallel tasks.
* @throws ExecutionException If an error occurred during a task.
*/
public void waitForPendingParallelTasks() throws ExecutionException {
taskService.waitForPendingTasks();
}
}
CleanupTask.java
Code:
package server.core.engine;
import server.core.CycleEngine;
import server.core.engine.Task;
/**
* Performs garbage collection and finalization.
* @author Graham Edgecombe
*
*/
public class CleanupTask implements Task {
@Override
public void execute(CycleEngine context) {
context.submitWork(new Runnable() {
public void run() {
//World.getWorld().getMySQLHandler().getHandler().cleanup();
System.gc();
System.runFinalization();
System.gc();
System.out.println("System resources cleaned");
}
});
}
}
SavePlayers.java
Code:
package server.core.engine;
import server.core.CycleEngine;
import server.world.World;
import server.core.engine.Task;
import server.model.players.Player;
import server.model.players.PlayerHandler;
import server.model.players.PlayerSave;
/**
*
* @author Pokemon
*
*/
/*
* 10/2/12
* To do checking the entire game if all the players are saved
*/
public class SavePlayers implements Task {
@Override
public void execute(CycleEngine context) {
if (PlayerHandler.players.length == 0)
return;
try {
for(int i = 0; i < PlayerHandler.players.length; i++) {
if (PlayerHandler.players[i] != null) {
//PlayerSave.saveGame((Player)PlayerHandler.players[i]);
System.out.println("Auto-Saving for "+PlayerHandler.players[i].playerName);
}
}
} catch (Exception e) {
World.getWorld().handleError(e);
}
}
}
Task.java
Code:
package server.core.engine;
import server.core.CycleEngine;
/**
* A task is a class which carries out a unit of work.
* @author Graham Edgecombe
*
*/
public interface Task {
/**
* Executes the task. The general contract of the execute method is that it
* may take any action whatsoever.
* @param context The game engine this task is being executed in.
*/
public void execute(CycleEngine context);
}
CleanupEvent.java
Code:
package server.core.cycle;
import server.world.World;
import server.core.event.Event;
import server.core.engine.CleanupTask;
/**
* An event which runs periodically and performs tasks such as garbage
* collection.
* @author Graham Edgecombe
*
*/
public class CleanupEvent extends Event {
/**
* The delay in milliseconds between consecutive cleanups.
*/
public static final int CLEANUP_CYCLE_TIME = 300000;
/**
* Creates the cleanup event to run every 5 minutes.
*/
public CleanupEvent() {
super(CLEANUP_CYCLE_TIME);
}
@Override
public void execute() {
World.getWorld().submit(new CleanupTask());
}
}
Now put this in server.util
call this BlockingExecutorService.java
Code:
package server.util;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* An <code>ExecutorService</code> that waits for all its events to finish
* executing.
* @author Graham Edgecombe
*
*/
public class BlockingExecutorService implements ExecutorService {
/**
* The service backing this service.
*/
private ExecutorService service;
/**
* A list of pending tasks.
*/
private BlockingQueue<Future<?>> pendingTasks = new LinkedBlockingQueue<Future<?>>();
/**
* Creates the executor service.
* @param service The service backing this service.
*/
public BlockingExecutorService(ExecutorService service) {
this.service = service;
}
/**
* Waits for pending tasks to complete.
* @throws ExecutionException if an error in a task occurred.
*/
public void waitForPendingTasks() throws ExecutionException {
while(pendingTasks.size() > 0) {
if(isShutdown()) {
return;
}
try {
pendingTasks.take().get();
} catch(InterruptedException e) {
continue;
}
}
}
/**
* Gets the number of pending tasks.
* @return The number of pending tasks.
*/
public int getPendingTaskAmount() {
return pendingTasks.size();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return service.awaitTermination(timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
List<Future<T>> futures = service.invokeAll(tasks);
for(Future<?> future : futures) {
pendingTasks.add(future);
}
return futures;
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
List<Future<T>> futures = service.invokeAll(tasks, timeout, unit);
for(Future<?> future : futures) {
pendingTasks.add(future);
}
return futures;
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return service.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return service.invokeAny(tasks, timeout, unit);
}
@Override
public boolean isShutdown() {
return service.isShutdown();
}
@Override
public boolean isTerminated() {
return service.isTerminated();
}
@Override
public void shutdown() {
service.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return service.shutdownNow();
}
@Override
public <T> Future<T> submit(Callable<T> task) {
Future<T> future = service.submit(task);
pendingTasks.add(future);
return future;
}
@Override
public Future<?> submit(Runnable task) {
Future<?> future = service.submit(task);
pendingTasks.add(future);
return future;
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
Future<T> future = service.submit(task, result);
pendingTasks.add(future);
return future;
}
@Override
public void execute(Runnable command) {
service.execute(command);
}
}
SimplerTimer.java
Code:
public class SimpleTimer {
private long cachedTime;
public SimpleTimer() {
reset();
}
public void reset() {
cachedTime = System.currentTimeMillis();
}
public long elapsed() {
return System.currentTimeMillis() - cachedTime;
}
}
Credits
Pokemon
Rs Wiki
Graham
Jinrake