JOGL v2.6.0-rc-20250706
JOGL, High-Performance Graphics Binding for Java™ (public API).
TriangleInstancedRendererWithShaderState.java
Go to the documentation of this file.
1package com.jogamp.opengl.test.junit.jogl.demos.gl4;
2
3import java.io.File;
4import java.io.FileOutputStream;
5import java.io.IOException;
6import java.io.PrintStream;
7import java.nio.FloatBuffer;
8import java.util.Random;
9
10import com.jogamp.math.FloatUtil;
11import com.jogamp.math.Matrix4f;
12import com.jogamp.math.Vec3f;
13import com.jogamp.opengl.DebugGL4;
14import com.jogamp.opengl.GL;
15import com.jogamp.opengl.GL2ES2;
16import com.jogamp.opengl.GL4;
17import com.jogamp.opengl.GLAutoDrawable;
18import com.jogamp.opengl.GLEventListener;
19import com.jogamp.opengl.GLException;
20import com.jogamp.opengl.GLUniformData;
21import com.jogamp.opengl.TraceGL4;
22import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
23import com.jogamp.opengl.util.GLArrayDataClient;
24import com.jogamp.opengl.util.GLArrayDataServer;
25import com.jogamp.opengl.util.PMVMatrix;
26import com.jogamp.opengl.util.glsl.ShaderCode;
27import com.jogamp.opengl.util.glsl.ShaderProgram;
28import com.jogamp.opengl.util.glsl.ShaderState;
29
31 private float aspect;
32
33 private static final String shaderBasename = "triangles";
34// private static final boolean useInterleaved = false;
35 private static final boolean useInterleaved = true;
36
37 private ShaderState st;
38 private PMVMatrix projectionMatrix;
39 private GLUniformData projectionMatrixUniform;
40 private GLUniformData transformMatrixUniform;
41
42 private GLArrayDataServer interleavedVBO;
43 private GLArrayDataClient verticesVBO;
44 private GLArrayDataClient colorsVBO;
45
46 private static final int NO_OF_INSTANCE = 30;
47 private final FloatBuffer triangleTransform = FloatBuffer.allocate(16 * NO_OF_INSTANCE);
48 private final Matrix4f[] mat = new Matrix4f[NO_OF_INSTANCE];
49 private final float[] rotationSpeed = new float[NO_OF_INSTANCE];
50
51 private static final boolean useTraceGL = false;
52 private PrintStream stream;
53 private final IInstancedRenderingView view;
54
55 private boolean isInitialized = false;
56
58 this.view = view;
59
60 if(useTraceGL) {
61 try {
62 stream = new PrintStream(new FileOutputStream(new File("instanced-with-st.txt")));
63 } catch (final IOException e1) {
64 e1.printStackTrace();
65 }
66 }
67
68 initTransform();
69 }
70
71 private void initTransform() {
72 final Random rnd = new Random();
73 final Matrix4f tmp = new Matrix4f();
74 for(int i = 0; i < NO_OF_INSTANCE; i++) {
75 rotationSpeed[i] = 0.3f * rnd.nextFloat();
76 mat[i] = new Matrix4f();
77 mat[i].loadIdentity();
78 final float scale = 1f + 4 * rnd.nextFloat();
79 mat[i].scale(scale, tmp);
80 //setup initial position of each triangle
81 mat[i].translate(20f * rnd.nextFloat() - 10f,
82 10f * rnd.nextFloat() - 5f,
83 0f, tmp);
84 }
85 }
86
87 @Override
88 public void init(final GLAutoDrawable drawable) {
89 final GL4 gl = drawable.getGL().getGL4();
90 drawable.setGL(new DebugGL4(gl));
91 if(useTraceGL) {
92 drawable.setGL(new TraceGL4(gl, stream));
93 }
94
95 gl.glClearColor(1, 1, 1, 1); //white background
96// gl.glClearColor(0, 0, 0, 1); //black background
97 gl.glClearDepth(1.0f);
98
99 System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities());
100 System.err.println("INIT GL IS: " + gl.getClass().getName());
101 System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR));
102 System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER));
103 System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION));
104
105 initShader(gl);
106 projectionMatrix = new PMVMatrix();
107 projectionMatrixUniform = new GLUniformData("mgl_PMatrix", 4, 4, projectionMatrix.getSyncP());
108 st.ownUniform(projectionMatrixUniform);
109 if(!st.uniform(gl, projectionMatrixUniform)) {
110 throw new GLException("Error setting mgl_PMatrix in shader: " + st);
111 }
112
113 transformMatrixUniform = new GLUniformData("mgl_MVMatrix", 4, 4, triangleTransform);
114
115 st.ownUniform(transformMatrixUniform);
116 if(!st.uniform(gl, transformMatrixUniform)) {
117 throw new GLException("Error setting mgl_MVMatrix in shader: " + st);
118 }
119
120 if(useInterleaved) {
121 initVBO_interleaved(gl);
122 } else {
123 initVBO_nonInterleaved(gl);
124 }
125
126 isInitialized = true;
127 }
128
129 @Override
130 public void display(final GLAutoDrawable drawable) {
131 if(!isInitialized ) return;
132
133 final GL4 gl = drawable.getGL().getGL4();
135
136 st.useProgram(gl, true);
137 projectionMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
138 projectionMatrix.glPushMatrix();
139
140 float winScale = 0.1f;
141 if(view != null) winScale = view.getScale();
142 projectionMatrix.glScalef(winScale, winScale, winScale);
143 st.uniform(gl, projectionMatrixUniform);
144 projectionMatrix.glPopMatrix();
145
146 generateTriangleTransform();
147 st.uniform(gl, transformMatrixUniform);
148 if(useInterleaved) {
149 interleavedVBO.enableBuffer(gl, true);
150 } else {
151 verticesVBO.enableBuffer(gl, true);
152 colorsVBO.enableBuffer(gl, true);
153 }
154 //gl.glVertexAttribDivisor() is not required since each instance has the same attribute (color).
155 gl.glDrawArraysInstanced(GL.GL_TRIANGLES, 0, 3, NO_OF_INSTANCE);
156 if(useInterleaved) {
157 interleavedVBO.enableBuffer(gl, false);
158 } else {
159 verticesVBO.enableBuffer(gl, false);
160 colorsVBO.enableBuffer(gl, false);
161 }
162 st.useProgram(gl, false);
163 }
164
165 @Override
166 public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) {
167 final GL4 gl3 = drawable.getGL().getGL4();
168 gl3.glViewport(0, 0, width, height);
169 aspect = (float) width / (float) height;
170
171 projectionMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
172 projectionMatrix.glLoadIdentity();
173 projectionMatrix.gluPerspective(FloatUtil.QUARTER_PI, aspect, 0.001f, 20f);
174 projectionMatrix.gluLookAt(new Vec3f(0, 0, -10), new Vec3f(0, 0, 0), new Vec3f(0, 1, 0));
175 }
176
177 @Override
178 public void dispose(final GLAutoDrawable drawable){
179 final GL4 gl = drawable.getGL().getGL4();
180 st.destroy(gl);
181 }
182
183 private void generateTriangleTransform() {
184 triangleTransform.clear();
185 final Matrix4f tmp = new Matrix4f();
186 for(int i = 0; i < NO_OF_INSTANCE; i++) {
187 mat[i].rotate(rotationSpeed[i], 0, 0, 1, tmp);
188 mat[i].get(triangleTransform);
189 }
190 triangleTransform.rewind();
191 }
192
193 private void initVBO_nonInterleaved(final GL4 gl) {
194 final int VERTEX_COUNT = 3;
195
196 verticesVBO = GLArrayDataClient.createGLSL("mgl_Vertex", 3, GL.GL_FLOAT, false, VERTEX_COUNT);
197 final FloatBuffer verticeBuf = (FloatBuffer)verticesVBO.getBuffer();
198 verticeBuf.put(vertices);
199 verticesVBO.seal(gl, true);
200
201 colorsVBO = GLArrayDataClient.createGLSL("mgl_Color", 4, GL.GL_FLOAT, false, VERTEX_COUNT);
202 final FloatBuffer colorBuf = (FloatBuffer)colorsVBO.getBuffer();
203 colorBuf.put(colors);
204 colorsVBO.seal(gl, true);
205
206 verticesVBO.enableBuffer(gl, false);
207 colorsVBO.enableBuffer(gl, false);
208
209 st.ownAttribute(verticesVBO, true);
210 st.ownAttribute(colorsVBO, true);
211 st.useProgram(gl, false);
212 }
213
214 private void initVBO_interleaved(final GL4 gl) {
215 final int VERTEX_COUNT = 3;
216 interleavedVBO = GLArrayDataServer.createGLSLInterleaved(3 + 4, GL.GL_FLOAT, false, VERTEX_COUNT, GL.GL_STATIC_DRAW);
217 interleavedVBO.addGLSLSubArray("mgl_Vertex", 3, GL.GL_ARRAY_BUFFER);
218 interleavedVBO.addGLSLSubArray("mgl_Color", 4, GL.GL_ARRAY_BUFFER);
219
220 final FloatBuffer ib = (FloatBuffer)interleavedVBO.getBuffer();
221
222 for(int i = 0; i < VERTEX_COUNT; i++) {
223 ib.put(vertices, i*3, 3);
224 ib.put(colors, i*4, 4);
225 }
226 interleavedVBO.seal(gl, true);
227 interleavedVBO.enableBuffer(gl, false);
228 st.ownAttribute(interleavedVBO, true);
229 st.useProgram(gl, false);
230 }
231
232 private void initShader(final GL4 gl) {
233 // Create & Compile the shader objects
234 final ShaderCode vp0 = ShaderCode.create(gl, GL2ES2.GL_VERTEX_SHADER, this.getClass(),
235 "shader", "shader/bin", shaderBasename, true);
236 final ShaderCode fp0 = ShaderCode.create(gl, GL2ES2.GL_FRAGMENT_SHADER, this.getClass(),
237 "shader", "shader/bin", shaderBasename, true);
238 vp0.replaceInShaderSource("NO_OF_INSTANCE", String.valueOf(NO_OF_INSTANCE));
239
240 vp0.defaultShaderCustomization(gl, true, true);
241 fp0.defaultShaderCustomization(gl, true, true);
242
243 //vp0.dumpShaderSource(System.out);
244
245 // Create & Link the shader program
246 final ShaderProgram sp = new ShaderProgram();
247 sp.add(vp0);
248 sp.add(fp0);
249 if(!sp.link(gl, System.err)) {
250 throw new GLException("Couldn't link program: "+sp);
251 }
252
253 // Let's manage all our states using ShaderState.
254 st = new ShaderState();
255 st.attachShaderProgram(gl, sp, true);
256 }
257
258
259 private static final float[] vertices = {
260 1.0f, 0.0f, 0,
261 -0.5f, 0.866f, 0,
262 -0.5f, -0.866f, 0
263 };
264
265 private final float[] colors = {
266 1.0f, 0.0f, 0.0f, 1.0f,
267 0.0f, 1.0f, 0.0f, 1.0f,
268 0f, 0f, 1.0f, 1f
269 };
270
271}
Basic Float math utility functions.
Definition: FloatUtil.java:83
static final float QUARTER_PI
The value PI/4, i.e.
Basic 4x4 float matrix implementation using fields for intensive use-cases (host operations).
Definition: Matrix4f.java:89
final Matrix4f loadIdentity()
Set this matrix to identity.
Definition: Matrix4f.java:172
final Matrix4f rotate(final float ang_rad, final float x, final float y, final float z, final Matrix4f tmp)
Rotate this matrix about give axis and angle in radians, i.e.
Definition: Matrix4f.java:1525
final Matrix4f scale(final float x, final float y, final float z, final Matrix4f tmp)
Scale this matrix, i.e.
Definition: Matrix4f.java:1580
final Matrix4f translate(final float x, final float y, final float z, final Matrix4f tmp)
Translate this matrix, i.e.
Definition: Matrix4f.java:1558
float get(final int i)
Gets the ith component, 0 <= i < 16.
Definition: Matrix4f.java:279
3D Vector based upon three float components.
Definition: Vec3f.java:37
final SyncMatrix4f getSyncP()
Returns the SyncMatrix of projection matrix (P).
A generic exception for OpenGL errors used throughout the binding as a substitute for RuntimeExceptio...
GLSL uniform data wrapper encapsulating data to be uploaded to the GPU as a uniform.
void init(final GLAutoDrawable drawable)
Called by the drawable immediately after the OpenGL context is initialized.
void display(final GLAutoDrawable drawable)
Called by the drawable to initiate OpenGL rendering by the client.
void reshape(final GLAutoDrawable drawable, 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 drawable)
Notifies the listener to perform the release of all OpenGL resources per GLContext,...
static GLArrayDataClient createGLSL(final String name, final int comps, final int dataType, final boolean normalized, final int initialElementCount)
Create a client side buffer object, using a custom GLSL array attribute name and starting with a new ...
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 createGLSLInterleaved(final int compsPerElement, final int dataType, final boolean normalized, final int initialElementCount, final int vboUsage)
Create a VBO for GLSL interleaved array data starting with a new created Buffer object with initialEl...
GLArrayDataWrapper addGLSLSubArray(final String name, final int comps, final int vboTarget)
Configure a segment of this GLSL interleaved array (see createGLSLInterleaved(int,...
Buffer getBuffer()
The Buffer holding the data, may be null if a GPU buffer without client bound data.
PMVMatrix implements a subset of the fixed function pipeline GLMatrixFunc using PMVMatrix4f.
Definition: PMVMatrix.java:62
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 gluPerspective(final float fovy_rad, final float aspect, final float zNear, final float zFar)
Multiply the current matrix with the perspective/frustum matrix.
Definition: PMVMatrix.java:499
final void glPushMatrix()
Push the current matrix to it's stack, while preserving it's values.
Definition: PMVMatrix.java:458
final void gluLookAt(final Vec3f eye, final Vec3f center, final Vec3f up)
Multiply the current matrix with the eye, object and orientation, i.e.
Definition: PMVMatrix.java:507
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
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.
void glClearDepth(double depth)
Aliased entrypoint of void {@native glClearDepth}(GLclampd depth); and void {@native glClearDepthf...
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
void glDrawArraysInstanced(int mode, int first, int count, int instancecount)
Entry point to C language function: void {@native glDrawArraysInstanced}(GLenum mode,...
A higher-level abstraction than GLDrawable which supplies an event based mechanism (GLEventListener) ...
GL getGL()
Returns the GL pipeline object this GLAutoDrawable uses.
GL setGL(GL gl)
Sets the GL pipeline object this GLAutoDrawable uses.
GL4 getGL4()
Casts this object to the GL4 interface.
GLCapabilitiesImmutable getChosenGLCapabilities()
Fetches the GLCapabilitiesImmutable corresponding to the chosen OpenGL capabilities (pixel format / v...
Declares events which client code can use to manage OpenGL rendering into a GLAutoDrawable.
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_TRIANGLES
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_TRIANGLES" with expre...
Definition: GL.java:145
static final int GL_VERSION
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_VERSION" with express...
Definition: GL.java:190
static final int GL_FLOAT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_FLOAT" with expressio...
Definition: GL.java:786
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,...
String glGetString(int name)
Entry point to C language function: const GLubyte * {@native glGetString}(GLenum name) Part of GL_...
static final int GL_RENDERER
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_RENDERER" with expres...
Definition: GL.java:662
void glClear(int mask)
Entry point to C language function: void {@native glClear}(GLbitfield mask) Part of GL_ES_VERSION_...
static final int GL_VENDOR
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_VENDOR" with expressi...
Definition: GL.java:607
void glViewport(int x, int y, int width, int height)
Entry point to C language function: void {@native glViewport}(GLint x, GLint y, GLsizei width,...
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_ARRAY_BUFFER
GL_VERSION_1_5, GL_ES_VERSION_2_0, GL_VERSION_ES_1_0, GL_ARB_vertex_buffer_object Alias for: GL_ARRAY...
Definition: GL.java:633
Subset of OpenGL fixed function pipeline's matrix operations.
static final int GL_PROJECTION
Matrix mode projection.