Jogamp
Fix setenv-jogl.sh script ..
[jogl-demos.git] / src / demos / es2 / RedSquare.java
1 package demos.es2;
2
3 import java.nio.*;
4 import java.util.*;
5 import javax.media.opengl.*;
6 import javax.media.nativewindow.*;
7
8 import com.jogamp.opengl.util.*;
9 import com.jogamp.opengl.util.glsl.*;
10
11 import com.jogamp.newt.*;
12 import com.jogamp.newt.event.*;
13 import com.jogamp.newt.opengl.*;
14
15 public class RedSquare extends Thread implements WindowListener, KeyListener, MouseListener, GLEventListener {
16
17     public Window nWindow = null;
18     public GLWindow window;
19     private GLProfile glp;
20     private boolean quit = false;
21     private final String glprofile;
22     private final int type;
23
24     public RedSquare() {
25         this(null, USE_NEWT);
26     }
27
28     public RedSquare(String glprofile, int type) {
29         super();
30         this.glprofile=glprofile;
31         this.type=type;
32     }
33
34     public void windowRepaint(WindowUpdateEvent e) { }
35     public void windowResized(WindowEvent e) { }
36     public void windowMoved(WindowEvent e) { }
37     public void windowGainedFocus(WindowEvent e) { }
38     public void windowLostFocus(WindowEvent e) { }
39     public void windowDestroyNotify(WindowEvent e) {
40         System.out.println("WINDOW-DESTROY NOTIFY "+Thread.currentThread()+" QUIT "+e);
41         quit = true;
42     }
43     public void windowDestroyed(WindowEvent e) {
44         System.out.println("WINDOW-DESTROYED "+Thread.currentThread());
45     }
46
47     public void keyPressed(KeyEvent e) {
48         System.out.println("KEY-PRESSED "+Thread.currentThread()+" UNHANDLED "+e);
49     }
50     public void keyReleased(KeyEvent e) {
51         System.out.println("KEY-RELEASED "+Thread.currentThread()+" UNHANDLED "+e);
52         if( !e.isPrintableKey() || e.isAutoRepeat() ) {
53             return;
54         }
55         if(e.getKeyChar()=='f') {
56             System.out.println("KEY-TYPED "+Thread.currentThread()+" FULLSCREEN "+e);
57             window.setFullscreen(!window.isFullscreen());
58         } else if(e.getKeyChar()=='q') {
59             System.out.println("KEY-TYPED "+Thread.currentThread()+" QUIT "+e);
60             quit = true;
61         } else {
62             System.out.println("KEY-TYPED "+Thread.currentThread()+" UNHANDLED "+e);
63         }
64     }
65
66     public void mouseClicked(MouseEvent e) {
67         System.out.println("MOUSE-CLICKED "+Thread.currentThread()+" UNHANDLED "+e);
68         switch(e.getClickCount()) {
69             case 1:
70                 if(e.getButton()>MouseEvent.BUTTON1) {
71                     window.setFullscreen(!window.isFullscreen());
72                 }
73                 break;
74             default:
75                 quit=true;
76                 break;
77         }
78     }
79     public void mouseEntered(MouseEvent e) {
80     }
81     public void mouseExited(MouseEvent e) {
82     }
83     public void mousePressed(MouseEvent e) {
84     }
85     public void mouseReleased(MouseEvent e) {
86     }
87     public void mouseMoved(MouseEvent e) {
88     }
89     public void mouseDragged(MouseEvent e) {
90     }
91     public void mouseWheelMoved(MouseEvent e) {
92     }
93
94     public boolean shouldQuit() { return quit; }
95
96     public void run() {
97         int width = 800;
98         int height = 480;
99         glp = GLProfile.get(glprofile);
100         System.out.println("RUN "+Thread.currentThread()+" "+glp);
101         try {
102             GLCapabilities caps = new GLCapabilities(glp);
103
104             if(0!=(type&USE_AWT)) {
105                 Display nDisplay = NewtFactory.createDisplay(NativeWindowFactory.TYPE_AWT, null); // local display
106                 Screen nScreen  = NewtFactory.createScreen(nDisplay, 0); // screen 0
107                 nWindow = NewtFactory.createWindow(nScreen, caps);
108                 window = GLWindow.create(nWindow);
109             } else {
110                 window = GLWindow.create(caps);
111             }
112
113             window.addWindowListener(this);
114             window.addMouseListener(this);
115             window.addKeyListener(this);
116             window.addGLEventListener(this);
117
118             // Size OpenGL to Video Surface
119             window.setSize(width, height);
120             // window.setFullscreen(true);
121             window.setVisible(true);
122             window.setUpdateFPSFrames(FPSCounter.DEFAULT_FRAMES_PER_INTERVAL, System.err);
123
124             if(!oneThread) {
125                 do {
126                     display();
127                 } while (!quit && window.getTotalFPSDuration() < 20000) ;
128
129                 shutdown();
130             }
131
132         } catch (Throwable t) {
133             t.printStackTrace();
134         }
135     }
136
137     public void display() {
138         try {
139             window.display();
140         } catch (Throwable t) {
141             t.printStackTrace();
142         }
143     }
144
145     public void shutdown() {
146         try {
147             // Shut things down cooperatively
148             window.destroy();
149             window = null;
150             if(null!=nWindow) {
151                 nWindow.destroy();
152                 nWindow=null;
153             }
154             System.out.println("SHUTDOWN "+Thread.currentThread()+" cleanly");
155         } catch (Throwable t) {
156             t.printStackTrace();
157         }
158     }
159
160
161     ShaderState st;
162     PMVMatrix pmvMatrix;
163
164     private void initShader(GL2ES2 gl) {
165         // Create & Compile the shader objects
166         ShaderCode rsVp = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, RedSquare.class,
167                                             "shader", "shader/bin", "redsquare", false);
168         ShaderCode rsFp = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, RedSquare.class,
169                                             "shader", "shader/bin", "redsquare", false);
170
171         // Create & Link the shader program
172         ShaderProgram sp = new ShaderProgram();
173         sp.add(rsVp);
174         sp.add(rsFp);
175         if(!sp.link(gl, System.err)) {
176             throw new GLException("Couldn't link program: "+sp);
177         }
178
179         // Let's manage all our states using ShaderState.
180         st = new ShaderState();
181         st.attachShaderProgram(gl, sp, false);
182     }
183
184     public void init(GLAutoDrawable drawable) {
185         GL2ES2 gl = drawable.getGL().getGL2ES2();
186         if(swapInterval>=0) {
187             gl.setSwapInterval(swapInterval);
188         }
189
190         System.err.println(Thread.currentThread()+" Entering initialization");
191         System.err.println(Thread.currentThread()+" GL Profile: "+gl.getGLProfile());
192         System.err.println(Thread.currentThread()+" GL:" + gl);
193         System.err.println(Thread.currentThread()+" GL_VERSION=" + gl.glGetString(gl.GL_VERSION));
194         System.err.println(Thread.currentThread()+" GL_EXTENSIONS:");
195         System.err.println(Thread.currentThread()+"   " + gl.glGetString(gl.GL_EXTENSIONS));
196         System.err.println(Thread.currentThread()+" swapInterval: " + swapInterval + " (GL: "+gl.getSwapInterval()+")");
197         System.err.println(Thread.currentThread()+" isShaderCompilerAvailable: " + ShaderUtil.isShaderCompilerAvailable(gl));
198
199         if(debuggl) {
200             try {
201                 // Debug ..
202                 gl = (GL2ES2) gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", GL2ES2.class, gl, null) );
203
204                 // Trace ..
205                 gl = (GL2ES2) gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", GL2ES2.class, gl, new Object[] { System.err } ) );
206             } catch (Exception e) {e.printStackTrace();}
207         }
208
209         pmvMatrix = new PMVMatrix();
210
211         initShader(gl);
212
213         // Push the 1st uniform down the path
214         st.useProgram(gl, true);
215
216         pmvMatrix.glMatrixMode(pmvMatrix.GL_PROJECTION);
217         pmvMatrix.glLoadIdentity();
218         pmvMatrix.glMatrixMode(pmvMatrix.GL_MODELVIEW);
219         pmvMatrix.glLoadIdentity();
220
221         if(!st.uniform(gl, new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.glGetPMvMatrixf()))) {
222             throw new GLException("Error setting PMVMatrix in shader: "+st);
223         }
224         // Allocate vertex arrays
225         GLArrayDataClient vertices = GLArrayDataClient.createGLSL("mgl_Vertex", 3, gl.GL_FLOAT, false, 4);
226         {
227             // Fill them up
228             FloatBuffer verticeb = (FloatBuffer)vertices.getBuffer();
229             verticeb.put(-2);  verticeb.put(  2);  verticeb.put( 0);
230             verticeb.put( 2);  verticeb.put(  2);  verticeb.put( 0);
231             verticeb.put(-2);  verticeb.put( -2);  verticeb.put( 0);
232             verticeb.put( 2);  verticeb.put( -2);  verticeb.put( 0);
233         }
234         vertices.seal(gl, true);
235
236         GLArrayDataClient colors = GLArrayDataClient.createGLSL("mgl_Color",  4, gl.GL_FLOAT, false, 4);
237         {
238             // Fill them up
239             FloatBuffer colorb = (FloatBuffer)colors.getBuffer();
240             colorb.put( 1);    colorb.put( 0);     colorb.put( 0);    colorb.put( 1);
241             colorb.put( 0);    colorb.put( 0);     colorb.put( 1);    colorb.put( 1);
242             colorb.put( 1);    colorb.put( 0);     colorb.put( 0);    colorb.put( 1);
243             colorb.put( 1);    colorb.put( 0);     colorb.put( 0);    colorb.put( 1);
244         }
245         colors.seal(gl, true);
246
247         // OpenGL Render Settings
248         gl.glClearColor(0, 0, 0, 1);
249         gl.glEnable(GL2ES2.GL_DEPTH_TEST);
250
251         st.useProgram(gl, false);
252
253         // Let's show the completed shader state ..
254         System.out.println(Thread.currentThread()+" "+st);
255     }
256
257     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
258         if(null==st) return;
259
260         GL2ES2 gl = drawable.getGL().getGL2ES2();
261
262         st.useProgram(gl, true);
263
264         // Set location in front of camera
265         pmvMatrix.glMatrixMode(pmvMatrix.GL_PROJECTION);
266         pmvMatrix.glLoadIdentity();
267         pmvMatrix.gluPerspective(45.0f, (float)width / (float)height, 1.0f, 100.0f);
268         //pmvMatrix.glOrthof(-4.0f, 4.0f, -4.0f, 4.0f, 1.0f, 100.0f);
269
270         GLUniformData ud = st.getUniform("mgl_PMVMatrix");
271         if(null!=ud) {
272             // same data object
273             st.uniform(gl, ud);
274         }
275
276         st.useProgram(gl, false);
277     }
278
279     public void dispose(GLAutoDrawable drawable) {
280         if(null==st) return;
281
282         GL2ES2 gl = drawable.getGL().getGL2ES2();
283         System.out.println(Thread.currentThread()+" RedSquare.dispose: "+gl.getContext());
284
285         st.destroy(gl);
286         st=null;
287         pmvMatrix=null;
288         System.out.println(Thread.currentThread()+" RedSquare.dispose: FIN");
289     }
290
291     public void display(GLAutoDrawable drawable) {
292         if(null==st) return;
293
294         GL2ES2 gl = drawable.getGL().getGL2ES2();
295
296         st.useProgram(gl, true);
297
298         gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
299
300         // One rotation every four seconds
301         pmvMatrix.glMatrixMode(pmvMatrix.GL_MODELVIEW);
302         pmvMatrix.glLoadIdentity();
303         pmvMatrix.glTranslatef(0, 0, -10);
304         float ang = (window.getTotalFPSDuration() * 360.0f) / 4000.0f;
305         pmvMatrix.glRotatef(ang, 0, 0, 1);
306         pmvMatrix.glRotatef(ang, 0, 1, 0);
307
308         GLUniformData ud = st.getUniform("mgl_PMVMatrix");
309         if(null!=ud) {
310             // same data object
311             st.uniform(gl, ud);
312         }
313
314         // Draw a square
315         gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4);
316
317         st.useProgram(gl, false);
318     }
319
320     public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
321     }
322
323     public static int USE_NEWT      = 0;
324     public static int USE_AWT       = 1 << 0;
325
326     public static boolean oneThread = false;
327     public static int swapInterval = -1;
328     public static boolean debuggl = false;
329
330     public static void main(String[] args) {
331         NewtFactory.setUseEDT(true); // should be the default
332         int type = USE_NEWT ;
333         List threads = new ArrayList();
334         for(int i=0; i<args.length; i++) {
335             if(args[i].equals("-swapi")) {
336                 i++;
337                 try {
338                     swapInterval = Integer.parseInt(args[i]);
339                 } catch (Exception ex) { ex.printStackTrace(); }
340             } else if(args[i].equals("-debug")) {
341                 debuggl=true;
342             } else if(args[i].equals("-1thread")) {
343                 oneThread=true;
344             } else if(args[i].equals("-awt")) {
345                 type |= USE_AWT;
346             } else if(args[i].startsWith("-GL")) {
347                 threads.add(new RedSquare(args[i].substring(1), type));
348             }
349         }
350         if(threads.size()==0) {
351             threads.add(new RedSquare(GLProfile.GL2ES2, type));
352         }
353
354         if(!oneThread) {
355             for(Iterator i = threads.iterator(); i.hasNext(); ) {
356                 ((Thread)i.next()).start();
357             }
358
359             boolean done = false;
360
361             while(!done) {
362                 int aliveCount = 0;
363                 for(Iterator i = threads.iterator(); i.hasNext(); ) {
364                     if ( ((Thread)i.next()).isAlive() ) {
365                         try {
366                             Thread.sleep(100);
367                         } catch (InterruptedException ie) {}
368                         aliveCount++;
369                     }
370                 }
371                 done = 0==aliveCount ;
372             }
373         } else {
374             // init all ..
375             for(Iterator i = threads.iterator(); i.hasNext(); ) {
376                 ((Thread)i.next()).run();
377             }
378             while (threads.size()>0) {
379                 for(Iterator i = threads.iterator(); i.hasNext(); ) {
380                     RedSquare app = (RedSquare) i.next();
381                     if(app.shouldQuit()) {
382                         app.shutdown();
383                         i.remove();
384                     } else {
385                         app.display();
386                     }
387                 }
388             }
389         }
390     }
391 }
http://JogAmp.org git info: FAQ, tutorial and man pages.