JOGL v2.6.0-rc-20250822
JOGL, High-Performance Graphics Binding for Java™ (public API).
RedSquareES2.java
Go to the documentation of this file.
1/**
2 * Copyright 2010 JogAmp Community. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification, are
5 * permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this list of
8 * conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
11 * of conditions and the following disclaimer in the documentation and/or other materials
12 * provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
15 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
16 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
21 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
22 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 *
24 * The views and conclusions contained in the software and documentation are those of the
25 * authors and should not be interpreted as representing official policies, either expressed
26 * or implied, of JogAmp Community.
27 */
28package com.jogamp.opengl.demos.es2;
29
30import com.jogamp.opengl.JoglVersion;
31import com.jogamp.opengl.demos.util.CommandlineOptions;
32import com.jogamp.opengl.util.Animator;
33import com.jogamp.opengl.util.GLArrayDataServer;
34import com.jogamp.opengl.util.PMVMatrix;
35import com.jogamp.opengl.util.caps.NonFSAAGLCapsChooser;
36import com.jogamp.opengl.util.glsl.ShaderCode;
37import com.jogamp.opengl.util.glsl.ShaderProgram;
38import com.jogamp.opengl.util.glsl.ShaderState;
39import com.jogamp.common.util.VersionUtil;
40import com.jogamp.newt.event.WindowAdapter;
41import com.jogamp.newt.event.WindowEvent;
42import com.jogamp.newt.opengl.GLWindow;
43import com.jogamp.opengl.GL;
44import com.jogamp.opengl.GL2ES2;
45import com.jogamp.opengl.GLAutoDrawable;
46import com.jogamp.opengl.GLCapabilities;
47import com.jogamp.opengl.GLEventListener;
48import com.jogamp.opengl.GLUniformData;
49import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
50
51public class RedSquareES2 implements GLEventListener {
52 private ShaderState st;
53 private PMVMatrix pmvMatrix;
54 private GLUniformData pmvMatrixUniform;
55 private GLArrayDataServer vertices ;
56 private GLArrayDataServer colors ;
57 private long t0;
58 private int swapInterval = 0;
59 private float aspect = 1.0f;
60 private boolean doRotate = true;
61 private boolean verbose = true;
62 private boolean clearBuffers = true;
63
64 public RedSquareES2(final int swapInterval) {
65 this.swapInterval = swapInterval;
66 }
67
68 public RedSquareES2() {
69 this.swapInterval = 1;
70 }
71
72 public void setAspect(final float aspect) { this.aspect = aspect; }
73 public void setDoRotation(final boolean rotate) { this.doRotate = rotate; }
74 public void setVerbose(final boolean v) { verbose = v; }
75 public void setClearBuffers(final boolean v) { clearBuffers = v; }
76
77 @Override
78 public void init(final GLAutoDrawable glad) {
79 if(verbose) {
80 System.err.println(Thread.currentThread()+" RedSquareES2.init");
81 }
82 final GL2ES2 gl = glad.getGL().getGL2ES2();
83
84 if(verbose) {
85 System.err.println("RedSquareES2 init on "+Thread.currentThread());
86 System.err.println("Chosen GLCapabilities: " + glad.getChosenGLCapabilities());
87 System.err.println("INIT GL IS: " + gl.getClass().getName());
88 System.err.println(JoglVersion.getGLStrings(gl, null, false).toString());
89 }
90 if( !gl.hasGLSL() ) {
91 System.err.println("No GLSL available, no rendering.");
92 return;
93 }
94 st = new ShaderState();
95 st.setVerbose(true);
96 final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(), "shader",
97 "shader/bin", "RedSquareShader", true);
98 final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(), "shader",
99 "shader/bin", "RedSquareShader", true);
100 vp0.defaultShaderCustomization(gl, true, true);
101 fp0.defaultShaderCustomization(gl, true, true);
102 final ShaderProgram sp0 = new ShaderProgram();
103 sp0.add(gl, vp0, System.err);
104 sp0.add(gl, fp0, System.err);
105 st.attachShaderProgram(gl, sp0, true);
106
107 // setup mgl_PMVMatrix
108 pmvMatrix = new PMVMatrix();
110 pmvMatrix.glLoadIdentity();
112 pmvMatrix.glLoadIdentity();
113 pmvMatrixUniform = new GLUniformData("mgl_PMVMatrix", 4, 4, pmvMatrix.getSyncPMv()); // P, Mv
114 st.ownUniform(pmvMatrixUniform);
115 st.uniform(gl, pmvMatrixUniform);
116
117 // Allocate Vertex Array
118 vertices = GLArrayDataServer.createGLSL("mgl_Vertex", 3, GL.GL_FLOAT, false, 4, GL.GL_STATIC_DRAW);
119 vertices.putf(-2); vertices.putf( 2); vertices.putf( 0);
120 vertices.putf( 2); vertices.putf( 2); vertices.putf( 0);
121 vertices.putf(-2); vertices.putf(-2); vertices.putf( 0);
122 vertices.putf( 2); vertices.putf(-2); vertices.putf( 0);
123 vertices.seal(gl, true);
124 st.ownAttribute(vertices, true);
125 vertices.enableBuffer(gl, false);
126
127 // Allocate Color Array
128 colors= GLArrayDataServer.createGLSL("mgl_Color", 4, GL.GL_FLOAT, false, 4, GL.GL_STATIC_DRAW);
129 colors.putf(1); colors.putf(0); colors.putf(0); colors.putf(1);
130 colors.putf(0); colors.putf(0); colors.putf(1); colors.putf(1);
131 colors.putf(1); colors.putf(0); colors.putf(0); colors.putf(1);
132 colors.putf(1); colors.putf(0); colors.putf(0); colors.putf(1);
133 colors.seal(gl, true);
134 st.ownAttribute(colors, true);
135 colors.enableBuffer(gl, false);
136
137 // OpenGL Render Settings
139 st.useProgram(gl, false);
140
141 t0 = System.currentTimeMillis();
142 if(verbose) {
143 System.err.println(Thread.currentThread()+" RedSquareES2.init FIN");
144 }
145 }
146
147 @Override
148 public void display(final GLAutoDrawable glad) {
149 final long t1 = System.currentTimeMillis();
150
151 final GL2ES2 gl = glad.getGL().getGL2ES2();
152 if( clearBuffers ) {
153 gl.glClearColor(0, 0, 0, 0);
155 }
156 if( !gl.hasGLSL() ) {
157 return;
158 }
159 st.useProgram(gl, true);
160 // One rotation every four seconds
162 pmvMatrix.glLoadIdentity();
163 pmvMatrix.glTranslatef(0, 0, -10);
164 if(doRotate) {
165 final float ang = ((t1 - t0) * 360.0F) / 4000.0F;
166 pmvMatrix.glRotatef(ang, 0, 0, 1);
167 pmvMatrix.glRotatef(ang, 0, 1, 0);
168 }
169 st.uniform(gl, pmvMatrixUniform);
170
171 // Draw a square
172 vertices.enableBuffer(gl, true);
173 colors.enableBuffer(gl, true);
175 vertices.enableBuffer(gl, false);
176 colors.enableBuffer(gl, false);
177 st.useProgram(gl, false);
178 }
179
180 @Override
181 public void reshape(final GLAutoDrawable glad, final int x, final int y, final int width, final int height) {
182 final GL2ES2 gl = glad.getGL().getGL2ES2();
183 if(verbose) {
184 System.err.println(Thread.currentThread()+" RedSquareES2.reshape "+x+"/"+y+" "+width+"x"+height+", swapInterval "+swapInterval+
185 ", drawable 0x"+Long.toHexString(gl.getContext().getGLDrawable().getHandle()));
186 }
187 gl.setSwapInterval(swapInterval);
188 if( !gl.hasGLSL() ) {
189 return;
190 }
191
192 st.useProgram(gl, true);
193 // Set location in front of camera
195 pmvMatrix.glLoadIdentity();
196
197 // compute projection parameters 'normal' perspective
198 final float fovy=45f;
199 final float aspect2 = ( (float) width / (float) height ) / aspect;
200 final float zNear=1f;
201 final float zFar=100f;
202
203 // compute projection parameters frustum
204 final float t=(float)Math.tan(fovy*((float)Math.PI)/360.0f)*zNear;
205 final float b=-1.0f*t;
206 final float l=aspect2*b;
207 final float r=aspect2*t;
208
209 pmvMatrix.glFrustumf(l, r, b, t, zNear, zFar);
210 //pmvMatrix.glOrthof(-4.0f, 4.0f, -4.0f, 4.0f, 1.0f, 100.0f);
211 st.uniform(gl, pmvMatrixUniform);
212 st.useProgram(gl, false);
213
214 System.err.println(Thread.currentThread()+" RedSquareES2.reshape FIN");
215 }
216
217 @Override
218 public void dispose(final GLAutoDrawable glad) {
219 if(verbose) {
220 System.err.println(Thread.currentThread()+" RedSquareES2.dispose");
221 }
222 final GL2ES2 gl = glad.getGL().getGL2ES2();
223 if( !gl.hasGLSL() ) {
224 return;
225 }
226 st.destroy(gl);
227 st = null;
228 pmvMatrix = null;
229 if(verbose) {
230 System.err.println(Thread.currentThread()+" RedSquareES2.dispose FIN");
231 }
232 }
233
234 public static void main(final String[] args) {
235 final CommandlineOptions options = new CommandlineOptions(1280, 720, 0);
236
237 System.err.println(options);
238 System.err.println(VersionUtil.getPlatformInfo());
239 // System.err.println(JoglVersion.getAllAvailableCapabilitiesInfo(dpy.getGraphicsDevice(), null).toString());
240
241 final GLCapabilities reqCaps = options.getGLCaps();
242 System.out.println("Requested: " + reqCaps);
243
244 final GLWindow window = GLWindow.create(reqCaps);
245 if( 0 == options.sceneMSAASamples ) {
247 }
248 window.setSize(options.surface_width, options.surface_height);
249 window.setTitle(RedSquareES2.class.getSimpleName());
250
251 window.addGLEventListener(new RedSquareES2(1));
252
253 final Animator animator = new Animator(0 /* w/o AWT */);
254 animator.setUpdateFPSFrames(5*60, null);
255 animator.add(window);
256
257 window.addWindowListener(new WindowAdapter() {
258 @Override
259 public void windowDestroyed(final WindowEvent e) {
260 animator.stop();
261 }
262 });
263
264 window.setVisible(true);
265 animator.start();
266 }
267}
final SyncMatrices4f getSyncPMv()
Returns SyncMatrices4f of 2 matrices within one FloatBuffer: P and Mv.
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.
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 void main(final String[] args)
void setDoRotation(final boolean rotate)
void display(final GLAutoDrawable glad)
Called by the drawable to initiate OpenGL rendering by the client.
void init(final GLAutoDrawable glad)
Called by the drawable immediately after the OpenGL context is initialized.
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.
void dispose(final GLAutoDrawable glad)
Notifies the listener to perform the release of all OpenGL resources per GLContext,...
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
void seal(final GL gl, final boolean seal)
Convenience method calling seal(boolean) and enableBuffer(GL, boolean).
void enableBuffer(final GL gl, final boolean enable)
Enables the buffer if enable is true, and transfers the data if required.
static GLArrayDataServer createGLSL(final String name, final int compsPerElement, final int dataType, final boolean normalized, final int initialElementCount, final int vboUsage)
Create a VBO, using a custom GLSL array attribute name and starting with a new created Buffer object ...
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 glMatrixMode(final int matrixName)
Sets the current matrix mode.
Definition: PMVMatrix.java:218
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 glLoadIdentity()
Load the current matrix with the identity matrix.
Definition: PMVMatrix.java:325
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 ...
void ownAttribute(final GLArrayData attribute, final boolean own)
Binds or unbinds the GLArrayData lifecycle to this ShaderState.
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.
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.
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:585
A higher-level abstraction than GLDrawable which supplies an event based mechanism (GLEventListener) ...
GL getGL()
Returns the GL pipeline object this GLAutoDrawable uses.
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.
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...
Declares events which client code can use to manage OpenGL rendering into a GLAutoDrawable.
void glDrawArrays(int mode, int first, int count)
Entry point to C language function: void {@native glDrawArrays}(GLenum mode, GLint first,...
static final int GL_STATIC_DRAW
GL_VERSION_1_5, GL_ES_VERSION_2_0, GL_VERSION_ES_1_0, GL_ARB_vertex_buffer_object Alias for: GL_STATI...
Definition: GL.java:673
static final int GL_FLOAT
GL_ES_VERSION_2_0, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_FLOAT" with expression '0x1406',...
Definition: GL.java:786
static final int GL_COLOR_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_COLOR_BUFFER_BIT" with expression '0x...
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_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_TEST" with expression '0x0B71',...
Definition: GL.java:43
void glClear(int mask)
Entry point to C language function: void {@native glClear}(GLbitfield mask) Part of GL_ES_VERSION_...
static final int GL_TRIANGLE_STRIP
GL_ES_VERSION_2_0, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_TRIANGLE_STRIP" with expression '0x00...
Definition: GL.java:760
static final int GL_DEPTH_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_BUFFER_BIT" with expression '0x...
Definition: GL.java:738
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.