Formatting, classpath.

This commit is contained in:
Ondřej Hruška
2014-04-01 09:07:33 +02:00
parent 4a1a84fd87
commit 4bd18be9bb
106 changed files with 4802 additions and 4043 deletions
+66 -67
View File
@@ -1,6 +1,5 @@
package mightypork.rogue;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
@@ -31,40 +30,40 @@ import org.lwjgl.input.Keyboard;
* @author MightyPork
*/
public class App implements Destroyable, AppAccess {
/** instance pointer */
private static App inst;
private InputSystem input;
private SoundSystem sounds;
private DisplaySystem display;
private MessageBus events;
/** current screen */
private Screen screen;
/** Flag that screenshot is scheduled to be taken next loop */
private boolean scheduledScreenshot = false;
/**
* @param args
*/
public static void main(String[] args)
{
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
inst = new App();
try {
inst.start();
} catch (Throwable t) {
onCrash(t);
}
}
/**
* Handle a crash
*
@@ -73,19 +72,19 @@ public class App implements Destroyable, AppAccess {
public static void onCrash(Throwable error)
{
Log.e("The game has crashed.", error);
if (inst != null) inst.shutdown();
}
@Override
public void shutdown()
{
destroy();
System.exit(0);
}
public void initialize()
{
Log.i("Initializing subsystems");
@@ -96,8 +95,8 @@ public class App implements Destroyable, AppAccess {
initSound();
initInput();
}
@Override
public void destroy()
{
@@ -105,15 +104,15 @@ public class App implements Destroyable, AppAccess {
if (input != null) input.destroy();
if (display != null) display.destroy();
}
private void initLock()
{
if (!Config.SINGLE_INSTANCE) return;
if (!lockInstance()) {
System.out.println("Working directory is locked.\nOnly one instance can run at a time.");
//@formatter:off
JOptionPane.showMessageDialog(
null,
@@ -122,13 +121,13 @@ public class App implements Destroyable, AppAccess {
JOptionPane.ERROR_MESSAGE
);
//@formatter:on
shutdown();
return;
}
}
private boolean lockInstance()
{
final File lockFile = new File(Paths.WORKDIR, ".lock");
@@ -137,7 +136,7 @@ public class App implements Destroyable, AppAccess {
final FileLock fileLock = randomAccessFile.getChannel().tryLock();
if (fileLock != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run()
{
@@ -159,8 +158,8 @@ public class App implements Destroyable, AppAccess {
}
return false;
}
/**
* initialize inputs
*/
@@ -168,11 +167,11 @@ public class App implements Destroyable, AppAccess {
{
events = new MessageBus();
events.subscribe(this);
events.createChannel(UpdateEvent.class, UpdateEvent.Listener.class);
}
/**
* initialize sound system
*/
@@ -181,17 +180,17 @@ public class App implements Destroyable, AppAccess {
sounds = new SoundSystem(this);
sounds.setMasterVolume(1);
}
/**
* initialize inputs
*/
private void initInput()
{
input = new InputSystem(this);
input.bindKeyStroke(new KeyStroke(Keyboard.KEY_F2), new Runnable() {
@Override
public void run()
{
@@ -199,9 +198,9 @@ public class App implements Destroyable, AppAccess {
scheduledScreenshot = true;
}
});
input.bindKeyStroke(new KeyStroke(false, Keyboard.KEY_F11), new Runnable() {
@Override
public void run()
{
@@ -209,9 +208,9 @@ public class App implements Destroyable, AppAccess {
display.switchFullscreen();
}
});
input.bindKeyStroke(new KeyStroke(Keyboard.KEY_LCONTROL, Keyboard.KEY_Q), new Runnable() {
@Override
public void run()
{
@@ -220,8 +219,8 @@ public class App implements Destroyable, AppAccess {
}
});
}
/**
* initialize display
*/
@@ -231,8 +230,8 @@ public class App implements Destroyable, AppAccess {
display.createMainWindow(Const.WINDOW_W, Const.WINDOW_H, true, Config.START_IN_FS, Const.TITLEBAR);
display.setTargetFps(Const.FPS_RENDER);
}
/**
* initialize main logger
*/
@@ -242,41 +241,41 @@ public class App implements Destroyable, AppAccess {
li.enable(Config.LOGGING_ENABLED);
li.enableSysout(Config.LOG_TO_STDOUT);
}
private void start()
{
initialize();
mainLoop();
shutdown();
}
/** timer */
private TimerDelta timerRender;
private void mainLoop()
{
screen = new ScreenTestAnimations(this);
screen.setActive(true);
timerRender = new TimerDelta();
while (!display.isCloseRequested()) {
display.beginFrame();
events.broadcast(new UpdateEvent(timerRender.getDelta()));
if (scheduledScreenshot) {
takeScreenshot();
scheduledScreenshot = false;
}
display.endFrame();
}
}
/**
* Do take a screenshot
*/
@@ -285,12 +284,12 @@ public class App implements Destroyable, AppAccess {
sounds.getEffect("gui.shutter").play(1);
Utils.runAsThread(new TaskTakeScreenshot(display));
}
//
// static accessors
// static accessors
//
/**
* @return sound system of the running instance
*/
@@ -299,8 +298,8 @@ public class App implements Destroyable, AppAccess {
{
return sounds;
}
/**
* @return input system of the running instance
*/
@@ -309,8 +308,8 @@ public class App implements Destroyable, AppAccess {
{
return input;
}
/**
* @return display system of the running instance
*/
@@ -319,8 +318,8 @@ public class App implements Destroyable, AppAccess {
{
return display;
}
/**
* @return event bus
*/
@@ -329,5 +328,5 @@ public class App implements Destroyable, AppAccess {
{
return events;
}
}
+10 -11
View File
@@ -1,6 +1,5 @@
package mightypork.rogue;
import mightypork.rogue.display.DisplaySystem;
import mightypork.rogue.input.InputSystem;
import mightypork.rogue.sounds.SoundSystem;
@@ -13,35 +12,35 @@ import mightypork.utils.patterns.subscription.MessageBus;
* @author MightyPork
*/
public interface AppAccess {
/**
* @return sound system
*/
abstract SoundSystem snd();
/**
* @return input system
*/
abstract InputSystem input();
/**
* @return display system
*/
abstract DisplaySystem disp();
/**
* @return event bus
*/
abstract MessageBus bus();
/**
* Quit to OS<br>
* Destroy app & exit VM
*/
abstract void shutdown();
}
+15 -16
View File
@@ -1,6 +1,5 @@
package mightypork.rogue;
import mightypork.rogue.display.DisplaySystem;
import mightypork.rogue.input.InputSystem;
import mightypork.rogue.sounds.SoundSystem;
@@ -13,49 +12,49 @@ import mightypork.utils.patterns.subscription.MessageBus;
* @author MightyPork
*/
public class AppAdapter implements AppAccess {
private AppAccess app;
public AppAdapter(AppAccess app) {
if (app == null) throw new NullPointerException("AppAccess instance cannot be null.");
this.app = app;
}
@Override
public final SoundSystem snd()
{
return app.snd();
}
@Override
public final InputSystem input()
{
return app.input();
}
@Override
public final DisplaySystem disp()
{
return app.disp();
}
@Override
public final MessageBus bus()
{
return app.bus();
}
@Override
public void shutdown()
{
app.shutdown();
}
}
+21 -22
View File
@@ -1,6 +1,5 @@
package mightypork.rogue;
import mightypork.utils.files.PropertyManager;
import mightypork.utils.logging.Log;
@@ -11,42 +10,42 @@ import mightypork.utils.logging.Log;
* @author MightyPork
*/
public class Config {
private static PropertyManager mgr;
// opts
public static final int def_LAST_RUN_VERSION = 0;
public static int LAST_RUN_VERSION;
public static final boolean def_START_IN_FS = false;
public static boolean START_IN_FS;
// property keys
private static final String PK_LAST_RUN_VERSION = "status.last_run_version";
private static final String PK_START_IN_FS = "cfg.start_in_fullscreen";
/**
* Prepare config manager and load user settings
*/
public static void init()
{
Log.f2("Initializing configuration manager.");
String comment = Const.APP_NAME + " config file";
mgr = new PropertyManager(Paths.CONFIG, comment);
mgr.cfgNewlineBeforeComments(true);
mgr.cfgSeparateSections(true);
mgr.putInteger(PK_LAST_RUN_VERSION, def_LAST_RUN_VERSION);
mgr.putBoolean(PK_START_IN_FS, def_START_IN_FS);
load(); // load what has been "put"
}
/**
* Save changed fields to config file
*/
@@ -54,28 +53,28 @@ public class Config {
{
mgr.setValue(PK_LAST_RUN_VERSION, Const.VERSION);
mgr.setValue(PK_START_IN_FS, START_IN_FS);
mgr.apply();
}
/**
* Load config file and assign values to fields
*/
public static void load()
{
mgr.apply();
LAST_RUN_VERSION = mgr.getInteger(PK_LAST_RUN_VERSION);
START_IN_FS = mgr.getBoolean(PK_START_IN_FS);
}
// options that can't be configured via config file
public static boolean LOGGING_ENABLED = true;
public static boolean LOG_TO_STDOUT = true;
public static boolean SINGLE_INSTANCE = true;
public static boolean LOG_FONTS = false;
}
+4 -5
View File
@@ -1,23 +1,22 @@
package mightypork.rogue;
/**
* Application constants
*
* @author MightyPork
*/
public class Const {
// STRINGS
public static final int VERSION = 1;
public static final String APP_NAME = "Rogue";
public static final String TITLEBAR = APP_NAME + " v." + VERSION;
// AUDIO
public static final int FPS_RENDER = 200; // max
public static final long FPS_GUI_UPDATE = 60;
// INITIAL WINDOW SIZE
public static final int WINDOW_W = 1024;
public static final int WINDOW_H = 768;
+2 -3
View File
@@ -1,16 +1,15 @@
package mightypork.rogue;
import java.lang.Thread.UncaughtExceptionHandler;
public class CrashHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e)
{
e.printStackTrace();
App.onCrash(e);
}
}
+4 -5
View File
@@ -1,22 +1,21 @@
package mightypork.rogue;
import java.io.File;
import mightypork.utils.files.OsUtils;
public class Paths {
private static final String APPDIR_NAME = "rogue";
public static final File WORKDIR = OsUtils.getWorkDir(APPDIR_NAME);
public static final File LOGS = OsUtils.getWorkDir(APPDIR_NAME, "logs");
public static final File SCREENSHOTS = OsUtils.getWorkDir(APPDIR_NAME, "screenshots");
public static final File CONFIG = new File(WORKDIR, "config.ini");
public static final String DIR_EFFECTS = "res/sounds/effects/";
public static final String DIR_MUSIC = "res/sounds/music/";
public static final String DIR_LOOPS = "res/sounds/loops/";
}
@@ -1,6 +1,5 @@
package mightypork.rogue.bus;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@@ -23,25 +22,25 @@ import mightypork.utils.time.Updateable;
* @author MightyPork
*/
public abstract class DelegatingBusClient extends AppAdapter implements DelegatingClient, ToggleableClient, Destroyable, Updateable, UpdateEvent.Listener {
/** Subsystem children subscribing to MessageBus */
private Set<Object> childSubscribers = new HashSet<Object>();
private boolean wantUpdates = true;
private boolean eventsEnabled = true;
public DelegatingBusClient(AppAccess app, boolean updates) {
super(app);
bus().subscribe(this);
enableUpdates(updates);
init();
}
/**
* Add a child subscriber to the {@link MessageBus}.<br>
*
@@ -51,40 +50,41 @@ public abstract class DelegatingBusClient extends AppAdapter implements Delegati
public final boolean addChildSubscriber(Object client)
{
if (client == null) return false;
childSubscribers.add(client);
return true;
}
/**
* Remove a child subscriber
*
* @param client subscriber to remove
* @param client
* subscriber to remove
*/
public final void removeChildSubscriber(Object client)
{
if (client == null) return;
childSubscribers.remove(client);
}
@Override
public final Collection<Object> getChildClients()
{
return childSubscribers;
}
@Override
public final boolean doesDelegate()
{
return doesSubscribe();
}
/**
* Set whether to receive {@link UpdateEvent}s (delta timing, one each
* frame).<br>
@@ -95,15 +95,15 @@ public abstract class DelegatingBusClient extends AppAdapter implements Delegati
{
wantUpdates = enable;
}
@Override
public final boolean doesSubscribe()
{
return eventsEnabled;
}
/**
* Set whether events should be received.
*
@@ -113,33 +113,33 @@ public abstract class DelegatingBusClient extends AppAdapter implements Delegati
{
this.eventsEnabled = enable;
}
@Override
public final void receive(UpdateEvent event)
{
if (wantUpdates) update(event.getDeltaTime());
}
@Override
public final void destroy()
{
deinit();
enableUpdates(false);
bus().unsubscribe(this);
}
@Override
public void update(double delta)
{
Log.w("Client " + getClass().getSimpleName() + " receives updates, but does not override the update() method.");
}
/**
* Initialize the subsystem<br>
* (called during construction)
@@ -148,8 +148,8 @@ public abstract class DelegatingBusClient extends AppAdapter implements Delegati
{
// no impl
}
/**
* Deinitialize the subsystem<br>
* (called during destruction)
@@ -158,5 +158,5 @@ public abstract class DelegatingBusClient extends AppAdapter implements Delegati
{
// no impl
}
}
@@ -1,6 +1,5 @@
package mightypork.rogue.bus;
import mightypork.rogue.AppAccess;
import mightypork.rogue.AppAdapter;
@@ -11,13 +10,14 @@ import mightypork.rogue.AppAdapter;
* @author MightyPork
*/
public class SimpleBusClient extends AppAdapter {
/**
* @param app app access
* @param app
* app access
*/
public SimpleBusClient(AppAccess app) {
super(app);
bus().subscribe(this);
}
}
+6 -7
View File
@@ -1,26 +1,25 @@
package mightypork.rogue.bus;
import mightypork.rogue.AppAccess;
import mightypork.rogue.bus.events.UpdateEvent;
import mightypork.utils.time.Updateable;
public abstract class UpdateReceiver extends SimpleBusClient implements UpdateEvent.Listener, Updateable {
public UpdateReceiver(AppAccess app) {
super(app);
}
@Override
public void receive(UpdateEvent event)
{
update(event.getDeltaTime());
}
@Override
public abstract void update(double delta);
}
@@ -1,6 +1,5 @@
package mightypork.rogue.bus.events;
import mightypork.utils.patterns.subscription.Handleable;
import org.lwjgl.input.Keyboard;
@@ -12,19 +11,19 @@ import org.lwjgl.input.Keyboard;
* @author MightyPork
*/
public class KeyboardEvent implements Handleable<KeyboardEvent.Listener> {
private int key;
private boolean down;
private char c;
public KeyboardEvent(int key, char c, boolean down) {
this.key = key;
this.c = c;
this.down = down;
}
/**
* @return key code (see {@link org.lwjgl.input.Keyboard})
*/
@@ -32,8 +31,8 @@ public class KeyboardEvent implements Handleable<KeyboardEvent.Listener> {
{
return key;
}
/**
* @return true if key was just pressed
*/
@@ -41,8 +40,8 @@ public class KeyboardEvent implements Handleable<KeyboardEvent.Listener> {
{
return down;
}
/**
* @return true if key was just released
*/
@@ -50,8 +49,8 @@ public class KeyboardEvent implements Handleable<KeyboardEvent.Listener> {
{
return !down;
}
/**
* @return event character (if any)
*/
@@ -59,29 +58,31 @@ public class KeyboardEvent implements Handleable<KeyboardEvent.Listener> {
{
return c;
}
@Override
public void handleBy(Listener keh)
{
keh.receive(this);
}
public interface Listener {
/**
* Handle an event
*
* @param event event
* @param event
* event
*/
public void receive(KeyboardEvent event);
}
@Override
public String toString()
{
return Keyboard.getKeyName(key) + ":" + (down ? "DOWN" : "UP");
}
}
@@ -1,6 +1,5 @@
package mightypork.rogue.bus.events;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.patterns.subscription.Handleable;
@@ -11,24 +10,28 @@ import mightypork.utils.patterns.subscription.Handleable;
* @author MightyPork
*/
public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
public static final int BUTTON_LEFT = 0;
public static final int BUTTON_MIDDLE = 1;
public static final int BUTTON_RIGHT = 2;
private int button;
private int wheeld;
private Coord pos;
private boolean down;
/**
* Mouse button event
*
* @param pos event position
* @param button button id
* @param down button pressed
* @param wheeld wheel change
* @param pos
* event position
* @param button
* button id
* @param down
* button pressed
* @param wheeld
* wheel change
*/
public MouseButtonEvent(Coord pos, int button, boolean down, int wheeld) {
this.button = button;
@@ -36,8 +39,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
this.pos = pos;
this.wheeld = wheeld;
}
/**
* @return true if the event was caused by a button state change
*/
@@ -45,8 +48,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return button != -1;
}
/**
* @return true if the event was caused by a wheel change
*/
@@ -54,8 +57,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return wheeld != 0;
}
/**
* @return button id or -1 if none was pressed
*/
@@ -63,8 +66,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return button;
}
/**
* @return number of steps the wheel changed since last event
*/
@@ -72,8 +75,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return wheeld;
}
/**
* @return mouse position when the event occurred
*/
@@ -81,8 +84,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return pos;
}
/**
* @return true if button was just pressed
*/
@@ -90,8 +93,8 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return button != -1 && down;
}
/**
* @return true if button was just released
*/
@@ -99,20 +102,22 @@ public class MouseButtonEvent implements Handleable<MouseButtonEvent.Listener> {
{
return button != -1 && !down;
}
@Override
public void handleBy(Listener handler)
{
handler.receive(this);
}
public interface Listener {
/**
* Handle an event
*
* @param event event
* @param event
* event
*/
public void receive(MouseButtonEvent event);
}
@@ -1,22 +1,21 @@
package mightypork.rogue.bus.events;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.patterns.subscription.Handleable;
public class MouseMotionEvent implements Handleable<MouseMotionEvent.Listener> {
private Coord move;
private Coord pos;
public MouseMotionEvent(Coord pos, Coord move) {
this.move = move;
this.pos = pos;
}
/**
* @return movement since last {@link MouseMotionEvent}
*/
@@ -24,8 +23,8 @@ public class MouseMotionEvent implements Handleable<MouseMotionEvent.Listener> {
{
return move;
}
/**
* @return current mouse position
*/
@@ -33,22 +32,24 @@ public class MouseMotionEvent implements Handleable<MouseMotionEvent.Listener> {
{
return pos;
}
@Override
public void handleBy(Listener keh)
{
keh.receive(this);
}
public interface Listener {
/**
* Handle an event
*
* @param event event
* @param event
* event
*/
public void receive(MouseMotionEvent event);
}
}
@@ -1,50 +1,50 @@
package mightypork.rogue.bus.events;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.patterns.subscription.Handleable;
public class ScreenChangeEvent implements Handleable<ScreenChangeEvent.Listener> {
private boolean fullscreen;
private Coord screenSize;
private boolean fsChanged;
public ScreenChangeEvent(boolean fsChanged, boolean fullscreen, Coord size) {
this.fullscreen = fullscreen;
this.screenSize = size;
this.fsChanged = fsChanged;
}
public boolean isFullscreen()
{
return fullscreen;
}
public boolean fullscreenChanged()
{
return fsChanged;
}
public Coord getScreenSize()
{
return screenSize;
}
@Override
public void handleBy(Listener handler)
{
handler.receive(this);
}
public interface Listener {
public void receive(ScreenChangeEvent event);
}
}
@@ -1,33 +1,33 @@
package mightypork.rogue.bus.events;
import mightypork.utils.patterns.subscription.Handleable;
public class UpdateEvent implements Handleable<UpdateEvent.Listener> {
private final double deltaTime;
public UpdateEvent(double deltaTime) {
this.deltaTime = deltaTime;
}
public double getDeltaTime()
{
return deltaTime;
}
@Override
public void handleBy(Listener handler)
{
handler.receive(this);
}
public interface Listener {
public void receive(UpdateEvent event);
}
}
+40 -40
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.display;
import static org.lwjgl.opengl.GL11.*;
import java.awt.image.BufferedImage;
@@ -21,31 +20,31 @@ import org.lwjgl.opengl.DisplayMode;
public class DisplaySystem extends DelegatingBusClient implements Bounding {
private DisplayMode windowDisplayMode;
private int targetFps;
public DisplaySystem(AppAccess app) {
super(app, true);
enableUpdates(false);
}
@Override
protected void init()
{
initChannels();
}
@Override
public void deinit()
{
Display.destroy();
}
/**
* Initialize event channels
*/
@@ -53,14 +52,14 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
{
bus().createChannel(ScreenChangeEvent.class, ScreenChangeEvent.Listener.class);
}
public void setTargetFps(int fps)
{
this.targetFps = fps;
}
public void createMainWindow(int width, int height, boolean resizable, boolean fullscreen, String title)
{
try {
@@ -69,7 +68,7 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
Display.setVSyncEnabled(true);
Display.setTitle(title);
Display.create();
if (fullscreen) {
switchFullscreen();
Display.update();
@@ -78,20 +77,20 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
throw new RuntimeException("Could not initialize screen", e);
}
}
/**
* Toggle FS if possible
*/
public void switchFullscreen()
{
try {
if (!Display.isFullscreen()) {
Log.f3("Entering fullscreen.");
// save window resize
windowDisplayMode = new DisplayMode(Display.getWidth(), Display.getHeight());
Display.setDisplayMode(Display.getDesktopDisplayMode());
Display.setFullscreen(true);
Display.update();
@@ -100,9 +99,9 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
Display.setDisplayMode(windowDisplayMode);
Display.update();
}
bus().broadcast(new ScreenChangeEvent(true, Display.isFullscreen(), getSize()));
} catch (Throwable t) {
Log.e("Failed to toggle fullscreen mode.", t);
try {
@@ -113,19 +112,20 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
}
}
}
public BufferedImage takeScreenshot()
{
glReadBuffer(GL_FRONT);
int width = Display.getDisplayMode().getWidth();
int height = Display.getDisplayMode().getHeight();
int bpp = 4; // Assuming a 32-bit display with a byte each for red, green, blue, and alpha.
int bpp = 4; // Assuming a 32-bit display with a byte each for red,
// green, blue, and alpha.
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// convert to a buffered image
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
@@ -136,11 +136,11 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
}
}
return image;
}
/**
* @return true if close was requested (i.e. click on cross)
*/
@@ -148,8 +148,8 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
{
return Display.isCloseRequested();
}
/**
* Get fullscreen state
*
@@ -159,8 +159,8 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
{
return Display.isFullscreen();
}
/**
* Get screen size
*
@@ -170,8 +170,8 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
{
return new Coord(Display.getWidth(), Display.getHeight());
}
/**
* Start a OpenGL frame
*/
@@ -180,12 +180,12 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
if (Display.wasResized()) {
bus().broadcast(new ScreenChangeEvent(false, Display.isFullscreen(), getSize()));
}
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
/**
* End an OpenGL frame, flip buffers, sync to fps.
*/
@@ -194,8 +194,8 @@ public class DisplaySystem extends DelegatingBusClient implements Bounding {
Display.update(false); // don't poll input devices
Display.sync(targetFps);
}
@Override
public Rect getRect()
{
+69 -67
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.display;
import static org.lwjgl.opengl.GL11.*;
import mightypork.rogue.AppAccess;
import mightypork.rogue.bus.DelegatingBusClient;
@@ -21,38 +20,39 @@ import mightypork.utils.math.coord.Rect;
* @author MightyPork
*/
public abstract class Screen extends DelegatingBusClient implements KeyBinder, Bounding, ScreenChangeEvent.Listener {
private KeyBindingPool keybindings;
private boolean active;
public Screen(AppAccess app) {
super(app, true);
// disable events initially
enableEvents(false);
}
@Override
public final void bindKeyStroke(KeyStroke stroke, Runnable task)
{
keybindings.bindKeyStroke(stroke, task);
}
@Override
public final void unbindKeyStroke(KeyStroke stroke)
{
keybindings.unbindKeyStroke(stroke);
}
/**
* Prepare for being shown
*
* @param shown true to show, false to hide
* @param shown
* true to show, false to hide
*/
public final void setActive(boolean shown)
{
@@ -62,45 +62,45 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
setupViewport();
onSizeChanged(getRect().getSize());
onScreenEnter();
// subscribe to event bus
enableEvents(true);
} else {
onScreenLeave();
active = false;
// unsusbcribe from event bus
enableEvents(false);
}
}
private void setupGraphics()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_LIGHTING);
glClearDepth(1f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_TEXTURE_2D);
setupViewport();
}
private void setupViewport()
{
// fix projection for changed size
@@ -109,80 +109,82 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
Coord s = disp().getSize();
glViewport(0, 0, s.xi(), s.yi());
glOrtho(0, s.x, 0, s.y, -1000, 1000);
// back to modelview
glMatrixMode(GL_MODELVIEW);
}
@Override
protected final void init()
{
keybindings = new KeyBindingPool();
addChildSubscriber(keybindings);
initScreen();
}
@Override
protected final void deinit()
{
deinitScreen();
}
/**
* Initialize screen layout and key bindings.<br>
* Called during screen construction.
*/
protected abstract void initScreen();
/**
* Clean up before screen is destroyed.
*/
protected abstract void deinitScreen();
/**
* Called when the screen becomes active
*/
protected abstract void onScreenEnter();
/**
* Called when the screen is no longer active
*/
protected abstract void onScreenLeave();
/**
* Update GUI for new screen size
*
* @param size screen size
* @param size
* screen size
*/
protected void onSizeChanged(Coord size)
{
// no impl
}
/**
* Render screen contents (context is ready for 2D rendering)
*/
protected abstract void renderScreen();
/**
* Update animations and timing
*
* @param delta time elapsed
* @param delta
* time elapsed
*/
protected abstract void updateScreen(double delta);
/**
* Render screen
*/
@@ -191,8 +193,8 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
glPushAttrib(GL_ENABLE_BIT);
glPushMatrix();
}
/**
* Render screen
*/
@@ -201,8 +203,8 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
glPopAttrib();
glPopMatrix();
}
/**
* @return true if screen is the curretn screen
*/
@@ -210,19 +212,19 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
{
return active;
}
@Override
public final void receive(ScreenChangeEvent event)
{
if (!isActive()) return;
setupViewport();
onSizeChanged(event.getScreenSize());
}
/**
* Update and render the screen
*/
@@ -230,17 +232,17 @@ public abstract class Screen extends DelegatingBusClient implements KeyBinder, B
public final void update(double delta)
{
updateScreen(delta);
renderBegin();
renderScreen();
renderEnd();
}
@Override
public final Rect getRect()
{
return disp().getRect();
}
}
@@ -1,6 +1,5 @@
package mightypork.rogue.display;
import java.util.Random;
import mightypork.rogue.AppAccess;
@@ -19,15 +18,15 @@ import org.lwjgl.opengl.Display;
public class ScreenTestAnimations extends Screen implements MouseButtonEvent.Listener {
public ScreenTestAnimations(AppAccess app) {
super(app);
}
private Random rand = new Random();
private AnimDoubleDeg degAnim = new AnimDoubleDeg(0, Easing.ELASTIC_OUT);
//@formatter:off
private AnimDouble[] anims = new AnimDouble[] {
new AnimDouble(0, Easing.BOUNCE_OUT),
@@ -95,12 +94,12 @@ public class ScreenTestAnimations extends Screen implements MouseButtonEvent.Lis
// new AnimDouble(0, Easing.ELASTIC_IN_OUT),
};
//@formatter:on
@Override
public void initScreen()
{
bindKeyStroke(new KeyStroke(Keyboard.KEY_RIGHT), new Runnable() {
@Override
public void run()
{
@@ -109,9 +108,9 @@ public class ScreenTestAnimations extends Screen implements MouseButtonEvent.Lis
}
}
});
bindKeyStroke(new KeyStroke(Keyboard.KEY_LEFT), new Runnable() {
@Override
public void run()
{
@@ -121,40 +120,40 @@ public class ScreenTestAnimations extends Screen implements MouseButtonEvent.Lis
}
});
}
@Override
protected void deinitScreen()
{
// no impl
}
@Override
protected void onScreenEnter()
{
// no impl
}
@Override
protected void onScreenLeave()
{
// no impl
}
@Override
protected void updateScreen(double delta)
{
degAnim.update(delta);
for (AnimDouble a : anims) {
a.update(delta);
}
}
@Override
protected void renderScreen()
{
@@ -163,31 +162,31 @@ public class ScreenTestAnimations extends Screen implements MouseButtonEvent.Lis
double perBoxH = screenH / anims.length;
double padding = perBoxH * 0.1;
double boxSide = perBoxH - padding * 2;
for (int i = 0; i < anims.length; i++) {
AnimDouble a = anims[i];
RenderUtils.setColor(RGB.GREEN);
RenderUtils.quadSize(padding + a.getCurrentValue() * (screenW - perBoxH), screenH - perBoxH * i - perBoxH + padding, boxSide, boxSide);
}
RenderUtils.setColor(RGB.YELLOW);
RenderUtils.translate(new Coord(Display.getWidth() / 2, Display.getHeight() / 2));
RenderUtils.rotateZ(degAnim.getCurrentValue());
RenderUtils.quadSize(-10, -10, 20, 200);
}
@Override
public void receive(MouseButtonEvent event)
{
if (event.isDown()) {
Coord vec = disp().getSize().half().vecTo(event.getPos());
Polar p = Polar.fromCoord(vec);
degAnim.fadeTo(p.getAngleDeg() - 90, 1.5);
}
}
}
@@ -1,6 +1,5 @@
package mightypork.rogue.display.constraints;
import mightypork.utils.math.coord.Rect;
@@ -10,7 +9,7 @@ import mightypork.utils.math.coord.Rect;
* @author MightyPork
*/
public interface Bounding {
/**
* @return bounding rectangle
*/
@@ -1,20 +1,19 @@
package mightypork.rogue.display.constraints;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.math.coord.Rect;
public abstract class Constraint implements Bounding {
protected Bounding context;
public Constraint(Bounding context) {
this.context = context;
}
/**
* Assign a context
*
@@ -24,8 +23,8 @@ public abstract class Constraint implements Bounding {
{
this.context = context;
}
/**
* @return context
*/
@@ -33,8 +32,8 @@ public abstract class Constraint implements Bounding {
{
return context;
}
/**
* @return context rect origin
*/
@@ -42,8 +41,8 @@ public abstract class Constraint implements Bounding {
{
return context.getRect().getOrigin();
}
/**
* @return context rect size
*/
@@ -51,9 +50,9 @@ public abstract class Constraint implements Bounding {
{
return context.getRect().getSize();
}
@Override
public abstract Rect getRect();
}
@@ -1,8 +1,7 @@
package mightypork.rogue.display.rendering;
public interface Renderable {
public void render();
}
@@ -1,18 +1,17 @@
package mightypork.rogue.display.rendering;
import mightypork.rogue.AppAccess;
import mightypork.rogue.bus.DelegatingBusClient;
public abstract class ScreenLayer extends DelegatingBusClient implements Renderable {
public ScreenLayer(AppAccess app) {
super(app, true);
}
@Override
public abstract void render();
}
+2 -3
View File
@@ -1,13 +1,12 @@
package mightypork.rogue.fonts;
/**
* Alignment
*
* @author MightyPork
*/
public class Align {
public static final int LEFT = -1;
public static final int RIGHT = 1;
public static final int TOP = 1;
@@ -16,5 +15,5 @@ public class Align {
public static final int DOWN = -1;
public static final int CENTER = 0;
public static final int MIDDLE = 0;
}
+151 -132
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.fonts;
import java.awt.Font;
import java.io.InputStream;
import java.util.HashMap;
@@ -18,16 +17,17 @@ import org.newdawn.slick.util.ResourceLoader;
* @author MightyPork
*/
public class FontManager {
private static final boolean DEBUG = Config.LOG_FONTS;
/**
* Glyph tables.
*
* @author MightyPork
*/
public static class Glyphs {
//@formatter:off
/** all glyphs */
public static final String all =
@@ -74,14 +74,14 @@ public class FontManager {
public static final String basic = alnum + signs;
//@formatter:on
}
/**
* Font style
*
* @author MightyPork
*/
public static enum Style
{
public static enum Style {
/** Normal */
NORMAL,
/** Italic */
@@ -111,98 +111,102 @@ public class FontManager {
/** Outline variant of normal */
OUTLINE;
}
// /**
// * Preloaded font identifier [name, size, style]
// *
// * @author MightyPork
// */
// public static class FontId {
//
// /** font size (pt) */
// public float size = 24;
// /** font name, registered with registerFile */
// public String name = "";
// /** font style. The given style must be in a file. */
// public Style style;
//
// /** Set of glyphs in this ID */
// public String glyphs = "";
//
// /** Index for faster comparision of glyph ids. */
// public int glyphset_id = 0;
//
//
// /**
// * Preloaded font identifier
// *
// * @param name font name (registerFile)
// * @param size font size (pt)
// * @param style font style
// * @param glyphs glyphs to load
// */
// public FontId(String name, double size, Style style, String glyphs) {
// this.name = name;
// this.size = (float) size;
// this.style = style;
//
// if (glyphs.equals(Glyphs.basic)) {
// glyphset_id = 1;
// } else if (glyphs.equals(Glyphs.alnum)) {
// glyphset_id = 2;
// } else if (glyphs.equals(Glyphs.basic_text)) {
// glyphset_id = 3;
// } else if (glyphs.equals(Glyphs.numbers)) {
// glyphset_id = 4;
// } else if (glyphs.equals(Glyphs.alpha)) {
// glyphset_id = 5;
// } else if (glyphs.equals(Glyphs.all)) {
// glyphset_id = 6;
// } else if (glyphs.equals(Glyphs.alnum_extra)) {
// glyphset_id = 7;
// } else if (glyphs.equals(Glyphs.signs)) {
// glyphset_id = 8;
// } else if (glyphs.equals(Glyphs.signs_extra)) {
// glyphset_id = 9;
// } else {
// this.glyphs = glyphs;
// }
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (obj == null) return false;
// if (!(obj.getClass().isAssignableFrom(getClass()))) return false;
// if (obj instanceof FontId) {
// if (obj == this) return true;
// FontId id2 = ((FontId) obj);
// boolean flag = true;
// flag &= id2.size == size;
// flag &= id2.name.equals(name);
// flag &= id2.style == style;
// flag &= ((id2.glyphset_id != -1 && id2.glyphset_id == glyphset_id) || id2.glyphs.equals(glyphs));
// return flag;
// }
// return false;
// }
//
//
// @Override
// public int hashCode()
// {
// return (new Float(size).hashCode()) ^ name.hashCode() ^ style.hashCode() ^ glyphset_id;
// }
//
//
// @Override
// public String toString()
// {
// return "[" + name + ", " + size + ", " + style + (glyphset_id > 0 ? ", g=" + glyphset_id : ", g=custom") + "]";
// }
// }
// /**
// * Preloaded font identifier [name, size, style]
// *
// * @author MightyPork
// */
// public static class FontId {
//
// /** font size (pt) */
// public float size = 24;
// /** font name, registered with registerFile */
// public String name = "";
// /** font style. The given style must be in a file. */
// public Style style;
//
// /** Set of glyphs in this ID */
// public String glyphs = "";
//
// /** Index for faster comparision of glyph ids. */
// public int glyphset_id = 0;
//
//
// /**
// * Preloaded font identifier
// *
// * @param name font name (registerFile)
// * @param size font size (pt)
// * @param style font style
// * @param glyphs glyphs to load
// */
// public FontId(String name, double size, Style style, String glyphs) {
// this.name = name;
// this.size = (float) size;
// this.style = style;
//
// if (glyphs.equals(Glyphs.basic)) {
// glyphset_id = 1;
// } else if (glyphs.equals(Glyphs.alnum)) {
// glyphset_id = 2;
// } else if (glyphs.equals(Glyphs.basic_text)) {
// glyphset_id = 3;
// } else if (glyphs.equals(Glyphs.numbers)) {
// glyphset_id = 4;
// } else if (glyphs.equals(Glyphs.alpha)) {
// glyphset_id = 5;
// } else if (glyphs.equals(Glyphs.all)) {
// glyphset_id = 6;
// } else if (glyphs.equals(Glyphs.alnum_extra)) {
// glyphset_id = 7;
// } else if (glyphs.equals(Glyphs.signs)) {
// glyphset_id = 8;
// } else if (glyphs.equals(Glyphs.signs_extra)) {
// glyphset_id = 9;
// } else {
// this.glyphs = glyphs;
// }
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (obj == null) return false;
// if (!(obj.getClass().isAssignableFrom(getClass()))) return false;
// if (obj instanceof FontId) {
// if (obj == this) return true;
// FontId id2 = ((FontId) obj);
// boolean flag = true;
// flag &= id2.size == size;
// flag &= id2.name.equals(name);
// flag &= id2.style == style;
// flag &= ((id2.glyphset_id != -1 && id2.glyphset_id == glyphset_id) ||
// id2.glyphs.equals(glyphs));
// return flag;
// }
// return false;
// }
//
//
// @Override
// public int hashCode()
// {
// return (new Float(size).hashCode()) ^ name.hashCode() ^ style.hashCode()
// ^ glyphset_id;
// }
//
//
// @Override
// public String toString()
// {
// return "[" + name + ", " + size + ", " + style + (glyphset_id > 0 ?
// ", g=" + glyphset_id : ", g=custom") + "]";
// }
// }
/**
* Group of styles of one font.
*
@@ -210,19 +214,22 @@ public class FontManager {
*/
public static class FontFamily extends HashMap<Style, String> {
}
/**
* Table of font files. name {style:file,style:file,style:file...}
*/
private static HashMap<String, FontFamily> fontFiles = new HashMap<String, FontFamily>();
/**
* Register font file.
*
* @param path resource path (res/fonts/...)
* @param name font name (for binding)
* @param style font style in this file
* @param path
* resource path (res/fonts/...)
* @param name
* font name (for binding)
* @param style
* font style in this file
*/
public static void registerFile(String path, String name, Style style)
{
@@ -232,47 +239,59 @@ public class FontManager {
return;
}
}
// insert new table of styles to font name.
FontFamily family = new FontFamily();
family.put(style, path);
fontFiles.put(name, family);
}
/** Counter of loaded fonts */
public static int loadedFontCounter = 0;
/**
* Preload font if needed, get preloaded font.<br>
* If needed file is not available, throws runtime exception.
*
* @param name font name (registerFile)
* @param size font size (pt)
* @param style font style
* @param glyphs glyphs needed
* @param name
* font name (registerFile)
* @param size
* font size (pt)
* @param style
* font style
* @param glyphs
* glyphs needed
* @return the loaded font.
*/
public static LoadedFont loadFont(String name, double size, Style style, String glyphs)
{
return loadFont(name, size, style, glyphs, 9, 8, Coord.one(), 0, 0);
}
/**
* Preload font if needed, get preloaded font.<br>
* If needed file is not available, throws runtime exception.
*
* @param name font name (registerFile)
* @param size font size (pt)
* @param style font style
* @param glyphs glyphs needed
* @param correctLeft left horizontal correction
* @param correctRight right horizontal correction
* @param scale font scale (changing aspect ratio)
* @param clipTop top clip (0-1) - top part of the font to be cut off
* @param clipBottom bottom clip (0-1) - bottom part of the font to be cut
* off
* @param name
* font name (registerFile)
* @param size
* font size (pt)
* @param style
* font style
* @param glyphs
* glyphs needed
* @param correctLeft
* left horizontal correction
* @param correctRight
* right horizontal correction
* @param scale
* font scale (changing aspect ratio)
* @param clipTop
* top clip (0-1) - top part of the font to be cut off
* @param clipBottom
* bottom clip (0-1) - bottom part of the font to be cut off
* @return the loaded font.
*/
public static LoadedFont loadFont(String name, double size, Style style, String glyphs, int correctLeft, int correctRight, Coord scale, double clipTop, double clipBottom)
@@ -290,9 +309,9 @@ public class FontManager {
} catch (NullPointerException npe) {
throw new RuntimeException("Font loading failed: no font file registered for name \"" + name + "\".");
}
InputStream in = ResourceLoader.getResourceAsStream(resourcePath);
Font awtFont;
try {
awtFont = Font.createFont(Font.TRUETYPE_FONT, in);
@@ -300,18 +319,18 @@ public class FontManager {
Log.e("Loading of font " + resourcePath + " failed.", e);
throw new RuntimeException(e);
}
awtFont = awtFont.deriveFont((float) size); // set font size
LoadedFont font = new LoadedFont(awtFont, true, glyphs);
font.setCorrection(correctLeft, correctRight);
font.setClip(clipTop, clipBottom);
font.setScale(scale.x, scale.y);
loadedFontCounter++;
if (DEBUG) Log.f3("Font from file \"" + resourcePath + "\" preloaded.");
return font;
}
}
+11 -12
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.fonts;
import static mightypork.rogue.fonts.FontManager.Style.*;
import mightypork.rogue.fonts.FontManager.Glyphs;
import mightypork.utils.logging.Log;
@@ -12,9 +11,9 @@ import mightypork.utils.logging.Log;
* @author Rapus
*/
public class Fonts {
public static LoadedFont splash_info;
public static LoadedFont tooltip;
public static LoadedFont gui;
public static LoadedFont gui_title;
@@ -22,26 +21,26 @@ public class Fonts {
public static LoadedFont menu_button;
public static LoadedFont menu_title;
public static LoadedFont tiny;
private static void registerFileNames()
{
FontManager.registerFile("res/fonts/4feb.ttf", "4feb", NORMAL);
}
/**
* Load fonts needed for splash.
*/
public static void loadForSplash()
{
registerFileNames();
gui = FontManager.loadFont("4feb", 24, NORMAL, Glyphs.basic).setCorrection(8, 7);
splash_info = FontManager.loadFont("4feb", 42, NORMAL, "Loading.");
}
/**
* Preload all fonts we will use in the game
*/
@@ -53,8 +52,8 @@ public class Fonts {
menu_title = FontManager.loadFont("4feb", 34, NORMAL, Glyphs.basic_text);
program_number = FontManager.loadFont("4feb", 28, NORMAL, Glyphs.numbers);
tiny = FontManager.loadFont("4feb", 20, NORMAL, Glyphs.basic_text);
Log.i("Fonts loaded = " + FontManager.loadedFontCounter);
}
}
+163 -153
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.fonts;
import static mightypork.rogue.fonts.Align.*;
import static org.lwjgl.opengl.GL11.*;
@@ -39,82 +38,83 @@ import org.lwjgl.util.glu.GLU;
* @new version edited by MightyPork
*/
public class LoadedFont {
private static final boolean DEBUG = Config.LOG_FONTS;
/** Map of user defined font characters (Character <-> IntObject) */
private Map<Character, CharStorageEntry> chars = new HashMap<Character, CharStorageEntry>(100);
/** Boolean flag on whether AntiAliasing is enabled or not */
private boolean antiAlias;
/** Font's size */
private int fontSize = 0;
/** Font's height */
private int fontHeight = 0;
/** Texture used to cache the font 0-255 characters */
private int fontTextureID;
/** Default font texture width */
private int textureWidth = 2048;
/** Default font texture height */
private int textureHeight = 2048;
/** A reference to Java's AWT Font that we create our font texture from */
private Font font;
/** The font metrics for our Java AWT font */
private FontMetrics fontMetrics;
private int correctL = 9, correctR = 8;
private double defScaleX = 1, defScaleY = 1;
private double clipVerticalT = 0;
private double clipVerticalB = 0;
private class CharStorageEntry {
/** Character's width */
public int width;
/** Character's height */
public int height;
/** Character's stored x position */
public int texPosX;
/** Character's stored y position */
public int texPosY;
}
public LoadedFont(Font font, boolean antiAlias, String charsNeeded) {
this.font = font;
this.fontSize = font.getSize() + 3;
this.antiAlias = antiAlias;
createSet(charsNeeded.toCharArray());
fontHeight -= 1;
if (fontHeight <= 0) fontHeight = 1;
}
public void setCorrection(boolean on)
{
if (on) {
correctL = 9;//2
correctR = 8;//1
correctL = 9;// 2
correctR = 8;// 1
} else {
correctL = 0;
correctR = 0;
}
}
private BufferedImage getFontImage(char ch)
{
// Create a temporary image to extract the character's size
@@ -126,7 +126,7 @@ public class LoadedFont {
g.setFont(font);
fontMetrics = g.getFontMetrics();
int charwidth = fontMetrics.charWidth(ch) + 8;
if (charwidth <= 0) {
charwidth = 7;
}
@@ -134,7 +134,7 @@ public class LoadedFont {
if (charheight <= 0) {
charheight = fontSize;
}
// Create another image holding the character we are creating
BufferedImage fontImage;
fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
@@ -143,28 +143,28 @@ public class LoadedFont {
gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
gt.setFont(font);
gt.setColor(Color.WHITE);
int charx = 3;
int chary = 1;
gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent());
return fontImage;
}
private void createSet(char[] charsToLoad)
{
try {
class LoadedGlyph {
public char c;
public BufferedImage image;
public int width;
public int height;
public LoadedGlyph(char c, BufferedImage image) {
this.image = image;
this.c = c;
@@ -172,7 +172,7 @@ public class LoadedFont {
this.height = image.getHeight();
}
}
List<LoadedGlyph> glyphs = new ArrayList<LoadedGlyph>();
List<Character> loaded = new ArrayList<Character>();
for (char ch : charsToLoad) {
@@ -181,35 +181,35 @@ public class LoadedFont {
loaded.add(ch);
}
}
Coord canvas = new Coord(128, 128);
double lineHeight = 0;
Coord begin = new Coord(0, 0);
boolean needsLarger = false;
while (true) {
needsLarger = false;
for (LoadedGlyph glyph : glyphs) {
if (begin.x + glyph.width > canvas.x) {
begin.y += lineHeight;
lineHeight = 0;
begin.x = 0;
}
if (lineHeight < glyph.height) {
lineHeight = glyph.height;
}
if (begin.y + lineHeight > canvas.y) {
needsLarger = true;
break;
}
// draw.
begin.x += glyph.width;
}
if (needsLarger) {
canvas.x *= 2;
canvas.y *= 2;
@@ -220,62 +220,62 @@ public class LoadedFont {
break;
}
}
textureWidth = (int) canvas.x;
textureHeight = (int) canvas.y;
BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) imgTemp.getGraphics();
g.setColor(new Color(0, 0, 0, 1));
g.fillRect(0, 0, textureWidth, textureHeight);
int rowHeight = 0;
int positionX = 0;
int positionY = 0;
for (LoadedGlyph glyph : glyphs) {
CharStorageEntry storedChar = new CharStorageEntry();
storedChar.width = glyph.width;
storedChar.height = glyph.height;
if (positionX + storedChar.width >= textureWidth) {
positionX = 0;
positionY += rowHeight;
rowHeight = 0;
}
storedChar.texPosX = positionX;
storedChar.texPosY = positionY;
if (storedChar.height > fontHeight) {
fontHeight = storedChar.height;
}
if (storedChar.height > rowHeight) {
rowHeight = storedChar.height;
}
// Draw it here
g.drawImage(glyph.image, positionX, positionY, null);
positionX += storedChar.width;
chars.put(glyph.c, storedChar);
}
fontTextureID = loadImage(imgTemp);
imgTemp = null;
} catch (Exception e) {
System.err.println("Failed to create font.");
e.printStackTrace();
}
}
private void drawQuad(double drawX, double drawY, double drawX2, double drawY2, CharStorageEntry charObj)
{
double srcX = charObj.texPosX + charObj.width;
@@ -290,9 +290,9 @@ public class LoadedFont {
double SrcHeight = srcY2 - srcY;
double RenderWidth = (SrcWidth / textureWidth);
double RenderHeight = (SrcHeight / textureHeight);
drawY -= DrawHeight * clipVerticalB;
GL11.glTexCoord2d(TextureSrcX, TextureSrcY);
GL11.glVertex2d(drawX, drawY);
GL11.glTexCoord2d(TextureSrcX, TextureSrcY + RenderHeight);
@@ -302,8 +302,8 @@ public class LoadedFont {
GL11.glTexCoord2d(TextureSrcX + RenderWidth, TextureSrcY);
GL11.glVertex2d(drawX + DrawWidth, drawY);
}
public int getWidth(String whatchars)
{
if (whatchars == null) whatchars = "";
@@ -312,61 +312,61 @@ public class LoadedFont {
char currentChar = 0;
for (int i = 0; i < whatchars.length(); i++) {
currentChar = whatchars.charAt(i);
charStorage = chars.get(currentChar);
if (charStorage != null) {
totalwidth += charStorage.width - correctL;
}
}
return (int) (totalwidth * defScaleX);
}
public int getHeight()
{
return (int) (fontHeight * defScaleY * (1 - clipVerticalT - clipVerticalB));
}
public int getLineHeight()
{
return getHeight();
}
public void drawString(double x, double y, String text, double scaleX, double scaleY, RGB color)
{
drawString(x, y, text, 0, text.length() - 1, scaleX, scaleY, color, LEFT);
}
public void drawString(double x, double y, String text, double scaleX, double scaleY, RGB color, int align)
{
drawString(x, y, text, 0, text.length() - 1, scaleX, scaleY, color, align);
}
private void drawString(double x, double y, String text, int startIndex, int endIndex, double scaleX, double scaleY, RGB color, int align)
{
x = Math.round(x);
y = Math.round(y);
scaleX *= defScaleX;
scaleY *= defScaleY;
CharStorageEntry charStorage = null;
int charCurrent;
int totalwidth = 0;
int i = startIndex, d = 1, c = correctL;
float startY = 0;
switch (align) {
case RIGHT: {
d = -1;
c = correctR;
while (i < endIndex) {
if (text.charAt(i) == '\n') startY -= getHeight();
i++;
@@ -377,7 +377,7 @@ public class LoadedFont {
for (int l = startIndex; l <= endIndex; l++) {
charCurrent = text.charAt(l);
if (charCurrent == '\n') break;
charStorage = chars.get((char) charCurrent);
if (charStorage != null) {
totalwidth += charStorage.width - correctL;
@@ -392,20 +392,20 @@ public class LoadedFont {
c = correctL;
break;
}
}
GL11.glPushAttrib(GL_ENABLE_BIT);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTextureID);
GL11.glColor4d(color.r, color.g, color.b, color.a);
GL11.glBegin(GL11.GL_QUADS);
while (i >= startIndex && i <= endIndex) {
charCurrent = text.charAt(i);
charStorage = chars.get(new Character((char) charCurrent));
if (charStorage != null) {
if (d < 0) totalwidth += (charStorage.width - c) * d;
if (charCurrent == '\n') {
@@ -415,14 +415,14 @@ public class LoadedFont {
for (int l = i + 1; l <= endIndex; l++) {
charCurrent = text.charAt(l);
if (charCurrent == '\n') break;
charStorage = chars.get((char) charCurrent);
totalwidth += charStorage.width - correctL;
}
totalwidth /= -2;
}
//if center get next lines total width/2;
// if center get next lines total width/2;
} else {
//@formatter:off
drawQuad(
@@ -432,25 +432,26 @@ public class LoadedFont {
charStorage
);
//@formatter:on
if (d > 0) totalwidth += (charStorage.width - c) * d;
}
}
i += d;
}
GL11.glEnd();
GL11.glPopAttrib();
}
public static int loadImage(BufferedImage bufferedImage)
{
try {
short width = (short) bufferedImage.getWidth();
short height = (short) bufferedImage.getHeight();
//textureLoader.bpp = bufferedImage.getColorModel().hasAlpha() ? (byte)32 : (byte)24;
// textureLoader.bpp = bufferedImage.getColorModel().hasAlpha() ?
// (byte)32 : (byte)24;
int bpp = (byte) bufferedImage.getColorModel().getPixelSize();
ByteBuffer byteBuffer;
DataBuffer db = bufferedImage.getData().getDataBuffer();
@@ -460,45 +461,45 @@ public class LoadedFont {
for (int i = 0; i < intI.length; i++) {
byte b[] = intToByteArray(intI[i]);
int newIndex = i * 4;
newI[newIndex] = b[1];
newI[newIndex + 1] = b[2];
newI[newIndex + 2] = b[3];
newI[newIndex + 3] = b[0];
}
byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)).order(ByteOrder.nativeOrder()).put(newI);
} else {
byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)).order(ByteOrder.nativeOrder()).put(((DataBufferByte) (bufferedImage.getData().getDataBuffer())).getData());
}
byteBuffer.flip();
int internalFormat = GL11.GL_RGBA8, format = GL11.GL_RGBA;
IntBuffer textureId = BufferUtils.createIntBuffer(1);
GL11.glGenTextures(textureId);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId.get(0));
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, internalFormat, width, height, format, GL11.GL_UNSIGNED_BYTE, byteBuffer);
return textureId.get(0);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
return -1;
}
public static boolean isSupported(String fontname)
{
Font font[] = getFonts();
@@ -507,14 +508,14 @@ public class LoadedFont {
}
return false;
}
public static Font[] getFonts()
{
return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
}
public static Font getFont(String fontname, int style, float size)
{
Font result = null;
@@ -527,14 +528,14 @@ public class LoadedFont {
}
return result;
}
public static byte[] intToByteArray(int value)
{
return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value };
}
public void destroy()
{
IntBuffer scratch = BufferUtils.createIntBuffer(1);
@@ -542,82 +543,91 @@ public class LoadedFont {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
GL11.glDeleteTextures(scratch);
}
public LoadedFont setScale(double x, double y)
{
defScaleX = x;
defScaleY = y;
return this;
}
public LoadedFont setClip(double clipRatioTop, double clipRatioBottom)
{
clipVerticalT = clipRatioTop;
clipVerticalB = clipRatioBottom;
return this;
}
public LoadedFont setCorrection(int correctionLeft, int correctionRight)
{
correctL = correctionLeft;
correctR = correctionRight;
return this;
}
/**
* Draw string with font.
*
* @param x x coord
* @param y y coord
* @param text text to draw
* @param color render color
* @param align (-1,0,1)
* @param x
* x coord
* @param y
* y coord
* @param text
* text to draw
* @param color
* render color
* @param align
* (-1,0,1)
*/
public void draw(double x, double y, String text, RGB color, int align)
{
drawString(x, y, text, 1, 1, color, align);
}
/**
* Draw string with font.
*
* @param pos coord
* @param text text to draw
* @param color render color
* @param align (-1,0,1)
* @param pos
* coord
* @param text
* text to draw
* @param color
* render color
* @param align
* (-1,0,1)
*/
public void draw(Coord pos, String text, RGB color, int align)
{
drawString(pos.x, pos.y, text, 1, 1, color, align);
}
public void drawFuzzy(Coord pos, String text, int align, RGB textColor, RGB blurColor, int blurSize)
{
drawFuzzy(pos, text, align, textColor, blurColor, blurSize, true);
}
public void drawFuzzy(Coord pos, String text, int align, RGB textColor, RGB blurColor, int blurSize, boolean smooth)
{
glPushMatrix();
glTranslated(pos.x, pos.y, pos.z);
//shadow
// shadow
int sh = blurSize;
int l = glGenLists(1);
glNewList(l, GL_COMPILE);
draw(0, 0, text, blurColor, align);
glEndList();
for (int xx = -sh; xx <= sh; xx += (smooth ? 1 : sh)) {
for (int yy = -sh; yy <= sh; yy += (smooth ? 1 : sh)) {
if (xx == 0 && yy == 0) continue;
@@ -627,12 +637,12 @@ public class LoadedFont {
glPopMatrix();
}
}
glDeleteLists(l, 1);
draw(0, 0, text, textColor, align);
glPopMatrix();
}
}
+26 -27
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.input;
import mightypork.rogue.AppAccess;
import mightypork.rogue.bus.DelegatingBusClient;
import mightypork.rogue.bus.events.KeyboardEvent;
@@ -15,37 +14,37 @@ import org.lwjgl.opengl.Display;
public class InputSystem extends DelegatingBusClient implements KeyBinder {
// listeners
private KeyBindingPool keybindings;
public InputSystem(AppAccess app) {
super(app, true);
}
@Override
protected void init()
{
initDevices();
initChannels();
// global keybindings
keybindings = new KeyBindingPool();
addChildSubscriber(keybindings);
}
@Override
public void deinit()
{
Mouse.destroy();
Keyboard.destroy();
}
private void initDevices()
{
try {
@@ -56,45 +55,45 @@ public class InputSystem extends DelegatingBusClient implements KeyBinder {
throw new RuntimeException("Failed to initialize input devices.", e);
}
}
private void initChannels()
{
bus().createChannel(KeyboardEvent.class, KeyboardEvent.Listener.class);
bus().createChannel(MouseMotionEvent.class, MouseMotionEvent.Listener.class);
bus().createChannel(MouseButtonEvent.class, MouseButtonEvent.Listener.class);
}
@Override
public void bindKeyStroke(KeyStroke stroke, Runnable task)
{
keybindings.bindKeyStroke(stroke, task);
}
@Override
public void unbindKeyStroke(KeyStroke stroke)
{
keybindings.unbindKeyStroke(stroke);
}
@Override
public void update(double delta)
{
Display.processMessages();
while (Mouse.next()) {
onMouseEvent();
}
while (Keyboard.next()) {
onKeyEvent();
}
}
private void onMouseEvent()
{
int button = Mouse.getEventButton();
@@ -102,12 +101,12 @@ public class InputSystem extends DelegatingBusClient implements KeyBinder {
Coord pos = new Coord(Mouse.getEventX(), Mouse.getEventY());
Coord move = new Coord(Mouse.getEventDX(), Mouse.getEventDY());
int wheeld = Mouse.getEventDWheel();
if (button != -1 || wheeld != 0) bus().broadcast(new MouseButtonEvent(pos, button, down, wheeld));
if (!move.isZero()) bus().broadcast(new MouseMotionEvent(pos, move));
}
private void onKeyEvent()
{
int key = Keyboard.getEventKey();
+10 -8
View File
@@ -1,22 +1,24 @@
package mightypork.rogue.input;
public interface KeyBinder {
/**
* Bind handler to a keystroke, replace current handler if any
*
* @param stroke trigger keystroke
* @param task handler
* @param stroke
* trigger keystroke
* @param task
* handler
*/
abstract void bindKeyStroke(KeyStroke stroke, Runnable task);
/**
* Remove handler from a keystroke (id any)
*
* @param stroke stroke
* @param stroke
* stroke
*/
abstract void unbindKeyStroke(KeyStroke stroke);
}
+13 -14
View File
@@ -1,48 +1,47 @@
package mightypork.rogue.input;
import mightypork.rogue.bus.events.KeyboardEvent;
public class KeyBinding implements KeyboardEvent.Listener {
private KeyStroke keystroke;
private Runnable handler;
private boolean wasActive = false;
public KeyBinding(KeyStroke stroke, Runnable handler) {
this.keystroke = stroke;
this.handler = handler;
wasActive = keystroke.isActive();
}
public boolean matches(KeyStroke stroke)
{
return this.keystroke.equals(stroke);
}
public void setHandler(Runnable handler)
{
this.handler = handler;
}
@Override
public void receive(KeyboardEvent event)
{
// ignore unrelated events
if (!keystroke.getKeys().contains(event.getKey())) return;
// run handler when event was met
if (keystroke.isActive() && !wasActive) {
handler.run();
}
wasActive = keystroke.isActive();
}
}
+15 -13
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.input;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
@@ -15,15 +14,17 @@ import mightypork.utils.logging.Log;
* @author MightyPork
*/
public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
private Set<KeyBinding> bindings = new HashSet<KeyBinding>();
/**
* Bind handler to a keystroke, replace current handler if any
*
* @param stroke trigger keystroke
* @param task handler
* @param stroke
* trigger keystroke
* @param task
* handler
*/
@Override
public void bindKeyStroke(KeyStroke stroke, Runnable task)
@@ -35,21 +36,22 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
return;
}
}
bindings.add(new KeyBinding(stroke, task));
}
/**
* Remove handler from keystroke (id any)
*
* @param stroke stroke
* @param stroke
* stroke
*/
@Override
public void unbindKeyStroke(KeyStroke stroke)
{
Iterator<KeyBinding> iter = bindings.iterator();
while (iter.hasNext()) {
KeyBinding kb = iter.next();
if (kb.matches(stroke)) {
@@ -58,8 +60,8 @@ public class KeyBindingPool implements KeyBinder, KeyboardEvent.Listener {
}
}
}
@Override
public void receive(KeyboardEvent event)
{
+29 -28
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.input;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -9,16 +8,18 @@ import org.lwjgl.input.Keyboard;
public class KeyStroke {
private Set<Integer> keys = new LinkedHashSet<Integer>();
private boolean down = true;
/**
* KeyStroke
*
* @param down true for falling edge, up for rising edge
* @param keys keys that must be pressed
* @param down
* true for falling edge, up for rising edge
* @param keys
* keys that must be pressed
*/
public KeyStroke(boolean down, int... keys) {
this.down = down;
@@ -26,8 +27,8 @@ public class KeyStroke {
this.keys.add(k);
}
}
/**
* Falling edge keystroke
*
@@ -38,25 +39,25 @@ public class KeyStroke {
this.keys.add(k);
}
}
public boolean isActive()
{
boolean st = true;
for (int k : keys) {
st &= Keyboard.isKeyDown(k);
}
return down ? st : !st;
}
public void setKeys(Set<Integer> keys)
{
this.keys = keys;
}
@Override
public int hashCode()
{
@@ -65,8 +66,8 @@ public class KeyStroke {
result = prime * result + ((keys == null) ? 0 : keys.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
@@ -74,39 +75,39 @@ public class KeyStroke {
if (obj == null) return false;
if (!(obj instanceof KeyStroke)) return false;
KeyStroke other = (KeyStroke) obj;
if (keys == null) {
if (other.keys != null) return false;
} else if (!keys.equals(other.keys)) {
return false;
}
if (down != other.down) return false;
return true;
}
@Override
public String toString()
{
String s = "(";
int cnt = 0;
Iterator<Integer> i = keys.iterator();
for (; i.hasNext(); cnt++) {
if (cnt > 0) s += "+";
s += Keyboard.getKeyName(i.next());
}
s += down ? ",DOWN" : "UP";
s += ")";
return s;
}
public Set<Integer> getKeys()
{
return keys;
+87 -70
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.sounds;
import mightypork.utils.files.FileUtils;
import mightypork.utils.logging.Log;
import mightypork.utils.math.coord.Coord;
@@ -16,12 +15,11 @@ import org.newdawn.slick.openal.SoundStore;
* @author MightyPork
*/
public class AudioX implements Destroyable {
private enum PlayMode
{
private enum PlayMode {
EFFECT, MUSIC;
};
private Audio audio = null;
private double pauseLoopPosition = 0;
private boolean looping = false;
@@ -29,37 +27,38 @@ public class AudioX implements Destroyable {
private PlayMode mode = PlayMode.EFFECT;
private double lastPlayPitch = 1;
private double lastPlayGain = 1;
private final String resourcePath;
private boolean loadFailed = false;
/**
* Create deferred primitive audio player
*
* @param resourceName resource to load when needed
* @param resourceName
* resource to load when needed
*/
public AudioX(String resourceName) {
this.audio = null;
this.resourcePath = resourceName;
}
/**
* Pause loop (remember position and stop playing) - if was looping
*/
public void pauseLoop()
{
if (!load()) return;
if (isPlaying() && looping) {
pauseLoopPosition = audio.getPosition();
stop();
paused = true;
}
}
/**
* Resume loop (if was paused)
*
@@ -68,7 +67,7 @@ public class AudioX implements Destroyable {
public int resumeLoop()
{
if (!load()) return -1;
int source = -1;
if (looping && paused) {
if (mode == PlayMode.MUSIC) {
@@ -81,8 +80,8 @@ public class AudioX implements Destroyable {
}
return source;
}
/**
* Check if resource is loaded
*
@@ -92,8 +91,8 @@ public class AudioX implements Destroyable {
{
return audio != null;
}
/**
* Try to load if not loaded already
*
@@ -102,12 +101,14 @@ public class AudioX implements Destroyable {
public boolean load()
{
if (isLoaded()) return true; // already loaded
if (loadFailed || resourcePath == null) return false; // not loaded, but can't load anyway
if (loadFailed || resourcePath == null) return false; // not loaded, but
// can't load
// anyway
loadFailed = false;
try {
String ext = FileUtils.getExtension(resourcePath);
// java 6 can't use String switch :(
if (ext.equalsIgnoreCase("ogg")) {
audio = SoundStore.get().getOgg(resourcePath);
@@ -121,61 +122,67 @@ public class AudioX implements Destroyable {
Log.e("Invalid audio file extension: " + resourcePath);
loadFailed = true; // don't try next time
}
} catch (Exception e) {
Log.e("Could not load " + resourcePath, e);
loadFailed = true; // don't try next time
}
return isLoaded();
}
public void stop()
{
if (!isLoaded()) return;
audio.stop();
paused = false;
}
public boolean isPlaying()
{
if (!isLoaded()) return false;
return audio.isPlaying();
}
public boolean isPaused()
{
if (!isLoaded()) return false;
return audio.isPaused();
}
/**
* Play as sound effect at listener position
*
* @param pitch pitch (1 = default)
* @param gain gain (0-1)
* @param loop looping
* @param pitch
* pitch (1 = default)
* @param gain
* gain (0-1)
* @param loop
* looping
* @return source id
*/
public int playAsEffect(double pitch, double gain, boolean loop)
{
return playAsEffect(pitch, gain, loop, SoundSystem.getListener());
}
/**
* Play as sound effect at given X-Y position
*
* @param pitch pitch (1 = default)
* @param gain gain (0-1)
* @param loop looping
* @param pitch
* pitch (1 = default)
* @param gain
* gain (0-1)
* @param loop
* looping
* @param x
* @param y
* @return source id
@@ -184,14 +191,17 @@ public class AudioX implements Destroyable {
{
return playAsEffect(pitch, gain, loop, x, y, SoundSystem.getListener().z);
}
/**
* Play as sound effect at given position
*
* @param pitch pitch (1 = default)
* @param gain gain (0-1)
* @param loop looping
* @param pitch
* pitch (1 = default)
* @param gain
* gain (0-1)
* @param loop
* looping
* @param x
* @param y
* @param z
@@ -200,63 +210,70 @@ public class AudioX implements Destroyable {
public int playAsEffect(double pitch, double gain, boolean loop, double x, double y, double z)
{
if (!load()) return -1;
this.lastPlayPitch = pitch;
this.lastPlayGain = gain;
looping = loop;
mode = PlayMode.EFFECT;
return audio.playAsSoundEffect((float) pitch, (float) gain, loop, (float) x, (float) y, (float) z);
}
/**
* Play as sound effect at given position
*
* @param pitch pitch (1 = default)
* @param gain gain (0-1)
* @param loop looping
* @param pos coord
* @param pitch
* pitch (1 = default)
* @param gain
* gain (0-1)
* @param loop
* looping
* @param pos
* coord
* @return source id
*/
public int playAsEffect(double pitch, double gain, boolean loop, Coord pos)
{
if (!load()) return -1;
return playAsEffect(pitch, gain, loop, pos.x, pos.y, pos.z);
}
/**
* Play as music using source 0.<br>
* Discouraged, since this does not allow cross-fading.
*
* @param pitch play pitch
* @param gain play gain
* @param loop looping
* @param pitch
* play pitch
* @param gain
* play gain
* @param loop
* looping
* @return source
*/
public int playAsMusic(double pitch, double gain, boolean loop)
{
if (!load()) return -1;
this.lastPlayPitch = (float) pitch;
this.lastPlayGain = (float) gain;
looping = loop;
mode = PlayMode.MUSIC;
return audio.playAsMusic((float) pitch, (float) gain, loop);
}
@Override
public void destroy()
{
if (!isLoaded()) return;
audio.release();
audio = null;
}
@Override
public int hashCode()
{
@@ -265,8 +282,8 @@ public class AudioX implements Destroyable {
result = prime * result + ((resourcePath == null) ? 0 : resourcePath.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
@@ -281,5 +298,5 @@ public class AudioX implements Destroyable {
}
return true;
}
}
@@ -1,66 +1,65 @@
package mightypork.rogue.sounds;
import mightypork.utils.objects.Mutable;
public abstract class BaseAudioPlayer {
/** the track */
private AudioX audio;
/** base gain for sfx */
private double baseGain = 1;
/** base pitch for sfx */
private double basePitch = 1;
/** dedicated volume control */
private Mutable<Double> gainMultiplier = null;
public BaseAudioPlayer(AudioX track, double baseGain, Mutable<Double> gainMultiplier) {
this(track, 1, baseGain, gainMultiplier);
}
public BaseAudioPlayer(AudioX track, double basePitch, double baseGain, Mutable<Double> gainMultiplier) {
this.audio = track;
this.baseGain = baseGain;
this.basePitch = basePitch;
if (gainMultiplier == null) gainMultiplier = new Mutable<Double>(1D);
this.gainMultiplier = gainMultiplier;
}
public void destroy()
{
audio.destroy();
audio = null;
}
protected AudioX getAudio()
{
return audio;
}
protected double getGain(double multiplier)
{
return baseGain * gainMultiplier.get() * multiplier;
}
protected double getPitch(double multiplier)
{
return basePitch * multiplier;
}
/**
* Get if audio is valid
*
@@ -70,8 +69,8 @@ public abstract class BaseAudioPlayer {
{
return (audio != null);
}
public void load()
{
if (canPlay()) audio.load();
+10 -11
View File
@@ -1,36 +1,35 @@
package mightypork.rogue.sounds;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.objects.Mutable;
public class EffectPlayer extends BaseAudioPlayer {
public EffectPlayer(AudioX track, double basePitch, double baseGain, Mutable<Double> gainMultiplier) {
super(track, (float) basePitch, (float) baseGain, gainMultiplier);
}
public int play(double pitch, double gain)
{
if (!canPlay()) return -1;
return getAudio().playAsEffect(getPitch(pitch), getGain(gain), false);
}
public int play(double gain)
{
return play(1, gain);
}
public int play(double pitch, double gain, Coord pos)
{
if (!canPlay()) return -1;
return getAudio().playAsEffect(getPitch(pitch), getGain(gain), false, pos);
}
}
+10 -10
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.sounds;
import mightypork.utils.math.Calc;
import mightypork.utils.objects.Mutable;
@@ -11,21 +10,22 @@ import mightypork.utils.objects.Mutable;
* @author MightyPork
*/
public class JointVolume extends Mutable<Double> {
private Mutable<Double>[] volumes;
/**
* Create joint volume with master gain of 1
*
* @param volumes individual volumes to join
* @param volumes
* individual volumes to join
*/
public JointVolume(Mutable<Double>... volumes) {
super(1D);
this.volumes = volumes;
}
/**
* Get combined gain (multiplied)
*/
@@ -35,11 +35,11 @@ public class JointVolume extends Mutable<Double> {
double d = super.get();
for (Mutable<Double> v : volumes)
d *= v.get();
return Calc.clampd(d, 0, 1);
}
/**
* Set master gain
*/
+40 -41
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.sounds;
import mightypork.utils.objects.Mutable;
import mightypork.utils.time.Pauseable;
import mightypork.utils.time.Updateable;
@@ -10,38 +9,38 @@ import org.lwjgl.openal.AL10;
public class LoopPlayer extends BaseAudioPlayer implements Updateable, Pauseable {
private int sourceID = -1;
/** animator for fade in and fade out */
private AnimDouble fadeAnim = new AnimDouble(0);
private double lastUpdateGain = 0;
/** flag that track is paused */
private boolean paused = true;
/** Default fadeIn time */
private double inTime = 1;
/** Default fadeOut time */
private double outTime = 1;
public LoopPlayer(AudioX track, double pitch, double baseGain, Mutable<Double> gainMultiplier) {
super(track, (float) pitch, (float) baseGain, gainMultiplier);
paused = true;
}
public void setFadeTimes(double in, double out)
{
inTime = in;
outTime = out;
}
private void initLoop()
{
if (!canPlay() && sourceID == -1) {
@@ -49,84 +48,84 @@ public class LoopPlayer extends BaseAudioPlayer implements Updateable, Pauseable
getAudio().pauseLoop();
}
}
@Override
public void pause()
{
if (!canPlay() || paused) return;
initLoop();
getAudio().pauseLoop();
paused = true;
}
@Override
public boolean isPaused()
{
return paused;
}
@Override
public void resume()
{
if (!canPlay() || paused) return;
initLoop();
sourceID = getAudio().resumeLoop();
paused = false;
}
@Override
public void update(double delta)
{
if (!canPlay() || paused) return;
initLoop();
fadeAnim.update(delta);
double gain = getGain(fadeAnim.getCurrentValue());
if (!paused && gain != lastUpdateGain) {
AL10.alSourcef(sourceID, AL10.AL_GAIN, (float) gain);
lastUpdateGain = gain;
}
if (gain == 0 && !paused) pause(); // pause on zero volume
}
public void fadeIn(double secs)
{
if (!canPlay()) return;
resume();
fadeAnim.fadeIn(secs);
}
public void fadeOut(double secs)
{
if (!canPlay()) return;
fadeAnim.fadeOut(secs);
}
public void fadeIn()
{
fadeIn(inTime);
}
public void fadeOut()
{
fadeOut(outTime);
}
}
+4 -5
View File
@@ -1,17 +1,16 @@
package mightypork.rogue.sounds;
public class NullAudio extends AudioX {
public NullAudio() {
super("");
}
@Override
public boolean load()
{
return false;
}
}
+102 -78
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.sounds;
import java.nio.FloatBuffer;
import java.util.HashMap;
import java.util.HashSet;
@@ -26,24 +25,24 @@ import org.newdawn.slick.openal.SoundStore;
*/
@SuppressWarnings("unchecked")
public class SoundSystem extends DelegatingBusClient {
private static final Coord INITIAL_LISTENER_POS = new Coord(0, 0, 0);
private static final int MAX_SOURCES = 256;
private static final AudioX NO_SOUND = new NullAudio();
private static final LoopPlayer NULL_LOOP = new LoopPlayer(NO_SOUND, 0, 0, null);
private static final EffectPlayer NULL_EFFECT = new EffectPlayer(NO_SOUND, 0, 0, null);
private static Coord listener = new Coord();
static {
// initialize sound system
SoundStore.get().setMaxSources(MAX_SOURCES);
SoundStore.get().init();
setListener(INITIAL_LISTENER_POS);
}
/**
* Set listener pos
*
@@ -65,42 +64,42 @@ public class SoundSystem extends DelegatingBusClient {
AL10.alListener(AL10.AL_ORIENTATION, buf6);
buf3 = buf6 = null;
}
// -- instance --
public Mutable<Double> masterVolume = new Mutable<Double>(1D);
public Mutable<Double> effectsVolume = new JointVolume(masterVolume);
public Mutable<Double> loopsVolume = new JointVolume(masterVolume);
private Map<String, EffectPlayer> effects = new HashMap<String, EffectPlayer>();
private Map<String, LoopPlayer> loops = new HashMap<String, LoopPlayer>();
private Set<AudioX> resources = new HashSet<AudioX>();
public SoundSystem(AppAccess app) {
super(app, true);
}
@Override
protected void init()
{
// empty
}
@Override
public void deinit()
{
for (AudioX r : resources) {
r.destroy();
}
SoundStore.get().clear();
AL.destroy();
}
@Override
public void update(double delta)
{
@@ -108,38 +107,48 @@ public class SoundSystem extends DelegatingBusClient {
lp.update(delta);
}
}
public static Coord getListener()
{
return listener;
}
/**
* Register effect resource
*
* @param key sound key
* @param resource resource path
* @param pitch default pitch (1 = unchanged)
* @param gain default gain (0-1)
* @param key
* sound key
* @param resource
* resource path
* @param pitch
* default pitch (1 = unchanged)
* @param gain
* default gain (0-1)
*/
public void addEffect(String key, String resource, double pitch, double gain)
{
EffectPlayer p = new EffectPlayer(getResource(resource), pitch, gain, effectsVolume);
effects.put(key, p);
}
/**
* Register loop resource (music / effect loop)
*
* @param key sound key
* @param resource resource path
* @param pitch default pitch (1 = unchanged)
* @param gain default gain (0-1)
* @param fadeIn default time for fadeIn
* @param fadeOut default time for fadeOut
* @param key
* sound key
* @param resource
* resource path
* @param pitch
* default pitch (1 = unchanged)
* @param gain
* default gain (0-1)
* @param fadeIn
* default time for fadeIn
* @param fadeOut
* default time for fadeOut
*/
public void addLoop(String key, String resource, double pitch, double gain, double fadeIn, double fadeOut)
{
@@ -147,14 +156,16 @@ public class SoundSystem extends DelegatingBusClient {
p.setFadeTimes(fadeIn, fadeOut);
loops.put(key, p);
}
/**
* Create {@link AudioX} for a resource
*
* @param res a resource name
* @param res
* a resource name
* @return the resource
* @throws IllegalArgumentException if resource is already registered
* @throws IllegalArgumentException
* if resource is already registered
*/
private AudioX getResource(String res)
{
@@ -163,12 +174,13 @@ public class SoundSystem extends DelegatingBusClient {
resources.add(a);
return a;
}
/**
* Get a loop player for key
*
* @param key sound key
* @param key
* sound key
* @return loop player
*/
public LoopPlayer getLoop(String key)
@@ -180,12 +192,13 @@ public class SoundSystem extends DelegatingBusClient {
}
return p;
}
/**
* Get a effect player for key
*
* @param key sound key
* @param key
* sound key
* @return effect player
*/
public EffectPlayer getEffect(String key)
@@ -197,8 +210,8 @@ public class SoundSystem extends DelegatingBusClient {
}
return p;
}
/**
* Fade out all loops (ie. for screen transitions)
*/
@@ -208,65 +221,72 @@ public class SoundSystem extends DelegatingBusClient {
p.fadeOut();
}
}
/**
* Fade in a loop (with default time)
*
* @param key sound key
* @param key
* sound key
*/
public void fadeInLoop(String key)
{
getLoop(key).fadeIn();
}
/**
* Fade in a loop
*
* @param key sound key
* @param seconds fade-in duration
* @param key
* sound key
* @param seconds
* fade-in duration
*/
public void fadeInLoop(String key, double seconds)
{
getLoop(key).fadeIn(seconds);
}
/**
* Fade out a loop (with default time)
*
* @param key sound key
* @param key
* sound key
*/
public void fadeOutLoop(String key)
{
getLoop(key).fadeOut();
}
/**
* Fade out a loop
*
* @param key sound key
* @param seconds fade-out duration
* @param key
* sound key
* @param seconds
* fade-out duration
*/
public void fadeOutLoop(String key, double seconds)
{
getLoop(key).fadeOut(seconds);
}
/**
* Pause a loop
*
* @param key sound key
* @param key
* sound key
*/
public void pauseLoop(String key)
{
getLoop(key).pause();
}
/**
* Pause all loops (leave volume unchanged)
*/
@@ -276,45 +296,49 @@ public class SoundSystem extends DelegatingBusClient {
p.pause();
}
}
/**
* Resume a loop
*
* @param key sound key
* @param key
* sound key
*/
public void resumeLoop(String key)
{
getLoop(key).resume();
}
/**
* Set level of master volume
*
* @param d level
* @param d
* level
*/
public void setMasterVolume(double d)
{
masterVolume.set(d);
}
/**
* Set level of effects volume
*
* @param d level
* @param d
* level
*/
public void setEffectsVolume(double d)
{
effectsVolume.set(d);
}
/**
* Set level of music volume
*
* @param d level
* @param d
* level
*/
public void setMusicVolume(double d)
{
@@ -1,6 +1,5 @@
package mightypork.rogue.tasks;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
@@ -16,20 +15,20 @@ import mightypork.utils.logging.Log;
public class TaskTakeScreenshot implements Runnable {
private BufferedImage image;
public TaskTakeScreenshot(DisplaySystem disp) {
this.image = disp.takeScreenshot();
}
@Override
public void run()
{
String fname = getUniqueScreenshotName();
// generate unique filename
File file;
int index = 0;
@@ -38,11 +37,11 @@ public class TaskTakeScreenshot implements Runnable {
if (!file.exists()) break;
index++;
}
Log.f3("Saving screenshot to file: " + file);
String format = "PNG";
// save to disk
try {
ImageIO.write(image, format, file);
@@ -50,12 +49,12 @@ public class TaskTakeScreenshot implements Runnable {
Log.e("Failed to save screenshot.", e);
}
}
private String getUniqueScreenshotName()
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
return df.format(new Date());
}
}
@@ -1,6 +1,5 @@
package mightypork.rogue.testing;
import mightypork.rogue.display.constraints.Bounding;
import mightypork.rogue.display.constraints.Constraint;
import mightypork.utils.math.coord.Coord;
@@ -8,56 +7,56 @@ import mightypork.utils.math.coord.Rect;
public class TestConstraints {
public static void main(String[] args)
{
Bounding context = new Bounding() {
@Override
public Rect getRect()
{
return Rect.fromSize(new Coord(0, 0), new Coord(400, 300));
}
};
class Navbar extends Constraint {
private double height;
public Navbar(Bounding context, double height) {
super(context);
this.height = height;
}
@Override
public Rect getRect()
{
return Rect.fromSize(origin().setY(size().y - height), size().setY(height));
}
}
class TileHorizontal extends Constraint {
private int count;
private int tile;
public TileHorizontal(Bounding context, int tileCount, int aTile) {
super(context);
this.count = tileCount;
setTile(aTile);
}
public void setTile(int aTile)
{
if (aTile > count) throw new IndexOutOfBoundsException("Tile count exceeded: " + aTile + " max: " + count);
this.tile = aTile;
}
@Override
public Rect getRect()
{
@@ -65,20 +64,20 @@ public class TestConstraints {
return Rect.fromSize(origin().add(size.x * tile, 0), size);
}
}
Navbar nb = new Navbar(context, 100);
TileHorizontal tile = new TileHorizontal(nb, 5, 0);
for (int i = 0; i < 5; i++) {
tile.setTile(i);
System.out.println(tile.getRect());
}
System.out.println("nb:" + nb.getRect());
System.out.println("ctx:" + context.getRect());
}
}
+62 -61
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.testing;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,16 +13,16 @@ import mightypork.utils.patterns.subscription.clients.ToggleableClient;
public class TestMsgbus {
public static void main(String[] args)
{
Log.create("runtime", new File("."), 0);
MessageBus bus = new MessageBus();
bus.createChannel(StringMessage.class, StringMessage.Listener.class);
bus.createChannel(IntMessage.class, IntMessage.Listener.class);
Delegator deleg1 = new Delegator("Deleg1");
Delegator deleg2 = new Delegator("Deleg2");
Toggleable togg1 = new Toggleable("Tog1");
@@ -31,61 +30,61 @@ public class TestMsgbus {
Toggleable plain1 = new Toggleable("Plain1");
Toggleable plain2 = new Toggleable("Plain2");
Toggleable plain3 = new Toggleable("Plain3");
PlainInt pint = new PlainInt("Ints");
PlainBoth pboth = new PlainBoth("Both");
bus.subscribe(deleg1);
deleg1.clients.add(togg1);
deleg1.clients.add(plain2);
deleg1.clients.add(deleg2);
deleg1.clients.add(pint);
deleg2.clients.add(deleg1);
deleg2.clients.add(togg1);
deleg2.clients.add(plain3);
deleg2.clients.add(pboth);
bus.subscribe(plain1);
bus.subscribe(togg2);
bus.broadcast(new StringMessage("<MSG>"));
bus.broadcast(new IntMessage(7));
bus.broadcast(new IntMessage(13));
deleg2.delegating = false;
bus.broadcast(new IntMessage(44));
deleg2.delegating = true;
bus.broadcast(new IntMessage(45));
}
}
class Delegator extends Plain implements DelegatingClient {
List<Object> clients = new ArrayList<Object>();
boolean delegating = true;
public Delegator(String name) {
super(name);
}
@Override
public Collection<Object> getChildClients()
{
return clients;
}
@Override
public boolean doesDelegate()
{
@@ -95,15 +94,15 @@ class Delegator extends Plain implements DelegatingClient {
class Toggleable extends Plain implements ToggleableClient {
boolean subscribing = true;
public Toggleable(String name) {
super(name);
}
@Override
public boolean doesSubscribe()
{
@@ -113,15 +112,15 @@ class Toggleable extends Plain implements ToggleableClient {
class Plain implements StringMessage.Listener {
String name;
public Plain(String name) {
this.name = name;
}
@Override
public void receive(StringMessage message)
{
@@ -131,15 +130,15 @@ class Plain implements StringMessage.Listener {
class PlainInt implements IntMessage.Listener {
String name;
public PlainInt(String name) {
this.name = name;
}
@Override
public void receive(IntMessage message)
{
@@ -149,22 +148,22 @@ class PlainInt implements IntMessage.Listener {
class PlainBoth implements IntMessage.Listener, StringMessage.Listener {
String name;
public PlainBoth(String name) {
this.name = name;
}
@Override
public void receive(IntMessage message)
{
System.out.println(name + " (both-INT) RECV: " + message.i);
}
@Override
public void receive(StringMessage message)
{
@@ -174,20 +173,21 @@ class PlainBoth implements IntMessage.Listener, StringMessage.Listener {
class StringMessage implements Handleable<StringMessage.Listener> {
String s;
StringMessage(String str) {
this.s = str;
}
public interface Listener {
public void receive(StringMessage message);
}
@Override
public void handleBy(Listener handler)
{
@@ -197,20 +197,21 @@ class StringMessage implements Handleable<StringMessage.Listener> {
class IntMessage implements Handleable<IntMessage.Listener> {
int i;
IntMessage(int i) {
this.i = i;
}
public interface Listener {
public void receive(IntMessage message);
}
@Override
public void handleBy(Listener handler)
{
@@ -1,6 +1,5 @@
package mightypork.rogue.textures;
import static org.lwjgl.opengl.GL11.*;
import java.io.IOException;
@@ -18,10 +17,10 @@ import org.newdawn.slick.util.ResourceLoader;
* @author MightyPork
*/
public class TextureManager {
private static Texture lastBinded = null;
/**
* Load texture
*
@@ -32,28 +31,30 @@ public class TextureManager {
{
try {
String ext = resourcePath.substring(resourcePath.length() - 4);
Texture texture = TextureLoader.getTexture(ext.toUpperCase(), ResourceLoader.getResourceAsStream(resourcePath));
if (texture != null) {
return texture;
}
Log.w("Texture " + resourcePath + " could not be loaded.");
return null;
} catch (IOException e) {
Log.e("Loading of texture " + resourcePath + " failed.", e);
throw new RuntimeException(e);
}
}
/**
* Bind texture
*
* @param texture the texture
* @throws RuntimeException if not loaded yet
* @param texture
* the texture
* @throws RuntimeException
* if not loaded yet
*/
public static void bind(Texture texture) throws RuntimeException
{
@@ -63,8 +64,8 @@ public class TextureManager {
lastBinded = texture;
}
}
/**
* Unbind all
*/
+7 -8
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.textures;
import static org.lwjgl.opengl.GL11.*;
import org.newdawn.slick.opengl.Texture;
@@ -14,12 +13,12 @@ import org.newdawn.slick.opengl.Texture;
* @author MightyPork
*/
public class Textures {
protected static Texture logo;
private static final String GUI = "res/images/gui/";
/**
* Load what's needed for splash
*/
@@ -29,12 +28,12 @@ public class Textures {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
logo = TextureManager.load(GUI + "logo.png");
Tx.initForSplash();
glDisable(GL_TEXTURE_2D);
Tx.init();
}
}
+7 -8
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.textures;
// TODO rewrite
/**
@@ -9,22 +8,22 @@ package mightypork.rogue.textures;
* @author MightyPork
*/
public class Tx {
// logo
public static TxQuad LOGO;
public static void initForSplash()
{
// splash logo
LOGO = TxQuad.fromSize(Textures.logo, 15, 9, 226, 132);
}
public static void init()
{
// title image (word art)
}
}
+33 -22
View File
@@ -1,6 +1,5 @@
package mightypork.rogue.textures;
import mightypork.utils.math.coord.Coord;
import mightypork.utils.math.coord.Rect;
@@ -13,58 +12,70 @@ import org.newdawn.slick.opengl.Texture;
* @author MightyPork
*/
public class TxQuad {
/** The texture */
public Texture tx;
/** Coords in texture (pixels) */
public Rect uvs;
/** Quad size */
public Coord size;
/**
* Create TxQuad from left top coord and rect size
*
* @param tx texture
* @param x1 left top X
* @param y1 left top Y
* @param width area width
* @param height area height
* @param tx
* texture
* @param x1
* left top X
* @param y1
* left top Y
* @param width
* area width
* @param height
* area height
* @return new TxQuad
*/
public static TxQuad fromSize(Texture tx, int x1, int y1, int width, int height)
{
return new TxQuad(tx, x1, y1, x1 + width, y1 + height);
}
/**
* @param tx Texture
* @param uvs Rect of texturwe UVs (pixels - from left top)
* @param tx
* Texture
* @param uvs
* Rect of texturwe UVs (pixels - from left top)
*/
public TxQuad(Texture tx, Rect uvs) {
this.tx = tx;
this.uvs = uvs.copy();
this.size = uvs.getSize();
}
/**
* Make of coords
*
* @param tx texture
* @param x1 x1
* @param y1 y1
* @param x2 x2
* @param y2 y2
* @param tx
* texture
* @param x1
* x1
* @param y1
* y1
* @param x2
* x2
* @param y2
* y2
*/
public TxQuad(Texture tx, int x1, int y1, int x2, int y2) {
this.tx = tx;
this.uvs = new Rect(x1, y1, x2, y2);
this.size = uvs.getSize();
}
public TxQuad copy()
{
return new TxQuad(tx, uvs);
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -1,13 +1,12 @@
package mightypork.rogue.util;
/**
* Utils class
*
* @author MightyPork
*/
public class Utils {
public static Thread runAsThread(Runnable r)
{
Thread t = new Thread(r);