-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathLwjglWindow.java
More file actions
813 lines (667 loc) · 26.4 KB
/
LwjglWindow.java
File metadata and controls
813 lines (667 loc) · 26.4 KB
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
/*
* Copyright (c) 2009-2021 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.system.lwjgl;
import com.jme3.input.JoyInput;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.TouchInput;
import com.jme3.input.lwjgl.GlfwJoystickInput;
import com.jme3.input.lwjgl.GlfwKeyInput;
import com.jme3.input.lwjgl.GlfwMouseInput;
import com.jme3.math.Vector2f;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeContext;
import com.jme3.system.JmeSystem;
import com.jme3.system.NanoTimer;
import com.jme3.util.BufferUtils;
import com.jme3.util.SafeArrayList;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWFramebufferSizeCallback;
import org.lwjgl.glfw.GLFWImage;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.glfw.GLFWWindowFocusCallback;
import org.lwjgl.glfw.GLFWWindowSizeCallback;
import org.lwjgl.system.Platform;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.system.Configuration;
import org.lwjgl.system.Platform;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.system.MemoryUtil.NULL;
/**
* A wrapper class over the GLFW framework in LWJGL 3.
*
* @author Daniel Johansson
*/
public abstract class LwjglWindow extends LwjglContext implements Runnable {
private static final Logger LOGGER = Logger.getLogger(LwjglWindow.class.getName());
private static final EnumSet<JmeContext.Type> SUPPORTED_TYPES = EnumSet.of(
JmeContext.Type.Display,
JmeContext.Type.Canvas,
JmeContext.Type.OffscreenSurface);
private static final Map<String, Runnable> RENDER_CONFIGS = new HashMap<>();
static {
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL30, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL31, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL32, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL33, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL40, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL41, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL42, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL43, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL44, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL45, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
});
}
protected final AtomicBoolean needClose = new AtomicBoolean(false);
protected final AtomicBoolean needRestart = new AtomicBoolean(false);
private final JmeContext.Type type;
private final SafeArrayList<WindowSizeListener> windowSizeListeners = new SafeArrayList<>(WindowSizeListener.class);
private GLFWErrorCallback errorCallback;
private GLFWWindowSizeCallback windowSizeCallback;
private GLFWFramebufferSizeCallback framebufferSizeCallback;
private GLFWWindowFocusCallback windowFocusCallback;
private Thread mainThread;
private long window = NULL;
private int frameRateLimit = -1;
protected boolean wasActive = false;
protected boolean autoFlush = true;
protected boolean allowSwapBuffers = false;
// temp variables used for glfw calls
private int width[] = new int[1];
private int height[] = new int[1];
private final Vector2f currentScale = new Vector2f(1, 1);
public LwjglWindow(final JmeContext.Type type) {
if (!SUPPORTED_TYPES.contains(type)) {
throw new IllegalArgumentException("Unsupported type '" + type.name() + "' provided");
}
this.type = type;
}
/**
* Registers the specified listener to get notified when window size changes.
*
* @param listener The WindowSizeListener to register.
*/
public void registerWindowSizeListener(WindowSizeListener listener) {
windowSizeListeners.add(listener);
}
/**
* Removes the specified listener from the listeners list.
*
* @param listener The WindowSizeListener to remove.
*/
public void removeWindowSizeListener(WindowSizeListener listener) {
windowSizeListeners.remove(listener);
}
/**
* @return Type.Display or Type.Canvas
*/
@Override
public JmeContext.Type getType() {
return type;
}
/**
* Set the title if it's a windowed display
*
* @param title the title to set
*/
@Override
public void setTitle(final String title) {
if (created.get() && window != NULL) {
glfwSetWindowTitle(window, title);
}
}
/**
* Restart if it's a windowed or full-screen display.
*/
@Override
public void restart() {
if (created.get()) {
needRestart.set(true);
} else {
LOGGER.warning("Display is not created, cannot restart window.");
}
}
/**
* Apply the settings, changing resolution, etc.
*
* @param settings the settings to apply when creating the context.
*/
protected void createContext(final AppSettings settings) {
glfwSetErrorCallback(errorCallback = new GLFWErrorCallback() {
@Override
public void invoke(int error, long description) {
final String message = GLFWErrorCallback.getDescription(description);
listener.handleError(message, new Exception(message));
}
});
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints();
final String renderer = settings.getRenderer();
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
RENDER_CONFIGS.computeIfAbsent(renderer, s -> () -> {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_FALSE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
}).run();
if (settings.getBoolean("RendererDebug")) {
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
}
if (settings.isGammaCorrection()) {
glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
}
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_RESIZABLE, settings.isResizable() ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_DEPTH_BITS, settings.getDepthBits());
glfwWindowHint(GLFW_STENCIL_BITS, settings.getStencilBits());
glfwWindowHint(GLFW_SAMPLES, settings.getSamples());
glfwWindowHint(GLFW_STEREO, settings.useStereo3D() ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_REFRESH_RATE, settings.getFrequency()<=0?GLFW_DONT_CARE:settings.getFrequency());
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, settings.isUseRetinaFrameBuffer() ? GLFW_TRUE : GLFW_FALSE);
if (settings.getBitsPerPixel() == 24) {
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
} else if (settings.getBitsPerPixel() == 16) {
glfwWindowHint(GLFW_RED_BITS, 5);
glfwWindowHint(GLFW_GREEN_BITS, 6);
glfwWindowHint(GLFW_BLUE_BITS, 5);
}
glfwWindowHint(GLFW_ALPHA_BITS, settings.getAlphaBits());
// TODO: Add support for monitor selection
long monitor = NULL;
if (settings.isFullscreen()) {
monitor = glfwGetPrimaryMonitor();
}
final GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
if (settings.getWindowWidth() <= 0 || settings.getWindowHeight() <= 0) {
settings.setWindowSize(videoMode.width(), videoMode.height());
} else {
settings.setWindowSize(settings.getWindowWidth(), settings.getWindowHeight());
}
// Assume default framebuffer size == window size
settings.setResolution(settings.getWindowWidth(), settings.getWindowHeight());
window = glfwCreateWindow(settings.getWindowWidth(), settings.getWindowHeight(), settings.getTitle(), monitor, NULL);
if (window == NULL) {
throw new RuntimeException("Failed to create the GLFW window");
}
glfwSetWindowFocusCallback(window, windowFocusCallback = new GLFWWindowFocusCallback() {
@Override
public void invoke(final long window, final boolean focus) {
if (wasActive != focus) {
if (!wasActive) {
listener.gainFocus();
timer.reset();
} else {
listener.loseFocus();
}
wasActive = !wasActive;
}
}
});
if (!settings.isFullscreen()) {
if (settings.getCenterWindow()) {
// Center the window
glfwSetWindowPos(window,
(videoMode.width() - settings.getWidth()) / 2,
(videoMode.height() - settings.getHeight()) / 2);
} else {
glfwSetWindowPos(window,
settings.getWindowXPosition(),
settings.getWindowYPosition());
}
}
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable vsync
if (settings.isVSync()) {
glfwSwapInterval(1);
} else {
glfwSwapInterval(0);
}
setWindowIcon(settings);
showWindow();
// HACK: the framebuffer seems to be initialized with the wrong size
// on some HiDPI platforms until glfwPollEvents is called 2 or 3 times
for (int i = 0; i < 4; i++) glfwPollEvents();
// Windows resize callback
glfwSetWindowSizeCallback(window, windowSizeCallback = new GLFWWindowSizeCallback() {
@Override
public void invoke(final long window, final int width, final int height) {
// This is the window size, never to passed to any pixel based stuff!
// https://www.glfw.org/docs/latest/window_guide.html#window_size
onWindowSizeChanged(width, height);
// Notify listeners
for (WindowSizeListener listener : windowSizeListeners.getArray()) {
listener.onWindowSizeChanged(width, height);
}
updateDefaultFramebufferSize(true);
}
});
// Add a framebuffer resize callback which delegates to the listener
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(final long window, final int width, final int height) {
updateDefaultFramebufferSize(true);
}
});
allowSwapBuffers = settings.isSwapBuffers();
// Create OpenCL
if (settings.isOpenCLSupport()) {
initOpenCL(window);
}
updateDefaultFramebufferSize(false);
}
private void updateDefaultFramebufferSize(boolean updateListener) {
// If default framebuffer size is different than window size (e.g. HiDPI)
int[] width = new int[1];
int[] height = new int[1];
glfwGetFramebufferSize(window, width, height);
Vector2f scale = getWindowContentScale(null);
if (updateListener) {
if (settings.getWidth() != width[0] || settings.getHeight() != height[0]) {
listener.reshape(width[0], height[0]);
}
if(!scale.equals(currentScale)){
listener.rescale(scale.x, scale.y);
currentScale.set(scale);
}
}
settings.setResolution(width[0], height[0]);
}
private void onWindowSizeChanged(final int width, final int height) {
settings.setResolution(width, height);
}
protected void showWindow() {
glfwShowWindow(window);
}
/**
* Set custom icons to the window of this application.
*
* @param settings settings for getting the icons
*/
protected void setWindowIcon(final AppSettings settings) {
final Object[] icons = settings.getIcons();
if (icons == null) return;
final GLFWImage[] images = imagesToGLFWImages(icons);
try (final GLFWImage.Buffer iconSet = GLFWImage.malloc(images.length)) {
for (int i = images.length - 1; i >= 0; i--) {
final GLFWImage image = images[i];
iconSet.put(i, image);
}
glfwSetWindowIcon(window, iconSet);
}
}
/**
* Convert array of images to array of {@link GLFWImage}.
*/
private GLFWImage[] imagesToGLFWImages(final Object[] images) {
final GLFWImage[] out = new GLFWImage[images.length];
for (int i = 0; i < images.length; i++) {
final BufferedImage image = (BufferedImage) images[i];
out[i] = imageToGLFWImage(image);
}
return out;
}
/**
* Convert the {@link BufferedImage} to the {@link GLFWImage}.
*/
private GLFWImage imageToGLFWImage(BufferedImage image) {
if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) {
final BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
final Graphics2D graphics = convertedImage.createGraphics();
final int targetWidth = image.getWidth();
final int targetHeight = image.getHeight();
graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null);
graphics.dispose();
image = convertedImage;
}
final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
for (int i = 0; i < image.getHeight(); i++) {
for (int j = 0; j < image.getWidth(); j++) {
int colorSpace = image.getRGB(j, i);
buffer.put((byte) ((colorSpace << 8) >> 24));
buffer.put((byte) ((colorSpace << 16) >> 24));
buffer.put((byte) ((colorSpace << 24) >> 24));
buffer.put((byte) (colorSpace >> 24));
}
}
buffer.flip();
final GLFWImage result = GLFWImage.create();
result.set(image.getWidth(), image.getHeight(), buffer);
return result;
}
/**
* Destroy the context.
*/
protected void destroyContext() {
try {
if (renderer != null) {
renderer.cleanup();
}
if (errorCallback != null) {
// We need to specifically set this to null as we might set a new callback before we reinit GLFW
glfwSetErrorCallback(null);
errorCallback.close();
errorCallback = null;
}
if (windowSizeCallback != null) {
windowSizeCallback.close();
windowSizeCallback = null;
}
if (framebufferSizeCallback != null) {
framebufferSizeCallback.close();
framebufferSizeCallback = null;
}
if (windowFocusCallback != null) {
windowFocusCallback.close();
windowFocusCallback = null;
}
if (window != NULL) {
glfwDestroyWindow(window);
window = NULL;
}
} catch (final Exception ex) {
listener.handleError("Failed to destroy context", ex);
}
}
@Override
public void create(boolean waitFor) {
if (created.get()) {
LOGGER.warning("create() called when display is already created!");
return;
}
if (Platform.get() == Platform.MACOSX) {
// NOTE: this is required for Mac OS X!
mainThread = Thread.currentThread();
mainThread.setName("jME3 Main");
if (waitFor) {
LOGGER.warning("create(true) is not supported for macOS!");
}
run();
} else {
mainThread = new Thread(this, "jME3 Main");
mainThread.start();
if (waitFor) {
waitFor(true);
}
}
}
/**
* Does LWJGL display initialization in the OpenGL thread
*
* @return returns {@code true} if the context initialization was successful
*/
protected boolean initInThread() {
try {
if (!JmeSystem.isLowPermissions()) {
// Enable uncaught exception handler only for current thread
Thread.currentThread().setUncaughtExceptionHandler((thread, thrown) -> {
listener.handleError("Uncaught exception thrown in " + thread.toString(), thrown);
if (needClose.get()) {
// listener.handleError() has requested the
// context to close. Satisfy request.
deinitInThread();
}
});
}
String libraryName = settings.getString("GlfwLibraryName");
if (libraryName == null) { // use the (platform-dependent) default
libraryName = (Platform.get() == Platform.MACOSX) ? "glfw_async" : "glfw";
}
Configuration.GLFW_LIBRARY_NAME.set(libraryName);
timer = new NanoTimer();
// For canvas, this will create a PBuffer,
// allowing us to query information.
// When the canvas context becomes available, it will
// be replaced seamlessly.
createContext(settings);
printContextInitInfo();
created.set(true);
super.internalCreate();
} catch (Exception ex) {
try {
if (window != NULL) {
glfwDestroyWindow(window);
window = NULL;
}
} catch (Exception ex2) {
LOGGER.log(Level.WARNING, null, ex2);
}
listener.handleError("Failed to create display", ex);
return false; // if we failed to create display, do not continue
}
listener.initialize();
updateDefaultFramebufferSize(true);
return true;
}
/**
* execute one iteration of the render loop in the OpenGL thread
*/
protected void runLoop() {
// If a restart is required, lets recreate the context.
if (needRestart.getAndSet(false)) {
restartContext();
}
if (!created.get()) {
throw new IllegalStateException();
}
listener.update();
// All this does is call glfwSwapBuffers().
// If the canvas is not active, there's no need to waste time
// doing that.
if (renderable.get()) {
// calls swap buffers, etc.
try {
if (allowSwapBuffers && autoFlush) {
glfwSwapBuffers(window);
}
} catch (Throwable ex) {
listener.handleError("Error while swapping buffers", ex);
}
}
// Subclasses just call GLObjectManager. Clean up objects here.
// It is safe ... for now.
if (renderer != null) {
renderer.postFrame();
}
if (autoFlush) {
if (frameRateLimit != getSettings().getFrameRate()) {
setFrameRateLimit(getSettings().getFrameRate());
}
} else if (frameRateLimit != 20) {
setFrameRateLimit(20);
}
Sync.sync(frameRateLimit);
glfwPollEvents();
}
private void restartContext() {
try {
destroyContext();
createContext(settings);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Failed to set display settings!", ex);
}
// Reinitialize context flags and such
reinitContext();
// We need to reinit the mouse and keyboard input as they are tied to a window handle
if (keyInput != null && keyInput.isInitialized()) {
keyInput.resetContext();
}
if (mouseInput != null && mouseInput.isInitialized()) {
mouseInput.resetContext();
}
LOGGER.fine("Display restarted.");
}
private void setFrameRateLimit(int frameRateLimit) {
this.frameRateLimit = frameRateLimit;
}
/**
* De-initialize in the OpenGL thread.
*/
protected void deinitInThread() {
listener.destroy();
destroyContext();
super.internalDestroy();
glfwTerminate();
LOGGER.fine("Display destroyed.");
}
@Override
public void run() {
if (listener == null) {
throw new IllegalStateException("SystemListener is not set on context!"
+ "Must set with JmeContext.setSystemListener().");
}
LOGGER.log(Level.FINE, "Using LWJGL {0}", Version.getVersion());
if (!initInThread()) {
LOGGER.log(Level.SEVERE, "Display initialization failed. Cannot continue.");
return;
}
while (true) {
runLoop();
if (needClose.get()) {
break;
}
if (glfwWindowShouldClose(window)) {
listener.requestClose(false);
}
}
deinitInThread();
}
@Override
public JoyInput getJoyInput() {
if (joyInput == null) {
joyInput = new GlfwJoystickInput();
}
return joyInput;
}
@Override
public MouseInput getMouseInput() {
if (mouseInput == null) {
mouseInput = new GlfwMouseInput(this);
}
return mouseInput;
}
@Override
public KeyInput getKeyInput() {
if (keyInput == null) {
keyInput = new GlfwKeyInput(this);
}
return keyInput;
}
@Override
public TouchInput getTouchInput() {
return null;
}
@Override
public void setAutoFlushFrames(boolean enabled) {
this.autoFlush = enabled;
}
@Override
public void destroy(boolean waitFor) {
needClose.set(true);
if (mainThread == Thread.currentThread()) {
// Ignore waitFor.
return;
}
if (waitFor) {
waitFor(false);
}
}
public long getWindowHandle() {
return window;
}
/**
* Get the window content scale, for HiDPI support.
*
* The content scale is the ratio between the current DPI and the platform's default DPI.
* This is especially important for text and any UI elements. If the pixel dimensions of
* your UI scaled by this look appropriate on your machine then it should appear at a
* reasonable size on other machines regardless of their DPI and scaling settings. This
* relies on the system DPI and scaling settings being somewhat correct.
*
* @param store A vector2f to store the result
* @return The window content scale
* @see <a href="https://www.glfw.org/docs/latest/window_guide.html#window_scale">Window content scale</a>
*/
public Vector2f getWindowContentScale(Vector2f store) {
if (store == null) store = new Vector2f();
glfwGetFramebufferSize(window, width, height);
store.set(width[0], height[0]);
glfwGetWindowSize(window, width, height);
store.x /= width[0];
store.y /= height[0];
return store;
}
}