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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
|
/*
* NEWTWin.java
* Copyright (C) 2004
*
*/
package jake2.render.opengl;
import jake2.Defines;
import jake2.Globals;
import jake2.SizeChangeListener;
import jake2.client.VID;
import jake2.game.cvar_t;
import jake2.qcommon.Cbuf;
import jake2.qcommon.Cvar;
import jake2.render.Base;
import jake2.sys.NEWTKBD;
import java.io.PrintStream;
import java.util.List;
import javax.media.nativewindow.CapabilitiesChooser;
import javax.media.nativewindow.WindowClosingProtocol.WindowClosingMode;
import javax.media.nativewindow.util.Dimension;
import javax.media.nativewindow.util.DimensionImmutable;
import javax.media.nativewindow.util.SurfaceSize;
import javax.media.opengl.*;
import jogamp.opengl.FPSCounterImpl;
import com.jogamp.common.os.Platform;
import com.jogamp.newt.*;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.event.*;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.newt.util.MonitorModeUtil;
import com.jogamp.opengl.GenericGLCapabilitiesChooser;
public class NEWTWin {
final static boolean DEBUG = false;
/** Required due to AWT lock of surface, if Applet! */
final static boolean FORCE_RELEASE_CTX_VAL = true;
MonitorMode oldDisplayMode = null;
volatile Screen screen = null;
volatile GLWindow window = null;
volatile GameAnimatorControl animCtrl = null;
/** Encapsulateed AWT dependency */
volatile Object newtCanvasObject = null;
boolean forceReleaseCtx = false;
volatile boolean shouldQuit = false;
volatile boolean shouldPause = false;
volatile boolean shouldReparent = false;
volatile boolean isAnimating = false;
public List<MonitorMode> getModeList() {
if( null != window ) {
final MonitorDevice mainMonitor = window.getMainMonitor();
return mainMonitor.getSupportedModes();
} else {
return screen.getMonitorModes();
}
}
public MonitorMode findDisplayMode(DimensionImmutable dim) {
final List<MonitorMode> sml = MonitorModeUtil.filterByResolution(getModeList(), dim);
if(sml.size() == 0) {
return oldDisplayMode;
}
return sml.get(0);
}
public String getModeString(MonitorMode mm) {
final SurfaceSize ss = mm.getSurfaceSize();
final DimensionImmutable m = ss.getResolution();
final StringBuffer sb = new StringBuffer();
sb.append(m.getWidth());
sb.append('x');
sb.append(m.getHeight());
sb.append('x');
sb.append(ss.getBitsPerPixel());
sb.append('@');
sb.append(mm.getRefreshRate());
sb.append("Hz");
return sb.toString();
}
/**
* @param dim
* @param mode
* @param fullscreen
* @param driverName
* @return enum Base.rserr_t
*/
public int setMode(GLProfile glp, Dimension dim, int mode, boolean fullscreen, String driverName) {
final Dimension newDim = new Dimension();
VID.Printf(Defines.PRINT_ALL, "Initializing OpenGL display for profile "+glp+"\n");
if(null == screen) {
screen = NewtFactory.createScreen(NewtFactory.createDisplay(null), 0);
screen.addReference(); // trigger native creation
} else if( !screen.isNativeValid() ) {
screen.addReference(); // trigger native creation
}
if (!VID.GetModeInfo(newDim, mode)) {
VID.Printf(Defines.PRINT_ALL, " invalid mode\n");
return Base.rserr_invalid_mode;
}
VID.Printf(Defines.PRINT_ALL, "...setting mode " + mode + ", " + newDim.getWidth() + " x " + newDim.getHeight() + ", fs " + fullscreen + ", driver " + driverName + "\n");
// destroy the existing window, not screen
shutdownImpl(false);
if(null != window) {
throw new InternalError("XXX");
}
final GLCapabilities caps = new GLCapabilities(glp);
CapabilitiesChooser chooser = null; // default
{
final cvar_t v = Cvar.Get("jogl_rgb565", "0", 0);
if( v.value != 0f ) {
caps.setRedBits(5);
caps.setGreenBits(6);
caps.setBlueBits(5);
chooser = new GenericGLCapabilitiesChooser(); // don't trust native GL-TK chooser
}
}
window = GLWindow.create(screen, caps);
window.setAutoSwapBufferMode(false);
window.setDefaultCloseOperation(WindowClosingMode.DO_NOTHING_ON_CLOSE); // we do handle QUIT on our own, no GLWindow.display() called.
window.setCapabilitiesChooser(chooser);
window.addWindowListener(new WindowAdapter() {
public void windowDestroyNotify(WindowEvent e) {
shouldQuit = !Globals.appletMode && null != window; // not applet and not already in shutdown ?
}
public void windowResized(WindowEvent e) {
propagateNewSize();
}
});
window.setTitle("Jake2 ("+driverName+"-newt-"+glp.getName().toLowerCase()+")");
animCtrl = new GameAnimatorControl();
window.setAnimator(animCtrl);
final MonitorDevice mainMonitor = window.getMainMonitor();
if (oldDisplayMode == null) {
oldDisplayMode = mainMonitor.getCurrentMode();
}
// We need to feed the NEWT Window to the NEWTKBD
NEWTKBD.Init(window);
window.addWindowListener(NEWTKBD.listener);
window.addKeyListener(NEWTKBD.listener);
window.addMouseListener(NEWTKBD.listener);
window.setSize(newDim.getWidth(), newDim.getHeight());
isAnimating = true; // no display() invocation on other thread!
if( !fullscreen && Globals.appletMode ) {
forceReleaseCtx = FORCE_RELEASE_CTX_VAL;
// Notify the size listener about the change
final SizeChangeListener listener = Globals.sizeChangeListener;
if (listener != null) {
listener.sizeChanged(newDim.getWidth(), newDim.getHeight());
}
window.addKeyListener( new ReparentKeyListener() );
final NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(window);
final java.applet.Applet applet = (java.applet.Applet) Globals.applet;
final Runnable appletAddAction = new Runnable() {
public void run() {
applet.add(newtCanvasAWT, java.awt.BorderLayout.CENTER);
applet.validate();
newtCanvasAWT.setFocusable(true);
newtCanvasAWT.requestFocus();
if( Platform.OSType.MACOS == Platform.getOSType() && newtCanvasAWT.isOffscreenLayerSurfaceEnabled() ) {
System.err.println("XXX Relayout");
// force relayout
final int cW = newtCanvasAWT.getWidth();
final int cH = newtCanvasAWT.getHeight();
newtCanvasAWT.setSize(cW+1, cH+1);
newtCanvasAWT.setSize(cW, cH);
}
} };
if( java.awt.EventQueue.isDispatchThread() ) {
System.err.println("XXX Adding on AWT EDT - same thread");
appletAddAction.run();
} else {
System.err.println("XXX Adding on AWT EDT - off thread");
try {
java.awt.EventQueue.invokeAndWait(appletAddAction);
} catch (Exception e) {
throw new RuntimeException("NEWT Exception during NewtCanvasAWT on AWT-EDT", e);
}
}
newtCanvasObject = newtCanvasAWT;
int w=0;
while ( w<10 && !window.isNativeValid()|| !window.isRealized() ) {
w++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
System.err.println("XXX waited = "+w+" * 100 ms");
} else {
forceReleaseCtx = false;
newtCanvasObject = null;
if (fullscreen) {
MonitorMode mm = findDisplayMode(newDim);
final DimensionImmutable smDim = mm.getSurfaceSize().getResolution();
newDim.setWidth( smDim.getWidth() );
newDim.setHeight( smDim.getHeight() );
mainMonitor.setCurrentMode(mm);
VID.Printf(Defines.PRINT_ALL, "...MonitorMode "+mm+'\n');
window.setFullscreen(true);
}
window.setVisible(true);
window.requestFocus();
}
if( !window.isNativeValid()|| !window.isRealized() ) {
throw new RuntimeException("NEWT window didn't not realize: "+window);
}
window.display(); // force GL creation
final GLContext ctx = window.getContext();
if( !ctx.isCreated() ) {
System.err.println("Warning: GL context not created: "+ctx);
}
if( ctx.isCurrent() ) {
throw new RuntimeException("NEWT GL context still current: "+ctx);
}
VID.Printf(Defines.PRINT_ALL, "...reques GLCaps "+window.getRequestedCapabilities()+'\n');
VID.Printf(Defines.PRINT_ALL, "...chosen GLCaps "+window.getChosenGLCapabilities()+'\n');
VID.Printf(Defines.PRINT_ALL, "...size "+window.getWidth()+" x "+window.getHeight()+'\n');
// propagateNewSize("init");
activateGLContext(true);
return Base.rserr_ok;
}
private void propagateNewSize() {
if( null != window ) {
final int width = window.getWidth();
final int height = window.getHeight();
final int _width;
final int mask = ~0x03;
if ((width & 0x03) != 0) {
_width = ( width & mask ) + 4;
} else {
_width = width;
}
VID.Printf(Defines.PRINT_ALL, "Resize: " + width + " x " + height + ", masked " + _width + "x" + height + "\n");
Base.setVid(_width, height);
// let the sound and input subsystems know about the new window
VID.NewWindow(_width, height);
}
}
protected final boolean activateGLContext(boolean force) {
boolean ctxCurrent = false;
if( force || !shouldPause ) {
final GLContext ctx = window.getContext();
if ( null != ctx && GLContext.getCurrent() != ctx ) {
if( DEBUG ) {
System.err.println("GLCtx Current pause "+shouldPause+": "+Thread.currentThread().getName());
}
ctxCurrent = GLContext.CONTEXT_NOT_CURRENT < ctx.makeCurrent();
} else {
ctxCurrent = true;
}
isAnimating = ctxCurrent;
}
return ctxCurrent;
}
protected final void deactivateGLContext() {
final GLContext ctx = window.getContext();
if ( null != ctx && GLContext.getCurrent() == ctx) {
if( DEBUG ) {
System.err.println("GLCtx Release pause "+shouldPause+": "+Thread.currentThread().getName());
}
ctx.release();
}
}
/**
* Performs {@link GLWindow#swapBuffers()}, ticks the fps counter and performs <code>QUIT</code> if requested.
*/
public final void endFrame() {
window.swapBuffers();
animCtrl.fpsCounter.tickFPS();
if( shouldQuit ) {
deactivateGLContext();
Cbuf.ExecuteText(Defines.EXEC_APPEND, "quit");
} else if( shouldReparent ) {
shouldReparent = false;
deactivateGLContext();
if( null != newtCanvasObject && null != window ) {
isAnimating = false; // don't let GLDrawableHelper.invoke(..) defer the GLRunnable (preserving GLState that is on OSX/CALayer)
final NewtCanvasAWT newtCanvasAWT = (NewtCanvasAWT) newtCanvasObject;
if(null == window.getParent()) {
forceReleaseCtx = FORCE_RELEASE_CTX_VAL; // Applet
window.reparentWindow( newtCanvasAWT.getNativeWindow() );
} else {
window.reparentWindow(null);
forceReleaseCtx = false;
}
}
} else if( forceReleaseCtx || shouldPause ) {
deactivateGLContext();
}
}
/** Performs <code>QUIT</code> if requested. */
public final void checkQuit() {
if( shouldQuit ) {
deactivateGLContext();
Cbuf.ExecuteText(Defines.EXEC_APPEND, "quit");
}
}
void shutdown() {
shutdownImpl(true);
}
private void shutdownImpl(boolean withScreen) {
if ( null != window ) {
deactivateGLContext();
final GLWindow _window = window;
window = null;
_window.destroy();
if( null != Globals.applet && null != newtCanvasObject ) {
final java.applet.Applet applet = (java.applet.Applet) Globals.applet;
final NewtCanvasAWT newtCanvasAWT = (NewtCanvasAWT) newtCanvasObject;
final Runnable appletRemoveAction = new Runnable() {
public void run() {
applet.remove(newtCanvasAWT);
applet.validate();
} };
if( java.awt.EventQueue.isDispatchThread() ) {
appletRemoveAction.run();
} else {
try {
java.awt.EventQueue.invokeAndWait(appletRemoveAction);
} catch (Throwable e) {
System.err.println("Catched "+e.getClass().getName()+": "+e.getMessage());
e.printStackTrace();
}
}
newtCanvasAWT.setNEWTChild(null);
newtCanvasObject = null;
}
}
if( withScreen && null != screen ) {
try {
screen.destroy();
} catch (Throwable e) {
System.err.println("Catched "+e.getClass().getName()+": "+e.getMessage());
e.printStackTrace();
}
screen = null;
}
}
class GameAnimatorControl implements GLAnimatorControl {
final FPSCounterImpl fpsCounter;
final Thread thread;
GameAnimatorControl() {
final boolean isARM = Platform.CPUFamily.ARM == Platform.getCPUFamily();
fpsCounter = new FPSCounterImpl();
fpsCounter.setUpdateFPSFrames(isARM ? 60 : 4*60, System.err);
thread = Thread.currentThread();
}
@Override
public final boolean start() {
return false;
}
@Override
public final boolean stop() {
shouldQuit = true;
return true;
}
@Override
public final boolean pause() {
if( DEBUG ) {
System.err.println("GLCtx Pause Anim: "+Thread.currentThread().getName());
Thread.dumpStack();
}
shouldPause = true;
return true;
}
@Override
public final boolean resume() {
shouldPause = false;
return true;
}
@Override
public final boolean isStarted() {
return null != window;
}
@Override
public final boolean isAnimating() {
return isAnimating; // null != window && !shouldPause;
}
@Override
public final boolean isPaused() {
return null == window || shouldPause;
}
@Override
public final Thread getThread() {
return thread;
}
@Override
public final void add(GLAutoDrawable drawable) {}
@Override
public final void remove(GLAutoDrawable drawable) {}
@Override
public final void setUpdateFPSFrames(int frames, PrintStream out) {
fpsCounter.setUpdateFPSFrames(frames, out);
}
@Override
public final void resetFPSCounter() {
fpsCounter.resetFPSCounter();
}
@Override
public final int getUpdateFPSFrames() {
return fpsCounter.getUpdateFPSFrames();
}
@Override
public final long getFPSStartTime() {
return fpsCounter.getFPSStartTime();
}
@Override
public final long getLastFPSUpdateTime() {
return fpsCounter.getLastFPSUpdateTime();
}
@Override
public final long getLastFPSPeriod() {
return fpsCounter.getLastFPSPeriod();
}
@Override
public final float getLastFPS() {
return fpsCounter.getLastFPS();
}
@Override
public final int getTotalFPSFrames() {
return fpsCounter.getTotalFPSFrames();
}
@Override
public final long getTotalFPSDuration() {
return fpsCounter.getTotalFPSDuration();
}
@Override
public final float getTotalFPS() {
return fpsCounter.getTotalFPS();
}
}
class ReparentKeyListener implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
System.err.println(e);
if( !e.isAutoRepeat() ) {
int keyCode = e.getKeyCode();
if( KeyEvent.VK_HOME == keyCode ) {
shouldReparent = true;
}
}
}
@Override
public void keyReleased(KeyEvent e) {
System.err.println(e);
}
}
}
|