forked from processing/processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSurfaceJOGL.java
More file actions
1371 lines (1180 loc) · 43.9 KB
/
PSurfaceJOGL.java
File metadata and controls
1371 lines (1180 loc) · 43.9 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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.opengl;
import java.awt.Component;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import com.jogamp.common.util.IOUtil;
import com.jogamp.common.util.IOUtil.ClassResources;
import com.jogamp.nativewindow.NativeSurface;
import com.jogamp.nativewindow.ScalableSurface;
import com.jogamp.nativewindow.util.Dimension;
import com.jogamp.nativewindow.util.PixelFormat;
import com.jogamp.nativewindow.util.PixelRectangle;
import com.jogamp.opengl.GLAnimatorControl;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.GLProfile;
import com.jogamp.nativewindow.MutableGraphicsConfiguration;
import com.jogamp.nativewindow.WindowClosingProtocol;
import com.jogamp.newt.Display;
import com.jogamp.newt.Display.PointerIcon;
import com.jogamp.newt.MonitorDevice;
import com.jogamp.newt.NewtFactory;
import com.jogamp.newt.Screen;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.event.InputEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PSurface;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
public class PSurfaceJOGL implements PSurface {
/** Selected GL profile */
public static GLProfile profile;
public PJOGL pgl;
protected GLWindow window;
protected FPSAnimator animator;
protected Rectangle screenRect;
private Thread drawExceptionHandler;
protected PApplet sketch;
protected PGraphics graphics;
protected int sketchX;
protected int sketchY;
protected int sketchWidth0;
protected int sketchHeight0;
protected int sketchWidth;
protected int sketchHeight;
protected Display display;
protected Screen screen;
protected List<MonitorDevice> monitors;
protected MonitorDevice displayDevice;
protected Throwable drawException;
private final Object drawExceptionMutex = new Object();
protected NewtCanvasAWT canvas;
protected float[] currentPixelScale = {0, 0};
protected boolean external = false;
public PSurfaceJOGL(PGraphics graphics) {
this.graphics = graphics;
this.pgl = (PJOGL) ((PGraphicsOpenGL)graphics).pgl;
}
public void initOffscreen(PApplet sketch) {
this.sketch = sketch;
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
if (window != null) {
canvas = new NewtCanvasAWT(window);
canvas.setBounds(0, 0, window.getWidth(), window.getHeight());
canvas.setFocusable(true);
}
}
public void initFrame(PApplet sketch) {
this.sketch = sketch;
initIcons();
// https://jogamp.org/bugzilla/show_bug.cgi?id=1290
File mesaLib = new File("/usr/lib/arm-linux-gnueabihf/libGLESv2.so.2");
if (mesaLib.exists()) {
System.out.println("\nIf you are receiving an error regarding the undefined symbol bcm_host_init, " +
"make sure you have the package libgles2-mesa deinstalled. This can be done " +
"by executing \"sudo aptitude remove libgles2-mesa\" in the terminal, and is " +
"a known issue with the Raspbian distribution.\n");
}
initDisplay();
initGL();
initWindow();
initListeners();
initAnimator();
}
public Object getNative() {
return window;
}
protected void initDisplay() {
Display tmpDisplay = NewtFactory.createDisplay(null);
tmpDisplay.addReference();
Screen tmpScreen = NewtFactory.createScreen(tmpDisplay, 0);
tmpScreen.addReference();
monitors = new ArrayList<MonitorDevice>();
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] awtDevices = environment.getScreenDevices();
List<MonitorDevice> newtDevices = tmpScreen.getMonitorDevices();
// AWT and NEWT name devices in different ways, depending on the platform,
// and also appear to order them in different ways. The following code
// tries to address the differences.
if (PApplet.platform == PConstants.LINUX) {
for (GraphicsDevice device: awtDevices) {
String did = device.getIDstring();
String[] parts = did.split("\\.");
String id1 = "";
if (1 < parts.length) {
id1 = parts[1].trim();
}
MonitorDevice monitor = null;
int id0 = newtDevices.size() > 0 ? newtDevices.get(0).getId() : 0;
for (int i = 0; i < newtDevices.size(); i++) {
MonitorDevice mon = newtDevices.get(i);
String mid = String.valueOf(mon.getId() - id0);
if (id1.equals(mid)) {
monitor = mon;
break;
}
}
if (monitor != null) {
monitors.add(monitor);
}
}
} else if (PApplet.platform == PConstants.WINDOWS) {
// NEWT display id is == (adapterId << 8 | monitorId),
// should be in the same order as AWT
monitors.addAll(newtDevices);
} else { // MAC OSX and others
for (GraphicsDevice device: awtDevices) {
String did = device.getIDstring();
String[] parts = did.split("Display");
String id1 = "";
if (1 < parts.length) {
id1 = parts[1].trim();
}
MonitorDevice monitor = null;
for (int i = 0; i < newtDevices.size(); i++) {
MonitorDevice mon = newtDevices.get(i);
String mid = String.valueOf(mon.getId());
if (id1.equals(mid)) {
monitor = mon;
break;
}
}
if (monitor == null) {
// Didn't find a matching monitor, try using less stringent id check
for (int i = 0; i < newtDevices.size(); i++) {
MonitorDevice mon = newtDevices.get(i);
String mid = String.valueOf(mon.getId());
if (-1 < did.indexOf(mid)) {
monitor = mon;
break;
}
}
}
if (monitor != null) {
monitors.add(monitor);
}
}
}
displayDevice = null;
int displayNum = sketch.sketchDisplay();
if (displayNum > 0) { // if -1, use the default device
if (displayNum <= monitors.size()) {
displayDevice = monitors.get(displayNum - 1);
} else {
System.err.format("Display %d does not exist, " +
"using the default display instead.%n", displayNum);
for (int i = 0; i < monitors.size(); i++) {
System.err.format("Display %d is %s%n", i+1, monitors.get(i));
}
}
} else if (0 < monitors.size()) {
displayDevice = monitors.get(0);
}
if (displayDevice != null) {
screen = displayDevice.getScreen();
display = screen.getDisplay();
} else {
screen = tmpScreen;
display = tmpDisplay;
displayDevice = screen.getPrimaryMonitor();
}
}
protected void initGL() {
// System.out.println("*******************************");
if (profile == null) {
if (PJOGL.profile == 1) {
try {
profile = GLProfile.getGL2ES1();
} catch (GLException ex) {
profile = GLProfile.getMaxFixedFunc(true);
}
} else if (PJOGL.profile == 2) {
try {
profile = GLProfile.getGL2ES2();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
} else if (PJOGL.profile == 3) {
try {
profile = GLProfile.getGL2GL3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL3()) {
PGraphics.showWarning("Requested profile GL3 but is not available, got: " + profile);
}
} else if (PJOGL.profile == 4) {
try {
profile = GLProfile.getGL4ES3();
} catch (GLException ex) {
profile = GLProfile.getMaxProgrammable(true);
}
if (!profile.isGL4()) {
PGraphics.showWarning("Requested profile GL4 but is not available, got: " + profile);
}
} else throw new RuntimeException(PGL.UNSUPPORTED_GLPROF_ERROR);
}
// Setting up the desired capabilities;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
// caps.setPBuffer(false);
// caps.setFBO(false);
// pgl.reqNumSamples = PGL.smoothToSamples(graphics.smooth);
caps.setSampleBuffers(true);
caps.setNumSamples(PGL.smoothToSamples(graphics.smooth));
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
pgl.setCaps(caps);
}
protected void initWindow() {
window = GLWindow.create(screen, pgl.getCaps());
// Make sure that we pass the window close through to exit(), otherwise
// we're likely to have OpenGL try to shut down halfway through rendering
// a frame. Particularly problematic for complex/slow apps.
// https://github.com/processing/processing/issues/4690
window.setDefaultCloseOperation(WindowClosingProtocol.WindowClosingMode.DO_NOTHING_ON_CLOSE);
// if (displayDevice == null) {
//
//
// } else {
// window = GLWindow.create(displayDevice.getScreen(), pgl.getCaps());
// }
boolean spanDisplays = sketch.sketchDisplay() == PConstants.SPAN;
screenRect = spanDisplays ?
new Rectangle(0, 0, screen.getWidth(), screen.getHeight()) :
new Rectangle(0, 0,
displayDevice.getViewportInWindowUnits().getWidth(),
displayDevice.getViewportInWindowUnits().getHeight());
// Set the displayWidth/Height variables inside PApplet, so that they're
// usable and can even be returned by the sketchWidth()/Height() methods.
sketch.displayWidth = screenRect.width;
sketch.displayHeight = screenRect.height;
sketchWidth0 = sketch.sketchWidth();
sketchHeight0 = sketch.sketchHeight();
/*
// Trying to fix
// https://github.com/processing/processing/issues/3401
if (sketch.displayWidth < sketch.width ||
sketch.displayHeight < sketch.height) {
int w = sketch.width;
int h = sketch.height;
if (sketch.displayWidth < w) {
w = sketch.displayWidth;
}
if (sketch.displayHeight < h) {
h = sketch.displayHeight;
}
// sketch.setSize(w, h - 22 - 22);
// graphics.setSize(w, h - 22 - 22);
System.err.println("setting width/height to " + w + " " + h);
}
*/
sketchWidth = sketch.sketchWidth();
sketchHeight = sketch.sketchHeight();
// System.out.println("init: " + sketchWidth + " " + sketchHeight);
boolean fullScreen = sketch.sketchFullScreen();
// Removing the section below because sometimes people want to do the
// full screen size in a window, and it also breaks insideSettings().
// With 3.x, fullScreen() is so easy, that it's just better that way.
// https://github.com/processing/processing/issues/3545
/*
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == sketchWidth &&
screenRect.height == sketchHeight) {
fullScreen = true;
sketch.fullScreen();
}
*/
if (fullScreen || spanDisplays) {
sketchWidth = screenRect.width;
sketchHeight = screenRect.height;
}
float[] reqSurfacePixelScale;
if (graphics.is2X()) {
// Retina
reqSurfacePixelScale = new float[] { ScalableSurface.AUTOMAX_PIXELSCALE,
ScalableSurface.AUTOMAX_PIXELSCALE };
} else {
// Non-retina
reqSurfacePixelScale = new float[] { ScalableSurface.IDENTITY_PIXELSCALE,
ScalableSurface.IDENTITY_PIXELSCALE };
}
window.setSurfaceScale(reqSurfacePixelScale);
window.setSize(sketchWidth, sketchHeight);
window.setResizable(false);
setSize(sketchWidth, sketchHeight);
sketchX = displayDevice.getViewportInWindowUnits().getX();
sketchY = displayDevice.getViewportInWindowUnits().getY();
if (fullScreen) {
PApplet.hideMenuBar();
window.setTopLevelPosition(sketchX, sketchY);
if (spanDisplays) {
window.setFullscreen(monitors);
} else {
List<MonitorDevice> display = Collections.singletonList(displayDevice);
window.setFullscreen(display);
}
}
}
protected void initListeners() {
NEWTMouseListener mouseListener = new NEWTMouseListener();
window.addMouseListener(mouseListener);
NEWTKeyListener keyListener = new NEWTKeyListener();
window.addKeyListener(keyListener);
NEWTWindowListener winListener = new NEWTWindowListener();
window.addWindowListener(winListener);
DrawListener drawlistener = new DrawListener();
window.addGLEventListener(drawlistener);
}
protected void initAnimator() {
if (PApplet.platform == PConstants.WINDOWS) {
// Force Windows to keep timer resolution high by
// sleeping for time which is not a multiple of 10 ms.
// See section "Clocks and Timers on Windows":
// https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks
Thread highResTimerThread = new Thread(() -> {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException ignore) { }
}, "HighResTimerThread");
highResTimerThread.setDaemon(true);
highResTimerThread.start();
}
animator = new FPSAnimator(window, 60);
drawException = null;
animator.setUncaughtExceptionHandler(new GLAnimatorControl.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final GLAnimatorControl animator,
final GLAutoDrawable drawable,
final Throwable cause) {
synchronized (drawExceptionMutex) {
drawException = cause;
drawExceptionMutex.notify();
}
}
});
drawExceptionHandler = new Thread(new Runnable() {
public void run() {
synchronized (drawExceptionMutex) {
try {
while (drawException == null) {
drawExceptionMutex.wait();
}
// System.err.println("Caught exception: " + drawException.getMessage());
if (drawException != null) {
Throwable cause = drawException.getCause();
if (cause instanceof ThreadDeath) {
// System.out.println("caught ThreadDeath");
// throw (ThreadDeath)cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof UnsatisfiedLinkError) {
throw new UnsatisfiedLinkError(cause.getMessage());
} else if (cause == null) {
throw new RuntimeException(drawException.getMessage());
} else {
throw new RuntimeException(cause);
}
}
} catch (InterruptedException e) {
return;
}
}
}
});
drawExceptionHandler.start();
}
@Override
public void setTitle(final String title) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setTitle(title);
}
});
}
@Override
public void setVisible(final boolean visible) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setVisible(visible);
}
});
}
@Override
public void setResizable(final boolean resizable) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setResizable(resizable);
}
});
}
public void setIcon(PImage icon) {
PGraphics.showWarning("Window icons for OpenGL sketches can only be set in settings()\n" +
"using PJOGL.setIcon(filename).");
}
@Override
public void setAlwaysOnTop(final boolean always) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setAlwaysOnTop(always);
}
});
}
protected void initIcons() {
IOUtil.ClassResources res = null;
if (PJOGL.icons == null || PJOGL.icons.length == 0) {
// Default Processing icons
final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
String[] iconImages = new String[sizes.length];
for (int i = 0; i < sizes.length; i++) {
iconImages[i] = "/icon/icon-" + sizes[i] + ".png";
}
res = new ClassResources(iconImages,
PApplet.class.getClassLoader(),
PApplet.class);
} else {
// Loading custom icons from user-provided files.
String[] iconImages = new String[PJOGL.icons.length];
for (int i = 0; i < PJOGL.icons.length; i++) {
iconImages[i] = resourceFilename(PJOGL.icons[i]);
}
res = new ClassResources(iconImages,
sketch.getClass().getClassLoader(),
sketch.getClass());
}
NewtFactory.setWindowIcons(res);
}
@SuppressWarnings("resource")
private String resourceFilename(String filename) {
// The code below comes from PApplet.createInputRaw() with a few adaptations
InputStream stream = null;
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(sketch.dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = sketch.sketchFile(filename);
}
if (file.exists() && !file.isDirectory()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
stream = new FileInputStream(file);
if (stream != null) {
stream.close();
return file.getCanonicalPath();
}
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
ClassLoader cl = sketch.getClass().getClassLoader();
try {
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return "data/" + filename;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
stream.close();
return filename;
}
}
} catch (IOException e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
String path = sketch.dataPath(filename);
stream = new FileInputStream(path);
if (stream != null) {
stream.close();
return path;
}
} catch (IOException e2) { }
try {
String path = sketch.sketchPath(filename);
stream = new FileInputStream(path);
if (stream != null) {
stream.close();
return path;
}
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) {
stream.close();
return filename;
}
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return "";
}
@Override
public void placeWindow(int[] location, int[] editorLocation) {
int x = window.getX() - window.getInsets().getLeftWidth();
int y = window.getY() - window.getInsets().getTopHeight();
int w = window.getWidth() + window.getInsets().getTotalWidth();
int h = window.getHeight() + window.getInsets().getTotalHeight();
if (location != null) {
// System.err.println("place window at " + location[0] + ", " + location[1]);
window.setTopLevelPosition(location[0], location[1]);
} else if (editorLocation != null) {
// System.err.println("place window at editor location " + editorLocation[0] + ", " + editorLocation[1]);
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - w > 10) {
// if it fits to the left of the window
window.setTopLevelPosition(locationX - w, locationY);
} else { // doesn't fit
/*
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + w > sketch.displayWidth - 33) ||
(locationY + h > sketch.displayHeight - 33)) {
// otherwise center on screen
*/
locationX = (sketch.displayWidth - w) / 2;
locationY = (sketch.displayHeight - h) / 2;
/*
}
*/
window.setTopLevelPosition(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
int sketchX = displayDevice.getViewportInWindowUnits().getX();
int sketchY = displayDevice.getViewportInWindowUnits().getY();
window.setTopLevelPosition(sketchX + screenRect.x + (screenRect.width - sketchWidth) / 2,
sketchY + screenRect.y + (screenRect.height - sketchHeight) / 2);
}
Point frameLoc = new Point(x, y);
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
window.setTopLevelPosition(frameLoc.x, 30);
}
}
public void placePresent(int stopColor) {
pgl.initPresentMode(0.5f * (screenRect.width - sketchWidth),
0.5f * (screenRect.height - sketchHeight), stopColor);
window.setSize(screenRect.width, screenRect.height);
PApplet.hideMenuBar();
window.setTopLevelPosition(sketchX + screenRect.x,
sketchY + screenRect.y);
window.setFullscreen(true);
}
public void setupExternalMessages() {
external = true;
}
public void startThread() {
if (animator != null) {
animator.start();
}
}
public void pauseThread() {
if (animator != null) {
animator.pause();
}
}
public void resumeThread() {
if (animator != null) {
animator.resume();
}
}
public boolean stopThread() {
if (drawExceptionHandler != null) {
drawExceptionHandler.interrupt();
drawExceptionHandler = null;
}
if (animator != null) {
return animator.stop();
} else {
return false;
}
}
public boolean isStopped() {
if (animator != null) {
return !animator.isAnimating();
} else {
return true;
}
}
public void setLocation(final int x, final int y) {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.setTopLevelPosition(x, y);
}
});
}
public void setSize(final int width, final int height) {
if (width == sketch.width && height == sketch.height) {
return;
}
if (!pgl.presentMode()) {
sketch.setSize(width, height);
sketchWidth = width;
sketchHeight = height;
graphics.setSize(width, height);
window.setSize(width, height);
}
}
public float getPixelScale() {
if (graphics.is2X()) {
// Even if the graphics are retina, the user might have moved the window
// into a non-retina monitor, so we need to check
window.getCurrentSurfaceScale(currentPixelScale);
return currentPixelScale[0];
} else {
return 1;
}
}
public Component getComponent() {
return canvas;
}
public void setSmooth(int level) {
pgl.reqNumSamples = level;
GLCapabilities caps = new GLCapabilities(profile);
caps.setAlphaBits(PGL.REQUESTED_ALPHA_BITS);
caps.setDepthBits(PGL.REQUESTED_DEPTH_BITS);
caps.setStencilBits(PGL.REQUESTED_STENCIL_BITS);
caps.setSampleBuffers(true);
caps.setNumSamples(pgl.reqNumSamples);
caps.setBackgroundOpaque(true);
caps.setOnscreen(true);
NativeSurface target = window.getNativeSurface();
MutableGraphicsConfiguration config = (MutableGraphicsConfiguration) target.getGraphicsConfiguration();
config.setChosenCapabilities(caps);
}
public void setFrameRate(float fps) {
if (fps < 1) {
PGraphics.showWarning("The OpenGL renderers cannot have a frame rate lower than 1.\nYour sketch will run at 1 frame per second.");
fps = 1;
}
if (animator != null) {
animator.stop();
animator.setFPS((int)fps);
pgl.setFps(fps);
animator.start();
}
}
public void requestFocus() {
display.getEDTUtil().invoke(false, new Runnable() {
@Override
public void run() {
window.requestFocus();
}
});
}
class DrawListener implements GLEventListener {
public void display(GLAutoDrawable drawable) {
if (display.getEDTUtil().isCurrentThreadEDT()) {
// For some reason, the first two frames of the animator are run on the
// EDT, skipping rendering Processing's frame in that case.
return;
}
if (sketch.frameCount == 0) {
if (sketchWidth < sketchWidth0 || sketchHeight < sketchHeight0) {
PGraphics.showWarning("The sketch has been automatically resized to fit the screen resolution");
}
// System.out.println("display: " + window.getWidth() + " "+ window.getHeight() + " - " + sketchWidth + " " + sketchHeight);
requestFocus();
}
if (!sketch.finished) {
pgl.getGL(drawable);
int pframeCount = sketch.frameCount;
sketch.handleDraw();
if (pframeCount == sketch.frameCount || sketch.finished) {
// This hack allows the FBO layer to be swapped normally even if
// the sketch is no looping or finished because it does not call draw(),
// otherwise background artifacts may occur (depending on the hardware/drivers).
pgl.beginRender();
pgl.endRender(sketch.sketchWindowColor());
}
PGraphicsOpenGL.completeFinishedPixelTransfers();
}
if (sketch.exitCalled()) {
PGraphicsOpenGL.completeAllPixelTransfers();
sketch.dispose(); // calls stopThread(), which stops the animator.
sketch.exitActual();
}
}
public void dispose(GLAutoDrawable drawable) {
// sketch.dispose();
}
public void init(GLAutoDrawable drawable) {
pgl.getGL(drawable);
pgl.init(drawable);
sketch.start();
int c = graphics.backgroundColor;
pgl.clearColor(((c >> 16) & 0xff) / 255f,
((c >> 8) & 0xff) / 255f,
((c >> 0) & 0xff) / 255f,
((c >> 24) & 0xff) / 255f);
pgl.clear(PGL.COLOR_BUFFER_BIT);
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
// int c = graphics.backgroundColor;
// pgl.clearColor(((c >> 16) & 0xff) / 255f,
// ((c >> 8) & 0xff) / 255f,
// ((c >> 0) & 0xff) / 255f,
// ((c >> 24) & 0xff) / 255f);
// pgl.clear(PGL.COLOR_BUFFER_BIT);
pgl.resetFBOLayer();
// final float[] valReqSurfacePixelScale = window.getRequestedSurfaceScale(new float[2]);
window.getCurrentSurfaceScale(currentPixelScale);
// final float[] nativeSurfacePixelScale = window.getMaximumSurfaceScale(new float[2]);
// System.err.println("[set PixelScale post]: "+
// valReqSurfacePixelScale[0]+"x"+valReqSurfacePixelScale[1]+" (val) -> "+
// hasSurfacePixelScale[0]+"x"+hasSurfacePixelScale[1]+" (has), "+
// nativeSurfacePixelScale[0]+"x"+nativeSurfacePixelScale[1]+" (native)");
// System.out.println("reshape: " + w + ", " + h);
pgl.getGL(drawable);
// if (!graphics.is2X() && 1 < hasSurfacePixelScale[0]) {
// setSize(w/2, h/2);
// } else {
// setSize(w, h);
// }
setSize((int)(w/currentPixelScale[0]), (int)(h/currentPixelScale[1]));
}
}
protected class NEWTWindowListener implements com.jogamp.newt.event.WindowListener {
public NEWTWindowListener() {
super();
}
@Override
public void windowGainedFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = true;
sketch.focusGained();
}
@Override
public void windowLostFocus(com.jogamp.newt.event.WindowEvent arg0) {
sketch.focused = false;
sketch.focusLost();
}
@Override
public void windowDestroyNotify(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowDestroyed(com.jogamp.newt.event.WindowEvent arg0) {
sketch.exit();
}
@Override
public void windowMoved(com.jogamp.newt.event.WindowEvent arg0) {
if (external) {