JOGL v2.6.0-rc-20250712
JOGL, High-Performance Graphics Binding for Java™ (public API).
GearsES2.java
Go to the documentation of this file.
1/**
2 * Copyright (C) 2011 JogAmp Community. All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 */
21package com.jogamp.opengl.demos.es2;
22
23import java.nio.FloatBuffer;
24
25import com.jogamp.common.nio.Buffers;
26import com.jogamp.common.util.VersionUtil;
27import com.jogamp.math.Matrix4f;
28import com.jogamp.math.Quaternion;
29import com.jogamp.math.Vec3f;
30import com.jogamp.math.util.PMVMatrix4f;
31import com.jogamp.nativewindow.NativeWindow;
32import com.jogamp.newt.Window;
33import com.jogamp.newt.event.GestureHandler;
34import com.jogamp.newt.event.GestureHandler.GestureEvent;
35import com.jogamp.newt.event.KeyAdapter;
36import com.jogamp.newt.event.KeyEvent;
37import com.jogamp.newt.event.KeyListener;
38import com.jogamp.newt.event.MouseEvent;
39import com.jogamp.newt.event.MouseListener;
40import com.jogamp.newt.event.PinchToZoomGesture;
41import com.jogamp.newt.event.WindowAdapter;
42import com.jogamp.newt.event.WindowEvent;
43import com.jogamp.newt.opengl.GLWindow;
44import com.jogamp.opengl.GL;
45import com.jogamp.opengl.GL2ES2;
46import com.jogamp.opengl.GLAnimatorControl;
47import com.jogamp.opengl.GLAutoDrawable;
48import com.jogamp.opengl.GLCapabilities;
49import com.jogamp.opengl.GLRendererQuirks;
50import com.jogamp.opengl.GLUniformData;
51import com.jogamp.opengl.JoglVersion;
52import com.jogamp.opengl.demos.GearsObject;
53import com.jogamp.opengl.demos.util.CommandlineOptions;
54import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
55import com.jogamp.opengl.util.Animator;
56import com.jogamp.opengl.util.CustomGLEventListener;
57import com.jogamp.opengl.util.PMVMatrix;
58import com.jogamp.opengl.util.TileRendererBase;
59import com.jogamp.opengl.util.caps.NonFSAAGLCapsChooser;
60import com.jogamp.opengl.util.glsl.ShaderCode;
61import com.jogamp.opengl.util.glsl.ShaderProgram;
62import com.jogamp.opengl.util.glsl.ShaderState;
63import com.jogamp.opengl.util.stereo.EyeParameter;
64import com.jogamp.opengl.util.stereo.StereoGLEventListener;
65import com.jogamp.opengl.util.stereo.ViewerPose;
66
67/**
68 * GearsES2.java <BR>
69 * @author Brian Paul (converted to Java by Ron Cemer and Sven Gothel) <P>
70 */
71public class GearsES2 implements StereoGLEventListener, TileRendererBase.TileRendererListener {
72 private final FloatBuffer lightPos = Buffers.newDirectFloatBuffer( new float[] { 5.0f, 5.0f, 10.0f } );
73
74 private ShaderState st = null;
75 private PMVMatrix pmvMatrix = null;
76 private GLUniformData pmvMatrixUniform = null;
77 private GLUniformData colorU = null;
78 private volatile float view_rotx = 20.0f, view_roty = 30.0f;
79 private boolean flipVerticalInGLOrientation = false;
80 private final boolean customRendering = false;
81
82 private final float view_rotz = 0.0f;
83 private float panX = 0.0f, panY = 0.0f, panZ=0.0f;
84 private volatile GearsObjectES2 gear1=null, gear2=null, gear3=null;
85 private GearsES2 sharedGears = null;
86 private Object syncObjects = null;
87 private boolean useMappedBuffers = false;
88 private boolean validateBuffers = false;
89 private volatile boolean usesSharedGears = false;
90 private FloatBuffer gear1Color=GearsObject.red, gear2Color=GearsObject.green, gear3Color=GearsObject.blue;
91 private float angle = 0.0f;
92 private int swapInterval = 0;
93 // private MouseListener gearsMouse = new TraceMouseAdapter(new GearsMouseAdapter());
94 public MouseListener gearsMouse = new GearsMouseAdapter();
95 public KeyListener gearsKeys = new GearsKeyAdapter();
96 private TileRendererBase tileRendererInUse = null;
97 private boolean doRotateBeforePrinting;
98
99 private boolean doRotate = true;
100 private float[] clearColor = null;
101 private boolean clearBuffers = true;
102 private boolean verbose = true;
103 private volatile boolean isInit = false;
104
105 private PinchToZoomGesture pinchToZoomGesture = null;
106
107
108 public GearsES2(final int swapInterval) {
109 this.swapInterval = swapInterval;
110 }
111
112 public GearsES2() {
113 this.swapInterval = 1;
114 }
115
116 @Override
118 tileRendererInUse = tr;
119 doRotateBeforePrinting = doRotate;
120 setDoRotation(false);
121 }
122 @Override
124 tileRendererInUse = null;
125 setDoRotation(doRotateBeforePrinting);
126 }
127 @Override
128 public void startTileRendering(final TileRendererBase tr) {
129 System.err.println("GearsES2.startTileRendering: "+sid()+""+tr);
130 }
131 @Override
132 public void endTileRendering(final TileRendererBase tr) {
133 System.err.println("GearsES2.endTileRendering: "+sid()+""+tr);
134 }
135
136 public void setDoRotation(final boolean rotate) { this.doRotate = rotate; }
137 public void setClearBuffers(final boolean v) { clearBuffers = v; }
138 public void setVerbose(final boolean v) { verbose = v; }
139 public void setFlipVerticalInGLOrientation(final boolean v) { flipVerticalInGLOrientation=v; }
140
141 /** float[4] */
142 public void setClearColor(final float[] clearColor) {
143 this.clearColor = clearColor;
144 }
145
146 public void setGearsColors(final FloatBuffer gear1Color, final FloatBuffer gear2Color, final FloatBuffer gear3Color) {
147 this.gear1Color = gear1Color;
148 this.gear2Color = gear2Color;
149 this.gear3Color = gear3Color;
150 }
151
152 public void setSharedGears(final GearsES2 shared) {
153 sharedGears = shared;
154 }
155
156 public void setSyncObjects(final Object sync) {
157 syncObjects = sync;
158 }
159
160 public float getRotX() { return view_rotx; }
161 public float getRotY() { return view_roty; }
162 public void setRotX(final float v) { view_rotx = v; }
163 public void setRotY(final float v) { view_roty = v; }
164
165 /**
166 * @return gear1
167 */
168 public GearsObjectES2 getGear1() { return gear1; }
169
170 /**
171 * @return gear2
172 */
173 public GearsObjectES2 getGear2() { return gear2; }
174
175 /**
176 * @return gear3
177 */
178 public GearsObjectES2 getGear3() { return gear3; }
179
180 public boolean usesSharedGears() { return usesSharedGears; }
181
182 public void setUseMappedBuffers(final boolean v) { useMappedBuffers = v; }
183 public void setValidateBuffers(final boolean v) { validateBuffers = v; }
184
186 return pmvMatrix;
187 }
188
189 private static final int TIME_OUT = 2000; // 2s
190 private static final int POLL_DIVIDER = 20; // TO/20
191 private static final int TIME_SLICE = TIME_OUT / POLL_DIVIDER ;
192
193 /**
194 * @return True if this GLEventListener became initialized within TIME_OUT 2s
195 */
196 public boolean waitForInit(final boolean initialized) throws InterruptedException {
197 int wait;
198 for (wait=0; wait<POLL_DIVIDER && initialized != isInit ; wait++) {
199 Thread.sleep(TIME_SLICE);
200 }
201 return wait<POLL_DIVIDER;
202 }
203
204 private final String sid() { return "0x"+Integer.toHexString(hashCode()); }
205
206 @Override
207 public void init(final GLAutoDrawable drawable) {
208 if(null != sharedGears && !sharedGears.isInit() ) {
209 System.err.println(Thread.currentThread()+" GearsES2.init.0 "+sid()+": pending shared Gears .. re-init later XXXXX");
210 drawable.setGLEventListenerInitState(this, false);
211 return;
212 }
213
214 final GL2ES2 gl = drawable.getGL().getGL2ES2();
215 if(verbose) {
216 System.err.println(Thread.currentThread()+" GearsES2.init.0 "+sid()+": tileRendererInUse "+tileRendererInUse+", "+this);
217 System.err.println("GearsES2 init "+sid()+" on "+Thread.currentThread());
218 System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities());
219 System.err.println("INIT GL IS: " + gl.getClass().getName());
220 System.err.println(JoglVersion.getGLStrings(gl, null, false).toString());
221 }
222 if( !gl.hasGLSL() ) {
223 System.err.println("No GLSL available, no rendering.");
224 return;
225 }
226
227 st = new ShaderState();
228 // st.setVerbose(true);
229 final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
230 "shader/bin", "gears", true);
231 final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
232 "shader/bin", "gears", true);
233 vp0.defaultShaderCustomization(gl, true, true);
234 fp0.defaultShaderCustomization(gl, true, true);
235 final ShaderProgram sp0 = new ShaderProgram();
236 sp0.add(gl, vp0, System.err);
237 sp0.add(gl, fp0, System.err);
238 st.attachShaderProgram(gl, sp0, true);
239 // Use debug pipeline
240 // drawable.setGL(new DebugGL(drawable.getGL()));
241
243 st.attachObject("pmvMatrix", pmvMatrix);
244 pmvMatrixUniform = new GLUniformData("pmvMatrix", 4, 4, pmvMatrix.getSyncPMvMviMvit()); // P, Mv, Mvi and Mvit
245 st.ownUniform(pmvMatrixUniform);
246 st.uniform(gl, pmvMatrixUniform);
247
248 final GLUniformData lightU = new GLUniformData("lightPos", 3, lightPos);
249 st.ownUniform(lightU);
250 st.uniform(gl, lightU);
251
252 colorU = new GLUniformData("color", 4, GearsObject.red);
253 st.ownUniform(colorU);
254 st.uniform(gl, colorU);
255
256 if( null != sharedGears ) {
257 gear1 = new GearsObjectES2(sharedGears.getGear1(), st, pmvMatrix, pmvMatrixUniform, colorU);
258 gear2 = new GearsObjectES2(sharedGears.getGear2(), st, pmvMatrix, pmvMatrixUniform, colorU);
259 gear3 = new GearsObjectES2(sharedGears.getGear3(), st, pmvMatrix, pmvMatrixUniform, colorU);
260 usesSharedGears = true;
261 if(verbose) {
262 System.err.println("gear1 "+sid()+" created w/ share: "+sharedGears.getGear1()+" -> "+gear1);
263 System.err.println("gear2 "+sid()+" created w/ share: "+sharedGears.getGear2()+" -> "+gear2);
264 System.err.println("gear3 "+sid()+" created w/ share: "+sharedGears.getGear3()+" -> "+gear3);
265 }
267 syncObjects = sharedGears;
268 System.err.println("Shared GearsES2: Synchronized Objects due to quirk "+GLRendererQuirks.toString(GLRendererQuirks.NeedSharedObjectSync));
269 } else if( null == syncObjects ) {
270 syncObjects = new Object();
271 System.err.println("Shared GearsES2: Unsynchronized Objects");
272 }
273 } else {
274 gear1 = new GearsObjectES2(gl, useMappedBuffers, st, gear1Color, 1.0f, 4.0f, 1.0f, 20, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
275 if(verbose) {
276 System.err.println("gear1 "+sid()+" created: "+gear1);
277 }
278
279 gear2 = new GearsObjectES2(gl, useMappedBuffers, st, gear2Color, 0.5f, 2.0f, 2.0f, 10, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
280 if(verbose) {
281 System.err.println("gear2 "+sid()+" created: "+gear2);
282 }
283
284 gear3 = new GearsObjectES2(gl, useMappedBuffers, st, gear3Color, 1.3f, 2.0f, 0.5f, 10, 0.7f, pmvMatrix, pmvMatrixUniform, colorU, validateBuffers);
285 if(verbose) {
286 System.err.println("gear3 "+sid()+" created: "+gear2);
287 }
288 if( null == syncObjects ) {
289 syncObjects = new Object();
290 }
291 }
292
293 final Object upstreamWidget = drawable.getUpstreamWidget();
294 if (upstreamWidget instanceof Window) {
295 final Window window = (Window) upstreamWidget;
298 window.addGestureListener(pinchToZoomListener);
299 pinchToZoomGesture = new PinchToZoomGesture(drawable.getNativeSurface(), false);
300 window.addGestureHandler(pinchToZoomGesture);
301 }
302
303 st.useProgram(gl, false);
304
305 gl.glFinish(); // make sure .. for shared context (impacts OSX 10.9)
306
307 isInit = true;
308 if(verbose) {
309 System.err.println(Thread.currentThread()+" GearsES2.init.X "+sid()+" FIN "+this);
310 }
311 }
312
313 public final boolean isInit() { return isInit; }
314
315 private final GestureHandler.GestureListener pinchToZoomListener = new GestureHandler.GestureListener() {
316 @Override
317 public void gestureDetected(final GestureEvent gh) {
318 final PinchToZoomGesture.ZoomEvent ze = (PinchToZoomGesture.ZoomEvent) gh;
319 final float zoom = ze.getZoom(); // * ( ze.getTrigger().getPointerCount() - 1 ); <- too much ..
320 panZ = zoom * 30f - 30f; // [0 .. 2] -> [-30f .. 30f]
321 }
322 };
323
324 @Override
325 public void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height) {
326 if( !isInit ) { return; }
327 final GL2ES2 gl = glad.getGL().getGL2ES2();
328 gl.setSwapInterval(swapInterval);
329 reshapeImpl(gl, x, y, width, height, width, height);
330 }
331
332 @Override
333 public void reshapeTile(final TileRendererBase tr,
334 final int tileX, final int tileY, final int tileWidth, final int tileHeight,
335 final int imageWidth, final int imageHeight) {
336 if( !isInit ) { return; }
337 final GL2ES2 gl = tr.getAttachedDrawable().getGL().getGL2ES2();
338 gl.setSwapInterval(0);
339 reshapeImpl(gl, tileX, tileY, tileWidth, tileHeight, imageWidth, imageHeight);
340 }
341
342 private float zNear = 5f;
343 private float zFar = 10000f;
344 private float zViewDist = 40.0f;
345
346 public void setZ(final float zNear, final float zFar, final float zViewDist) {
347 this.zNear = zNear;
348 this.zFar = zFar;
349 this.zViewDist = zViewDist;
350 }
351
352 void reshapeImpl(final GL2ES2 gl, final int tileX, final int tileY, final int tileWidth, final int tileHeight, final int imageWidth, final int imageHeight) {
354 if(verbose) {
355 System.err.println(Thread.currentThread()+" GearsES2.reshape "+sid()+" "+tileX+"/"+tileY+" "+tileWidth+"x"+tileHeight+" of "+imageWidth+"x"+imageHeight+", swapInterval "+swapInterval+", drawable 0x"+Long.toHexString(gl.getContext().getGLDrawable().getHandle())+", msaa "+msaa+", tileRendererInUse "+tileRendererInUse);
356 }
357
358 if( !gl.hasGLSL() ) {
359 return;
360 }
361
362 // compute projection parameters 'normal'
363 float left, right, bottom, top;
364 if( imageHeight > imageWidth ) {
365 final float a = (float)imageHeight / (float)imageWidth;
366 left = -1.0f;
367 right = 1.0f;
368 bottom = -a;
369 top = a;
370 } else {
371 final float a = (float)imageWidth / (float)imageHeight;
372 left = -a;
373 right = a;
374 bottom = -1.0f;
375 top = 1.0f;
376 }
377 final float w = right - left;
378 final float h = top - bottom;
379
380 // compute projection parameters 'tiled'
381 final float l = left + tileX * w / imageWidth;
382 final float r = l + tileWidth * w / imageWidth;
383 final float b = bottom + tileY * h / imageHeight;
384 final float t = b + tileHeight * h / imageHeight;
385
386 final float _w = r - l;
387 final float _h = t - b;
388 if(verbose) {
389 System.err.println(">> GearsES2 "+sid()+", angle "+angle+", [l "+left+", r "+right+", b "+bottom+", t "+top+"] "+w+"x"+h+" -> [l "+l+", r "+r+", b "+b+", t "+t+"] "+_w+"x"+_h+", v-flip "+flipVerticalInGLOrientation);
390 }
391
392 pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
393 pmvMatrix.glLoadIdentity();
394 if( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() ) {
395 pmvMatrix.glScalef(1f, -1f, 1f);
396 }
397 pmvMatrix.glFrustumf(l, r, b, t, zNear, zFar);
398
399 pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
400 pmvMatrix.glLoadIdentity();
401 pmvMatrix.glTranslatef(0.0f, 0.0f, -zViewDist);
402 st.useProgram(gl, true);
403 st.uniform(gl, pmvMatrixUniform);
404 st.useProgram(gl, false);
405 }
406 // private boolean useAndroidDebug = false;
407
408 private final Matrix4f mat4Tmp1 = new Matrix4f();
409 private final Matrix4f mat4Tmp2 = new Matrix4f();
410 private final Vec3f vec3Tmp1 = new Vec3f();
411 private final Vec3f vec3Tmp2 = new Vec3f();
412 private final Vec3f vec3Tmp3 = new Vec3f();
413
414 private static final float scalePos = 20f;
415
416 @Override
417 public void reshapeForEye(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height,
418 final EyeParameter eyeParam, final ViewerPose viewerPose) {
419 final GL2ES2 gl = drawable.getGL().getGL2ES2();
420
421 {
422 //
423 // Projection
424 //
425 final Matrix4f mat4 = new Matrix4f();
427 if( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() ) {
428 mat4Tmp1.setToScale(1f, -1f, 1f);
429 mat4Tmp2.setToPerspective(eyeParam.fovhv, zNear, zFar);
430 mat4.mul(mat4Tmp1, mat4Tmp2);
431 } else {
432 mat4.setToPerspective(eyeParam.fovhv, zNear, zFar);
433 }
434 pmvMatrix.glLoadMatrixf(mat4);
435
436 //
437 // Modelview
438 //
440 final Quaternion rollPitchYaw = new Quaternion();
441 // private final float eyeYaw = FloatUtil.PI; // 180 degrees in radians
442 // rollPitchYaw.rotateByAngleY(eyeYaw);
443 // final Vec3f shiftedEyePos = rollPitchYaw.rotateVector(viewerPose.position, vec3Tmp1);
444 final Vec3f shiftedEyePos = vec3Tmp1.set(viewerPose.position);
445 shiftedEyePos.scale(scalePos); // amplify viewerPose position
446 shiftedEyePos.add(eyeParam.positionOffset);
447
448 rollPitchYaw.mult(viewerPose.orientation);
449 final Vec3f up = rollPitchYaw.rotateVector(Vec3f.UNIT_Y, vec3Tmp2);
450 final Vec3f forward = rollPitchYaw.rotateVector(Vec3f.UNIT_Z_NEG, vec3Tmp3); // -> center
451 final Vec3f center = forward.add(shiftedEyePos);
452
453 final Matrix4f mLookAt = mat4Tmp2.setToLookAt(shiftedEyePos, center, up, mat4Tmp1);
454 mat4.mul( mat4Tmp1.setToTranslation( eyeParam.distNoseToPupilX,
455 eyeParam.distMiddleToPupilY,
456 eyeParam.eyeReliefZ ), mLookAt);
457 mat4.translate(0, 0, -zViewDist, mat4Tmp1);
458 pmvMatrix.glLoadMatrixf(mat4);
459 }
460 st.useProgram(gl, true);
461 st.uniform(gl, pmvMatrixUniform);
462 st.useProgram(gl, false);
463 }
464
465 @Override
466 public void dispose(final GLAutoDrawable drawable) {
467 if( !isInit ) { return; }
468 isInit = false;
469 if(verbose) {
470 System.err.println(Thread.currentThread()+" GearsES2.dispose "+sid()+": tileRendererInUse "+tileRendererInUse);
471 }
472 final Object upstreamWidget = drawable.getUpstreamWidget();
473 if (upstreamWidget instanceof Window) {
474 final Window window = (Window) upstreamWidget;
477 window.removeGestureHandler(pinchToZoomGesture);
478 pinchToZoomGesture = null;
479 window.removeGestureListener(pinchToZoomListener);
480 }
481 final GL2ES2 gl = drawable.getGL().getGL2ES2();
482 if( !gl.hasGLSL() ) {
483 return;
484 }
485 st.useProgram(gl, false);
486 gear1.destroy(gl);
487 gear1 = null;
488 gear2.destroy(gl);
489 gear2 = null;
490 gear3.destroy(gl);
491 gear3 = null;
492 pmvMatrix = null;
493 colorU = null;
494 st.destroy(gl);
495 st = null;
496 sharedGears = null;
497 syncObjects = null;
498
499 if(verbose) {
500 System.err.println(Thread.currentThread()+" GearsES2.dispose "+sid()+" FIN");
501 }
502 }
503
504 @Override
505 public void display(final GLAutoDrawable drawable) {
506 display(drawable, 0);
507 }
508
509 @Override
510 public void display(final GLAutoDrawable drawable, final int flags) {
511 if( !isInit ) { return; }
512 if(null != sharedGears && !sharedGears.isInit() ) { return; }
513 final GLAnimatorControl anim = drawable.getAnimator();
514
515 final boolean repeatedFrame = 0 != ( CustomGLEventListener.DISPLAY_REPEAT & flags );
516 final boolean dontClear = 0 != ( CustomGLEventListener.DISPLAY_DONTCLEAR & flags );
517
518 // Turn the gears' teeth
519 if( doRotate && !repeatedFrame ) {
520 angle += 0.5f;
521 }
522
523 // Get the GL corresponding to the drawable we are animating
524 final GL2ES2 gl = drawable.getGL().getGL2ES2();
525
526 final boolean hasFocus;
527 final Object upstreamWidget = drawable.getUpstreamWidget();
528 if(upstreamWidget instanceof NativeWindow) {
529 hasFocus = ((NativeWindow)upstreamWidget).hasFocus();
530 } else {
531 hasFocus = true;
532 }
533
534 if( clearBuffers && !dontClear ) {
535 if( null != clearColor ) {
536 gl.glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
537 } else if( null != tileRendererInUse ) {
538 gl.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
539 } else {
540 gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
541 }
543 }
544 if( !gl.hasGLSL() ) {
545 return;
546 }
547
548 setGLStates(gl, true);
549
550 st.useProgram(gl, true);
551 pmvMatrix.glPushMatrix();
552 pmvMatrix.glTranslatef(panX, panY, panZ);
553 pmvMatrix.glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
554 pmvMatrix.glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
555 pmvMatrix.glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
556
557 synchronized ( syncObjects ) {
558 gear1.draw(gl, -3.0f, -2.0f, 1f * angle - 0f);
559 gear2.draw(gl, 3.1f, -2.0f, -2f * angle - 9.0f);
560 gear3.draw(gl, -3.1f, 4.2f, -2f * angle - 25.0f);
561 }
562 pmvMatrix.glPopMatrix();
563 st.useProgram(gl, false);
564
565 setGLStates(gl, false);
566 }
567
568 public void setGLStates(final GL2ES2 gl, final boolean enable) {
569 // Culling only possible if we do not flip the projection matrix
570 final boolean useCullFace = ! ( flipVerticalInGLOrientation && gl.getContext().getGLDrawable().isGLOriented() || customRendering );
571 if( enable ) {
573 if( useCullFace ) {
575 }
576 } else {
578 if( useCullFace ) {
580 }
581 }
582 }
583
584 @Override
585 public String toString() {
586 return "GearsES2[obj "+sid()+" isInit "+isInit+", usesShared "+usesSharedGears+", 1 "+gear1+", 2 "+gear2+", 3 "+gear3+", sharedGears "+sharedGears+"]";
587 }
588
589 public KeyListener getKeyListener() { return this.gearsKeys; }
590 public MouseListener getMouseListener() { return this.gearsMouse; }
591
592 class GearsKeyAdapter extends KeyAdapter {
593 @Override
594 public void keyPressed(final KeyEvent e) {
595 final int kc = e.getKeyCode();
596 if(KeyEvent.VK_LEFT == kc) {
597 view_roty -= 1;
598 } else if(KeyEvent.VK_RIGHT == kc) {
599 view_roty += 1;
600 } else if(KeyEvent.VK_UP == kc) {
601 view_rotx -= 1;
602 } else if(KeyEvent.VK_DOWN == kc) {
603 view_rotx += 1;
604 }
605 }
606 }
607
608 class GearsMouseAdapter implements MouseListener{
609 private int prevMouseX, prevMouseY;
610
611 @Override
612 public void mouseClicked(final MouseEvent e) {
613 }
614
615 @Override
616 public void mouseEntered(final MouseEvent e) {
617 }
618
619 @Override
620 public void mouseExited(final MouseEvent e) {
621 }
622
623 @Override
624 public void mouseWheelMoved(final MouseEvent e) {
625 final float[] rot = e.getRotation();
626 if( e.isControlDown() ) {
627 // alternative zoom
628 final float incr = e.isShiftDown() ? rot[0] : rot[1] * 0.5f ;
629 panZ += incr;
630 System.err.println("panZ.2: incr "+incr+", dblZoom "+e.isShiftDown()+" -> "+panZ);
631 } else {
632 // panning
633 panX -= rot[0]; // positive -> left
634 panY += rot[1]; // positive -> up
635 }
636 }
637
638 @Override
639 public void mousePressed(final MouseEvent e) {
640 if( e.getPointerCount()==1 ) {
641 prevMouseX = e.getX();
642 prevMouseY = e.getY();
643 } else if( e.getPointerCount() == 4 ) {
644 final Object src = e.getSource();
645 if( e.getPressure(0, true) > 0.7f && src instanceof Window) { // show Keyboard
646 ((Window) src).setKeyboardVisible(true);
647 }
648 }
649 }
650
651 @Override
652 public void mouseReleased(final MouseEvent e) {
653 }
654
655 @Override
656 public void mouseMoved(final MouseEvent e) {
657 if( e.isConfined() ) {
658 navigate(e);
659 } else {
660 // track prev. position so we don't have 'jumps'
661 // in case we move to confined navigation.
662 prevMouseX = e.getX();
663 prevMouseY = e.getY();
664 }
665 }
666
667 @Override
668 public void mouseDragged(final MouseEvent e) {
669 navigate(e);
670 }
671
672 private void navigate(final MouseEvent e) {
673 final int x = e.getX();
674 final int y = e.getY();
675
676 int width, height;
677 final Object source = e.getSource();
678 Window window = null;
679 if(source instanceof Window) {
680 window = (Window) source;
681 width=window.getSurfaceWidth();
682 height=window.getSurfaceHeight();
683 } else if (source instanceof GLAutoDrawable) {
684 final GLAutoDrawable glad = (GLAutoDrawable) source;
685 width = glad.getSurfaceWidth();
686 height = glad.getSurfaceHeight();
687 } else {
688 throw new RuntimeException("Event source neither Window nor Component: "+source);
689 }
690 final float thetaY = 360.0f * ( (float)(x-prevMouseX)/(float)width);
691 final float thetaX = 360.0f * ( (float)(prevMouseY-y)/(float)height);
692 view_rotx += thetaX;
693 view_roty += thetaY;
694 prevMouseX = x;
695 prevMouseY = y;
696 // System.err.println("rotXY.1: "+view_rotx+"/"+view_roty+", source "+e);
697 }
698 }
699
700 public static void main(final String[] args) {
701 final CommandlineOptions options = new CommandlineOptions(1280, 720, 0);
702
703 System.err.println(options);
704 System.err.println(VersionUtil.getPlatformInfo());
705 // System.err.println(JoglVersion.getAllAvailableCapabilitiesInfo(dpy.getGraphicsDevice(), null).toString());
706
707 final GLCapabilities reqCaps = options.getGLCaps();
708 System.out.println("Requested: " + reqCaps);
709
710 final GLWindow window = GLWindow.create(reqCaps);
711 if( 0 == options.sceneMSAASamples ) {
713 }
714 window.setSize(options.surface_width, options.surface_height);
715 window.setTitle(GearsES2.class.getSimpleName());
716
717 window.addGLEventListener(new GearsES2(1));
718
719 final Animator animator = new Animator(0 /* w/o AWT */);
720 animator.setUpdateFPSFrames(5*60, null);
721 animator.add(window);
722
723 window.addWindowListener(new WindowAdapter() {
724 @Override
725 public void windowDestroyed(final WindowEvent e) {
726 animator.stop();
727 }
728 });
729
730 window.setVisible(true);
731 animator.start();
732 }
733
734}
Basic 4x4 float matrix implementation using fields for intensive use-cases (host operations).
Definition: Matrix4f.java:89
final Matrix4f mul(final Matrix4f b)
Multiply matrix: [this] = [this] x [b].
Definition: Matrix4f.java:726
final Matrix4f translate(final float x, final float y, final float z, final Matrix4f tmp)
Translate this matrix, i.e.
Definition: Matrix4f.java:1558
Matrix4f setToPerspective(final float fovy_rad, final float aspect, final float zNear, final float zFar)
Set this matrix to perspective frustum projection.
Definition: Matrix4f.java:1303
Matrix4f setToLookAt(final Vec3f eye, final Vec3f center, final Vec3f up, final Matrix4f tmp)
Set this matrix to the look-at matrix based on given parameters.
Definition: Matrix4f.java:1432
Quaternion implementation supporting Gimbal-Lock free rotations.
Definition: Quaternion.java:45
final Vec3f rotateVector(final Vec3f vecIn, final Vec3f vecOut)
final Quaternion mult(final Quaternion q)
Multiply this quaternion by the param quaternion.
3D Vector based upon three float components.
Definition: Vec3f.java:37
Vec3f scale(final float s)
this = this * s, returns this.
Definition: Vec3f.java:218
static final Vec3f UNIT_Z_NEG
Definition: Vec3f.java:44
static final Vec3f UNIT_Y
Definition: Vec3f.java:41
Vec3f set(final Vec3f o)
this = o, returns this.
Definition: Vec3f.java:79
Vec3f add(final float dx, final float dy, final float dz)
this = this + { dx, dy, dz }, returns this.
Definition: Vec3f.java:239
PMVMatrix4f implements the basic computer graphics Matrix4f pack using projection (P),...
static final int INVERSE_TRANSPOSED_MODELVIEW
Bit value for inverse transposed modelview matrix (Mvit), updated via update().
static final int INVERSE_MODELVIEW
Bit value for inverse modelview matrix (Mvi), updated via update().
final SyncMatrices4f getSyncPMvMviMvit()
Returns SyncMatrices4f of 4 matrices within one FloatBuffer: P, Mv, Mvi and Mvit if requested.
static final short VK_LEFT
Constant for the cursor- or numerical-pad left arrow key.
Definition: KeyEvent.java:811
final short getKeyCode()
Returns the virtual key code using a fixed mapping to the US keyboard layout.
Definition: KeyEvent.java:195
A GestureHandler.GestureEvent denominating zoom.
NEWT Window events are provided for notification purposes ONLY.
An implementation of GLAutoDrawable and Window interface, using a delegated Window instance,...
Definition: GLWindow.java:121
final void setTitle(final String title)
Definition: GLWindow.java:297
final void setSize(final int width, final int height)
Sets the size of the window's client area in window units, excluding decorations.
Definition: GLWindow.java:625
final void setVisible(final boolean visible)
Calls setVisible(true, visible), i.e.
Definition: GLWindow.java:615
final void addWindowListener(final WindowListener l)
Appends the given com.jogamp.newt.event.WindowListener to the end of the list.
Definition: GLWindow.java:882
CapabilitiesChooser setCapabilitiesChooser(final CapabilitiesChooser chooser)
Set the CapabilitiesChooser to help determine the native visual type.
Definition: GLWindow.java:261
static GLWindow create(final GLCapabilitiesImmutable caps)
Creates a new GLWindow attaching a new Window referencing a new default Screen and default Display wi...
Definition: GLWindow.java:169
Specifies a set of OpenGL capabilities.
abstract GLDrawable getGLDrawable()
Returns the write-drawable this context uses for framebuffer operations.
final boolean hasRendererQuirk(final int quirk)
Returns true if the quirk exist in getRendererQuirks(), otherwise false.
Definition: GLContext.java:304
GLRendererQuirks contains information of known bugs of various GL renderer.
static final int NeedSharedObjectSync
Need GL objects (VBO, ..) to be synchronized when utilized concurrently from multiple threads via a s...
final StringBuilder toString(StringBuilder sb)
GLSL uniform data wrapper encapsulating data to be uploaded to the GPU as a uniform.
static StringBuilder getGLStrings(final GL gl, final StringBuilder sb)
static final FloatBuffer green
static final FloatBuffer red
static final FloatBuffer blue
void setGearsColors(final FloatBuffer gear1Color, final FloatBuffer gear2Color, final FloatBuffer gear3Color)
Definition: GearsES2.java:146
void setVerbose(final boolean v)
Definition: GearsES2.java:138
void display(final GLAutoDrawable drawable, final int flags)
Extended display method, allowing to pass a display flag, e.g.
Definition: GearsES2.java:510
void reshapeTile(final TileRendererBase tr, final int tileX, final int tileY, final int tileWidth, final int tileHeight, final int imageWidth, final int imageHeight)
Called by the TileRendererBase during tile-rendering via an attached GLAutoDrawable's GLAutoDrawable#...
Definition: GearsES2.java:333
void setDoRotation(final boolean rotate)
Definition: GearsES2.java:136
void setClearColor(final float[] clearColor)
float[4]
Definition: GearsES2.java:142
void setUseMappedBuffers(final boolean v)
Definition: GearsES2.java:182
GearsES2(final int swapInterval)
Definition: GearsES2.java:108
void setValidateBuffers(final boolean v)
Definition: GearsES2.java:183
void display(final GLAutoDrawable drawable)
Called by the drawable to initiate OpenGL rendering by the client.
Definition: GearsES2.java:505
void init(final GLAutoDrawable drawable)
Called by the drawable immediately after the OpenGL context is initialized.
Definition: GearsES2.java:207
void dispose(final GLAutoDrawable drawable)
Notifies the listener to perform the release of all OpenGL resources per GLContext,...
Definition: GearsES2.java:466
void setClearBuffers(final boolean v)
Definition: GearsES2.java:137
static void main(final String[] args)
Definition: GearsES2.java:700
void setSharedGears(final GearsES2 shared)
Definition: GearsES2.java:152
boolean waitForInit(final boolean initialized)
Definition: GearsES2.java:196
void startTileRendering(final TileRendererBase tr)
Called by the TileRendererBase during tile-rendering after TileRendererBase#beginTile(GL) and before ...
Definition: GearsES2.java:128
void setGLStates(final GL2ES2 gl, final boolean enable)
Definition: GearsES2.java:568
void reshapeForEye(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height, final EyeParameter eyeParam, final ViewerPose viewerPose)
Stereo capable specialization of reshape(GLAutoDrawable, int, int, int, int) for one StereoDeviceRend...
Definition: GearsES2.java:417
void setZ(final float zNear, final float zFar, final float zViewDist)
Definition: GearsES2.java:346
void endTileRendering(final TileRendererBase tr)
Called by the TileRenderer during tile-rendering after TileRendererBase#endTile(GL) and GLAutoDrawabl...
Definition: GearsES2.java:132
void setFlipVerticalInGLOrientation(final boolean v)
Definition: GearsES2.java:139
void addTileRendererNotify(final TileRendererBase tr)
The owning GLAutoDrawable is attached to the given TileRendererBase instance.
Definition: GearsES2.java:117
void setSyncObjects(final Object sync)
Definition: GearsES2.java:156
void removeTileRendererNotify(final TileRendererBase tr)
The owning GLAutoDrawable is detached from the given TileRendererBase instance.
Definition: GearsES2.java:123
void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height)
Called by the drawable during the first repaint after the component has been resized.
Definition: GearsES2.java:325
final synchronized void add(final GLAutoDrawable drawable)
Adds a drawable to this animator's list of rendering drawables.
final void setUpdateFPSFrames(final int frames, final PrintStream out)
final synchronized boolean start()
Starts this animator, if not running.
Definition: Animator.java:344
final synchronized boolean stop()
Stops this animator.
Definition: Animator.java:368
PMVMatrix implements a subset of the fixed function pipeline GLMatrixFunc using PMVMatrix4f.
Definition: PMVMatrix.java:62
final void glTranslatef(final float x, final float y, final float z)
Translate the current matrix.
Definition: PMVMatrix.java:379
final void glScalef(final float x, final float y, final float z)
Scale the current matrix.
Definition: PMVMatrix.java:396
final void glMatrixMode(final int matrixName)
Sets the current matrix mode.
Definition: PMVMatrix.java:218
final void glPushMatrix()
Push the current matrix to it's stack, while preserving it's values.
Definition: PMVMatrix.java:458
final void glFrustumf(final float left, final float right, final float bottom, final float top, final float zNear, final float zFar)
Multiply the current matrix with the frustum matrix.
Definition: PMVMatrix.java:481
final void glRotatef(final float ang_deg, final float x, final float y, final float z)
Rotate the current matrix.
Definition: PMVMatrix.java:413
final void glPopMatrix()
Pop the current matrix from it's stack.
Definition: PMVMatrix.java:447
final void glLoadIdentity()
Load the current matrix with the identity matrix.
Definition: PMVMatrix.java:325
final void glLoadMatrixf(final float[] values, final int offset)
Load the current matrix w/ the provided one.
Definition: PMVMatrix.java:271
A fairly direct port of Brian Paul's tile rendering library, found at http://www.mesa3d....
final GLAutoDrawable getAttachedDrawable()
Returns a previously attached GLAutoDrawable, null if none is attached.
Custom GLCapabilitiesChooser, filtering out all full screen anti-aliasing (FSAA, multisample) capabil...
Convenient shader code class to use and instantiate vertex or fragment programs.
Definition: ShaderCode.java:75
final int defaultShaderCustomization(final GL2ES2 gl, final boolean preludeVersion, final boolean addDefaultPrecision)
Default customization of this shader source code.
static ShaderCode create(final GL2ES2 gl, final int type, final int count, final Class<?> context, final String[] sourceFiles, final boolean mutableStringBuilder)
Creates a complete ShaderCode object while reading all shader source of sourceFiles,...
synchronized void add(final ShaderCode shaderCode)
Adds a new shader to this program.
ShaderState allows to sharing data between shader programs, while updating the attribute and uniform ...
synchronized void useProgram(final GL2ES2 gl, final boolean on)
Turns the shader program on or off.
synchronized boolean attachShaderProgram(final GL2ES2 gl, final ShaderProgram prog, final boolean enable)
Attach or switch a shader program.
final Object attachObject(final String name, final Object obj)
Attach user object for the given name to this ShaderState.
synchronized void destroy(final GL2ES2 gl)
Calls release(gl, true, true, true).
boolean uniform(final GL2ES2 gl, final GLUniformData data)
Set the uniform data, if it's location is valid, i.e.
void ownUniform(final GLUniformData uniform)
Bind the GLUniform lifecycle to this ShaderState.
Constant single eye parameter of the viewer, relative to its ViewerPose.
final float distNoseToPupilX
IPD related horizontal distance from nose to pupil in meter.
final FovHVHalves fovhv
Field of view in both directions, may not be centered, either FovHVHalves#inTangents or radians.
final float distMiddleToPupilY
Vertical distance from middle-line to pupil in meter.
final Vec3f positionOffset
eye position vector used to define eye height in meter relative to actor.
final float eyeReliefZ
Z-axis eye relief in meter.
position and orientation of viewer.
Definition: ViewerPose.java:36
final Quaternion orientation
Orientation of viewer.
Definition: ViewerPose.java:50
final Vec3f position
position of viewer in meter.
Definition: ViewerPose.java:47
Extend the NativeSurface interface with windowing information such as window-handle,...
Specifying NEWT's Window functionality:
Definition: Window.java:115
void addGestureListener(GestureHandler.GestureListener gl)
Appends the given GestureHandler.GestureListener to the end of the list.
void addKeyListener(KeyListener l)
Appends the given com.jogamp.newt.event.KeyListener to the end of the list.
void removeGestureHandler(GestureHandler gh)
Removes the given GestureHandler from the list.
void removeKeyListener(KeyListener l)
void addMouseListener(MouseListener l)
Appends the given MouseListener to the end of the list.
void removeGestureListener(GestureHandler.GestureListener gl)
Removes the given GestureHandler.GestureListener from the list.
void addGestureHandler(GestureHandler gh)
Appends the given GestureHandler to the end of the list.
void removeMouseListener(MouseListener l)
Removes the given MouseListener from the list.
Generic gesture handler interface designed to allow pass-through filtering of InputEvents.
Listener for KeyEvents.
static final int GL_VERTEX_SHADER
GL_ES_VERSION_2_0, GL_VERSION_2_0, GL_EXT_vertex_shader, GL_ARB_vertex_shader Alias for: GL_VERTEX_SH...
Definition: GL2ES2.java:39
static final int GL_FRAGMENT_SHADER
GL_ES_VERSION_2_0, GL_VERSION_2_0, GL_ATI_fragment_shader, GL_ARB_fragment_shader Alias for: GL_FRAGM...
Definition: GL2ES2.java:541
An animator control interface, which implementation may drive a com.jogamp.opengl....
A higher-level abstraction than GLDrawable which supplies an event based mechanism (GLEventListener) ...
GLAnimatorControl getAnimator()
GL getGL()
Returns the GL pipeline object this GLAutoDrawable uses.
void setGLEventListenerInitState(GLEventListener listener, boolean initialized)
Sets the given listener's initialized state.
Object getUpstreamWidget()
Method may return the upstream UI toolkit object holding this GLAutoDrawable instance,...
void addGLEventListener(GLEventListener listener)
Adds the given listener to the end of this drawable queue.
boolean hasGLSL()
Indicates whether this GL object supports GLSL.
GL2ES2 getGL2ES2()
Casts this object to the GL2ES2 interface.
void setSwapInterval(int interval)
Set the swap interval of the current context and attached onscreen GLDrawable.
GLContext getContext()
Returns the GLContext associated which this GL object.
boolean getSampleBuffers()
Returns whether sample buffers for full-scene antialiasing (FSAA) should be allocated for this drawab...
GLCapabilitiesImmutable getChosenGLCapabilities()
Fetches the GLCapabilitiesImmutable corresponding to the chosen OpenGL capabilities (pixel format / v...
long getHandle()
Returns the GL drawable handle, guaranteed to be valid after realization and while it's surface is be...
boolean isGLOriented()
Returns true if the drawable is rendered in OpenGL's coordinate system, origin at bottom left.
NativeSurface getNativeSurface()
Returns the associated NativeSurface of this NativeSurfaceHolder.
void glDisable(int cap)
Entry point to C language function: void {@native glDisable}(GLenum cap) Part of GL_ES_VERSION_2_0...
static final int GL_COLOR_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_COLOR_BUFFER_BIT" wit...
Definition: GL.java:390
void glClearColor(float red, float green, float blue, float alpha)
Entry point to C language function: void {@native glClearColor}(GLfloat red, GLfloat green,...
void glEnable(int cap)
Entry point to C language function: void {@native glEnable}(GLenum cap) Part of GL_ES_VERSION_2_0,...
static final int GL_DEPTH_TEST
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_TEST" with expr...
Definition: GL.java:43
void glClear(int mask)
Entry point to C language function: void {@native glClear}(GLbitfield mask) Part of GL_ES_VERSION_...
void glFinish()
Entry point to C language function: void {@native glFinish}() Part of GL_ES_VERSION_2_0,...
static final int GL_DEPTH_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_BUFFER_BIT" wit...
Definition: GL.java:738
static final int GL_CULL_FACE
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_CULL_FACE" with expre...
Definition: GL.java:720
Subset of OpenGL fixed function pipeline's matrix operations.
static final int GL_PROJECTION
Matrix mode projection.
static final int GL_MODELVIEW
Matrix mode modelview.
Extended GLEventListener and CustomGLEventListener interface supporting stereoscopic client rendering...