Login  Register

Re: Cross platform GLSL (ES)?

Posted by Xerxes Rånby on Dec 13, 2013; 1:02pm
URL: https://forum.jogamp.org/Cross-platform-GLSL-ES-tp4030871p4030880.html

In order to create cross platform GLSL shaders the following three points have to be taken into account:

1. GLSL VERSION >= 130 uses in and out keywords instead of attributes and varying.  GLSL VERSION >= 130 also require the fragment shader to explicitly define the out variable. GLSL VERSION >= 130 compatibility can be handled by adding some GLSL pre-processor defines at the beginning of the shaders.
Vertex shader:
#if __VERSION__ >= 130
   #define attribute in
   #define varying out
#endif

Fragment shader:
#if __VERSION__ >= 130
   #define varying in
   out vec4 mgl_FragColor;
 #else
   #define mgl_FragColor gl_FragColor  
#endif

Look at the Cross platform GLSL shaders used by the JogAmp JOGL junit tests how to add the pre-processor defines:
http://jogamp.org/git/?p=jogl.git;a=tree;f=src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/shader;hb=HEAD


2. Some OpenGL contexts require the GLSL #version to be explicitly set at the start of the shader or else it will refuse to compile the shader. The GLSL #version must match a version that is compatible with the OpenGL context or else the shader will refuse to compile.

JogAmp JOGL can return the matching String containing the #version you need to add by analysing the context at runtime by using: gl.getContext().getGLSLVersionString()

http://jogamp.org/deployment/jogamp-current/javadoc/jogl/javadoc/com/jogamp/opengl/util/glsl/ShaderCode.html#addGLSLVersion%28javax.media.opengl.GL2ES2%29

3. You need to add a default precision qualifier if you target es2 es3 or gl3 opengl contexts.

You can use the com.jogamp.opengl.util.glsl.ShaderCode defaultShaderCustomization to add the GLSL shader customization required by your OpenGL context this will allow the shader to work on both desktop and mobile.
http://jogamp.org/deployment/jogamp-current/javadoc/jogl/javadoc/com/jogamp/opengl/util/glsl/ShaderCode.html#addDefaultShaderPrecision%28javax.media.opengl.GL2ES2,%20int%29


2 & 3 can be fixed in one go by using the com.jogamp.opengl.util.glsl.ShaderCode class to load your shaders from disk and customize them using defaultShaderCustomization

http://jogamp.org/deployment/jogamp-current/javadoc/jogl/javadoc/com/jogamp/opengl/util/glsl/ShaderCode.html#defaultShaderCustomization%28javax.media.opengl.GL2ES2,%20boolean,%20boolean%29

Look at how GLSL shaders are loaded inside the jogamp jogl junit tests using ShaderCode for cross platform GLSL use.
http://jogamp.org/git/?p=jogl.git;a=blob;f=src/test/com/jogamp/opengl/test/junit/jogl/demos/es2/RedSquareES2.java;hb=HEAD#l91

Cheers
Xerxes