summaryrefslogtreecommitdiffstats
path: root/src/subconscious/graphics/Scene.java
blob: db035b31f1f8d6989f648e652a8aaf91aff52489 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package subconscious.graphics;

import subconscious.Game;

import subconscious.graphics.widget.Widget;
import subconscious.graphics.widget.Clickable;
import subconscious.graphics.widget.Dynamic;

import subconscious.graphics.widget.PerfView;

import java.lang.Thread;

import java.util.ArrayList;
import java.util.Map;
import java.util.EnumMap;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;

import java.io.InputStream;
import java.io.IOException;

import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.RenderingHints;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Point;

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;

import java.awt.image.BufferStrategy;



/* Scene
 * Abstract model class for all scenes of the game. Each scene is in a different
 * thread and renders with a double buffered. As threads, scenes can be paused
 * from rendering.
 *
 * It is also responsable for all inputs, which are transferred to the Game 
 * object which controls the internal state of the game.
 */
@SuppressWarnings("serial")
public abstract class Scene extends Panel
	implements Runnable, KeyListener, MouseListener, MouseMotionListener, 
				MouseWheelListener, ComponentListener {

	// this is required to manage multiple scenes
	public final String UNIQUE_NAME;
	private static int absScenesCount = 0;

	public static final long DESIRED_FPS = 80;
	public static final long DESIRED_DELTA_LOOP_NS = (1000*1000*1000)/DESIRED_FPS;
	public static final long NO_DELAYS_PER_YELD = 15;
	public static final Map<RenderingHints.Key, ?> RENDERING_HINTS = Map.of(
		RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON,
		RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON,
		RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED,
		RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
		// RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR,
		RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED
	);

	protected final EnumMap<Widget.Anchor, Point> widgetAnchors = new EnumMap<Widget.Anchor, Point>(Widget.Anchor.class);
	private ArrayList<Widget> widgets = new ArrayList<>();
	private ArrayList<Widget> dynamicWidgetsCache = new ArrayList<>();
	private ArrayList<Widget> clickableWidgetsCache = new ArrayList<>();

	// Game is never cached in the local thread
	protected volatile Game game;

	// TODO: this could become a Queue of scenes to load
	protected Scene requestedScene = null;
	protected boolean requestedPrevScene = false;

	protected volatile boolean running = true;
	protected volatile boolean threadPaused = false;
	protected Lock pauseLock = new ReentrantLock();
	protected Condition threadResumed = pauseLock.newCondition();

	protected volatile Dimension canvasSize = GameWindow.WINDOW_SIZE;
	protected Canvas canvas = new Canvas();
	protected BufferStrategy buffer;

	// TODO: make accessible from user settings
	protected int guiSize = 2;

	public Scene(Game game, String label) {
		// generate unique name
		String uniqueName = this.getClass().getCanonicalName() + Integer.toString(Scene.absScenesCount);
		Scene.absScenesCount++;

		this.UNIQUE_NAME = uniqueName + " (" + label + ")";
		this.game = game;

		// set default scene font unscii

		// watch for resize
		this.addComponentListener(this);

		// set up canvas
		this.canvas.setBounds(0, 0, this.canvasSize.width, this.canvasSize.height);
		this.canvas.setIgnoreRepaint(true);

		this.canvas.addKeyListener(this);
		this.canvas.addMouseListener(this);
		this.canvas.addMouseMotionListener(this);
		this.canvas.addMouseWheelListener(this);

		// TODO: solve canvas

		// create widget anchors 
		this.widgetAnchors.put(Widget.Anchor.SO, new Point(0, this.canvasSize.height));
		this.widgetAnchors.put(Widget.Anchor.S , new Point(this.canvasSize.width / 2, this.canvasSize.height));
		this.widgetAnchors.put(Widget.Anchor.SE, new Point(this.canvasSize.width, this.canvasSize.height));
		this.widgetAnchors.put(Widget.Anchor.E , new Point(this.canvasSize.width, this.canvasSize.width / 2));
		this.widgetAnchors.put(Widget.Anchor.NE, new Point(this.canvasSize.width, 0));
		this.widgetAnchors.put(Widget.Anchor.N , new Point(this.canvasSize.width / 2, 0));
		this.widgetAnchors.put(Widget.Anchor.NO, new Point(0, 0));
		this.widgetAnchors.put(Widget.Anchor.O , new Point(0, this.canvasSize.height / 2));

		// this.add(this.canvas, BorderLayout.CENTER);
		this.build();

		// TODO: this will be controlled in the settings
		this.addWidget(new PerfView("default-perfview", 0, 0));
	}

	public Scene(Game game) {
		this(game, "");
	}

	/* */

	/* abstract methods */
	// runs when the the scene thread starts
	protected abstract void build();
	// runs on each tick
	protected abstract void update(long deltaNanoTime);
	protected abstract void render(Graphics2D g);

	protected void updateWidgets(long deltaNanoTime) {
		for (Widget w : this.dynamicWidgetsCache) {
			((Dynamic) w).update(deltaNanoTime);
		}
	}

	protected void renderWidgets(Graphics2D g) {
		for (Widget w : this.widgets) {
			Point absPos = new Point(this.widgetAnchors.get(w.getAnchor()));
			absPos.translate(w.getX(), w.getY());

			Graphics2D widgetGraphics = (Graphics2D) g.create(
				absPos.x, absPos.y, w.getWidth(), w.getHeight()
			);

			w.render(widgetGraphics);
			widgetGraphics.dispose();
		}
	}

	/* widgets management */
	protected void addWidget(Widget widget) {
		this.widgets.add(widget);

		if (widget instanceof Dynamic) {
			this.dynamicWidgetsCache.add(widget);
		}

		if (widget instanceof Clickable) {
			this.clickableWidgetsCache.add(widget);
		}
	}

	protected void removeWidget(Widget widget) {
		// TODO
		throw new UnsupportedOperationException("TODO");
	}

	/* request scenes */
	protected synchronized void requestPrevScene() {
		this.requestedPrevScene = true;
	}

	protected synchronized boolean isRequestingPrevScene() {
		return this.requestedPrevScene;
	}

	protected synchronized void requestScene(Scene sc) {
		if (this.requestedScene != null)
			throw new UnsupportedOperationException("only one scene can be requested at once");

		this.requestedScene = sc;
	}

	// TODO: protected synchronized void requestScene(String uniqueName) {}

	public synchronized boolean isRequestingScene() {
		return this.requestedScene != null;
	}

	public synchronized Scene getRequestedScene() {
		Scene requested = this.requestedScene;
		this.requestedScene = null;

		return requested;
	}

	/* runnable implementation */
	public void run() {
		long beforeTime, afterTime, timeDiff = 0, sleepTime;
		long overSleepTime = 0L;
		int noDelays = 0;

		this.running = true;

		// wait for the canvas to be ready
		// this is required otherwise createBufferStrategy()
		// throws an IllegalStateException
		while (!this.canvas.isDisplayable() && running);

		// initialize canvas buffer
		// the condition checks because the while above can be interrupted by
		// changing this.running
		// TODO: this is because of the MainMenuScene which hides the canvas
		//       when the scene will be fixed this if can be removed
		if (this.canvas.isDisplayable()) {
			this.canvas.createBufferStrategy(2);
			this.buffer = this.canvas.getBufferStrategy();
			this.canvas.requestFocus();	
		}

		while (running) {
			beforeTime = System.nanoTime();

			// render on a double buffer
			do {
				do {
					Graphics2D g = (Graphics2D) this.buffer.getDrawGraphics();
					g.addRenderingHints(Scene.RENDERING_HINTS);
					g.setFont(Fonts.DEFAULT);
					this.render(g);
					this.renderWidgets(g);
					g.dispose();
				// repeat if the rendering buffer contents were restored
				} while (this.buffer.contentsRestored() && running);
			// repeat if the drawing buffer contents were lost
			} while (this.buffer.contentsLost() && running);

			try {
				this.buffer.show();
			} catch (IllegalStateException ex) {
				// this happens when the scene is hidden or the frame is disposed
				// for example then the thread is stopped, and so this exception
				// can be ignored
			}

			// update game and widgets
			this.update(Scene.DESIRED_DELTA_LOOP_NS - timeDiff);
			this.updateWidgets(Scene.DESIRED_DELTA_LOOP_NS - timeDiff);
			this.game.update(Scene.DESIRED_DELTA_LOOP_NS - timeDiff);

			afterTime = System.nanoTime();
			timeDiff = afterTime - beforeTime;
			sleepTime = (Scene.DESIRED_DELTA_LOOP_NS - timeDiff) - overSleepTime;


			// if sleep is needed (too fast)
			if (sleepTime > 0) {
				try {
					Thread.sleep(sleepTime/(1000*1000));
				} catch (InterruptedException ex) {
					// ex.printStackTrace();
				}

				overSleepTime = (System.nanoTime() - afterTime) - sleepTime;

			// if sleep is not needed (too slow)
			} else {
				overSleepTime = 0L;
				// if the thread has been late for too much time, give up
				// the cpu to other threads
				if (++noDelays >= Scene.NO_DELAYS_PER_YELD) {
					Thread.yield();
					noDelays = 0;
				}
			}

			if (this.threadPaused) {
				this.pauseLock.lock();
				this.threadResumed.awaitUninterruptibly();
				this.pauseLock.unlock();
			}
		}
	}

	/* game pause controls */
	public void stop() {
		// stop thread even if paused
		this.resumeThread();
		this.running = false;
	}

	public void pauseThread() {
		this.threadPaused = true;
	}

	public void resumeThread() {
		if (!this.threadPaused)
			return;

		this.threadPaused = false;
		this.threadResumed.signal();
	}


	// automagically set the canvas size to the parent's size
	// WARNING: does not always work
	// TODO: why doesn't this always work?
	public synchronized void updateCanvasSize() {
		this.updateCanvasSize(this.getParent().getSize());
	}

	// this one always works
	public synchronized void updateCanvasSize(Dimension newSize) {
		this.canvasSize = newSize;

		this.widgetAnchors.get(Widget.Anchor.SO).move(0, newSize.height);
		this.widgetAnchors.get(Widget.Anchor.S ).move(newSize.width / 2, newSize.height);
		this.widgetAnchors.get(Widget.Anchor.SE).move(newSize.width, newSize.height);
		this.widgetAnchors.get(Widget.Anchor.E ).move(newSize.width, newSize.width / 2);
		this.widgetAnchors.get(Widget.Anchor.NE).move(newSize.width, 0);
		this.widgetAnchors.get(Widget.Anchor.N ).move(newSize.width / 2, 0);
		// this.widgetAnchors.get(Widget.Anchor.NO).move(0, 0);
		this.widgetAnchors.get(Widget.Anchor.O ).move(0, newSize.height / 2);
	}

	/* key listener */
	@Override public void keyTyped(KeyEvent e) {}
	@Override public void keyPressed(KeyEvent e) {}
	@Override public void keyReleased(KeyEvent e) {}
	
	/* mouse listener */
	@Override
	public void mouseClicked(MouseEvent e) {
		for (Widget w : this.clickableWidgetsCache) {
			((Clickable) w).mouseClick(e.getPoint());
		}
	}

	@Override public void mouseEntered(MouseEvent e) {}
	@Override public void mouseExited(MouseEvent e) {}
	@Override public void mousePressed(MouseEvent e) {}
	@Override public void mouseReleased(MouseEvent e) {}
	@Override public void mouseDragged(MouseEvent e) {}
	@Override public void mouseMoved(MouseEvent e) {}
	@Override public void mouseWheelMoved(MouseWheelEvent e) {}

	/* component listener */
	@Override
	public void componentResized(ComponentEvent e) {
		this.updateCanvasSize();
	}

	@Override public void componentMoved(ComponentEvent e) {}
	@Override public void componentShown(ComponentEvent e) {}
	@Override public void componentHidden(ComponentEvent e) {}

}