jme3_shaders.adoc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. = JME3 and Shaders
  2. :revnumber: 2.0
  3. :revdate: 2020/07/22
  4. == Shaders Basics
  5. Shaders are sets of instructions that are executed on the GPU. They are used to take advantage of hardware acceleration available on the GPU for rendering purposes.
  6. This paper only covers Vertex and Fragment shaders because they are the only ones supported by JME3 for the moment. Be aware that there are some other types of shaders (geometry, tessellation,…).
  7. There are multiple frequently used languages that you may encounter to code shaders but as JME3 is based on OpenGL, shaders in JME use GLSL and any example in this paper will be written in GLSL.
  8. === How Does it work?
  9. To keep it Simple: The Vertex shader is executed once for each vertex in the view, then the Fragment shader (also called the Pixel shader) is executed once for each pixel on the screen.
  10. The main purpose of the Vertex shader is to compute the screen coordinate of a vertex (where this vertex will be displayed on screen) while the main purpose of the Fragment shader is to compute the color of a pixel.
  11. This is a very simplified graphic to describe the call stack:
  12. image:shader/jme3andshaders.png[jme3andshaders.png,width="",height="", align="left]
  13. The main program sends mesh data to the vertex shader (vertex position in object space, normals, tangents, etc..). The vertex shader computes the screen position of the vertex and sends it to the Fragment shader. The fragment shader computes the color, and the result is displayed on screen or in a texture.
  14. === Variables scope
  15. There are different types of scope for variables in a shader:
  16. * uniform: User defined variables that are passed by the main program to the vertex and fragment shader, these variables are global for a given execution of a shader.
  17. * attribute: Per-vertex variables passed by the engine to the shader, like position, normal, etc (Mesh data in the graphic)
  18. * varying: Variables passed from the vertex shader to the fragment shader.
  19. There is a large panel of variable types to be used, for more information about it I recommend reading the GLSL specification link:http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.20.8.pdf[here].
  20. === Spaces and Matrices
  21. To understand the coming example you must know about the different spaces in 3D computer graphics, and the matrices used to translate coordinate from one space to another.
  22. image:shader/jme3andshaders-1.png[jme3andshaders-1.png,width="",height="", align="left"]
  23. The engine passes the object space coordinates to the vertex shader. We need to compute its position in projection space. To do that we transform the object space position by the WorldViewProjectionMatrix, which is a combination of the World, View, Projection matrices (who would have guessed?).
  24. === Simple example: rendering a solid color on an object
  25. Here is the simplest application to shaders, rendering a solid color.
  26. Vertex Shader:
  27. [source,java]
  28. ----
  29. //the global uniform World view projection matrix
  30. //(more on global uniforms below)
  31. uniform mat4 g_WorldViewProjectionMatrix;
  32. //The attribute inPosition is the Object space position of the vertex
  33. attribute vec3 inPosition;
  34. void main(){
  35. //Transformation of the object space coordinate to projection space
  36. //coordinates.
  37. //- gl_Position is the standard GLSL variable holding projection space
  38. //position. It must be filled in the vertex shader
  39. //- To convert position we multiply the worldViewProjectionMatrix by
  40. //by the position vector.
  41. //The multiplication must be done in this order.
  42. gl_Position = g_WorldViewProjectionMatrix * vec4(inPosition, 1.0);
  43. }
  44. ----
  45. Fragment Shader :
  46. [source,java]
  47. ----
  48. void main(){
  49. //returning the color of the pixel (here solid blue)
  50. //- gl_FragColor is the standard GLSL variable that holds the pixel
  51. //color. It must be filled in the Fragment Shader.
  52. gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
  53. }
  54. ----
  55. For example applying this shader to a sphere would render a solid blue sphere on screen.
  56. == How to use shaders in JME3
  57. You probably heard that JME3 is "`shader oriented`", but what does that mean? +
  58. Usually, to use shaders you must create a program. This program specifies the vertex shader and the fragment shader to use. JME3 encloses this in the material system. Every material in JME3 uses shaders.
  59. For example let’s have a look at the SolidColor.j3md file :
  60. [source,java]
  61. ----
  62. MaterialDef Solid Color {
  63. //This is the complete list of user defined uniforms to be used in the
  64. //shaders
  65. MaterialParameters {
  66. Vector4 Color
  67. }
  68. Technique {
  69. //This is where the vertex and fragment shader files are
  70. //specified
  71. VertexShader GLSL100: Common/MatDefs/Misc/SolidColor.vert
  72. FragmentShader GLSL100: Common/MatDefs/Misc/SolidColor.frag
  73. //This is where you specify which global uniform you need for your
  74. //shaders
  75. WorldParameters {
  76. WorldViewProjectionMatrix
  77. }
  78. }
  79. Technique FixedFunc {
  80. }
  81. }
  82. ----
  83. For more information on JME3 material system, I suggest you read link:https://hub.jmonkeyengine.org/t/jmonkeyengine3-material-system-full-explanation/12947[jMonkeyEngine3 material system - full explanation].
  84. === JME3 Global uniforms
  85. JME3 can expose pre-computed global uniforms to your shaders. You must specify the ones that are required for your shader in the WorldParameter's section of the material definition file (.j3md).
  86. [NOTE]
  87. ====
  88. In the shader, the uniform names will be prefixed by a "`g_`".
  89. ====
  90. In the example above, WorldViewProjectionMatrix is declared as uniform mat4 g_WorldViewProjectionMatrix in the shader.
  91. The complete list of global uniforms that can be used in JME3 can be found in link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-core/src/main/java/com/jme3/shader/UniformBinding.java[UniformBinding.java].
  92. === JME3 Lighting Global uniforms
  93. JME3 uses some global uniforms for lighting:
  94. * g_LightDirection (vec4): the direction of the light
  95. ** use for SpotLight: x,y,z contain the world direction vector of the light, the w component contains the spotlight angle cosine
  96. * g_LightColor (vec4): the color of the light
  97. * g_LightPosition: the position of the light
  98. ** use for SpotLight: x,y,z contain the world position of the light, the w component contains 1/lightRange
  99. ** use for PointLight: x,y,z contain the world position of the light, the w component contains 1/lightRadius
  100. ** use for DirectionalLight: strangely enough it's used for the direction of the light…this might change though. The fourth component contains -1 and it's used in the lighting shader to know if it's a directionalLight or not.
  101. * g_AmbientLightColor: the color of the ambient light.
  102. These uniforms are passed to the shader without having to declare them in the j3md file, but you have to specify in the technique definition "`LightMode MultiPass`" see lighting.j3md for more information.
  103. === JME3 attributes
  104. Those are different attributes that are always passed to your shader.
  105. You can find a complete list of those attribute in the Type enum of the VertexBuffer in link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-core/src/main/java/com/jme3/scene/VertexBuffer.java[VertexBuffer.java].
  106. [NOTE]
  107. ====
  108. In the shader the attributes names will be prefixed by an "`in`".
  109. ====
  110. When the enumeration lists some usual types for each attribute (for example texCoord specifies two floats) then that is the format expected by all standard JME3 shaders that use that attribute. When writing your own shaders though you can use alternative formats such as placing three floats in texCoord simply by declaring the attribute as vec3 in the shader and passing 3 as the component count into the mesh setBuffer call.
  111. === User's uniforms
  112. At some point when making your own shader you'll need to pass your own uniforms.
  113. Any uniform has to be declared in the material definition file (.j3md) in the "`MaterialParameters`" section.
  114. [source,java]
  115. ----
  116. MaterialParameters {
  117. Vector4 Color
  118. Texture2D ColorMap
  119. }
  120. ----
  121. You can also pass some define to your vertex/fragment programs to know if an uniform as been declared.
  122. You simply add it in the Defines section of your Technique in the definition file.
  123. [source,java]
  124. ----
  125. Defines {
  126. COLORMAP : ColorMap
  127. }
  128. ----
  129. For integer and floating point parameters, the define will contain the value that was set.
  130. For all other types of parameters, the value 1 is defined.
  131. If no value is set for that parameter, the define is not declared in the shader.
  132. Those material parameters will be sent from the engine to the shader as follows,
  133. there are setXXXX methods for any type of uniform you want to pass.
  134. [source,java]
  135. ----
  136. material.setColor("Color", new ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f)); // red color
  137. material.setTexture("ColorMap", myTexture); // bind myTexture for that sampler uniform
  138. ----
  139. To use this uniform in the shader, you need to declare it in the .frag or .vert files (depending on where you need it).
  140. You can make use of the defines here and later in the code: *Note that the "`m_`" prefix specifies that the uniform is a material parameter.*
  141. [source,java]
  142. ----
  143. uniform vec4 m_Color;
  144. #ifdef COLORMAP
  145. uniform sampler2D m_ColorMap;
  146. #endif
  147. ----
  148. The uniforms will be populated at runtime with the value you sent.
  149. === Example: Adding Color Keying to the Lighting.j3md Material Definition
  150. Color Keying is useful in games involving many players. It consists of adding some player-specific color on models textures. The easiest way of doing this is to use a keyMap which will contain the amount of color to add in its alpha channel.
  151. We need to pass 2 new parameters to the Lighting.j3md definition, MaterialParameters section:
  152. [source,java]
  153. ----
  154. // Keying Map
  155. Texture2D KeyMap
  156. // Key Color
  157. Color KeyColor
  158. ----
  159. Below, add a new Define in the main Technique section:
  160. [source,java]
  161. ----
  162. KEYMAP : KeyMap
  163. ----
  164. In the Lighting.frag file, define the new uniforms:
  165. [source,java]
  166. ----
  167. #ifdef KEYMAP
  168. uniform sampler2D m_KeyMap;
  169. uniform vec4 m_KeyColor;
  170. #endif
  171. ----
  172. Further, when obtaining the diffuseColor from the DiffuseMap texture, check
  173. if we need to blend it:
  174. [source,java]
  175. ----
  176. #ifdef KEYMAP
  177. vec4 keyColor = texture2D(m_KeyMap, newTexCoord);
  178. diffuseColor.rgb = (1.0-keyColor.a) * diffuseColor.rgb + keyColor.a * m_KeyColor.rgb;
  179. #endif
  180. ----
  181. This way, a transparent pixel in the KeyMap texture doesn't modify the color. A black pixel replaces it for the m_KeyColor and values in between are blended.
  182. === Step by step
  183. * Create a vertex shader (.vert) file
  184. * Create a fragment shader (.frag) file
  185. * Create a material definition (j3md) file specifying the user defined uniforms, path to the shaders and the global uniforms to use
  186. * In your initSimpleApplication, create a material using this definition, apply it to a geometry
  187. * That’s it!!
  188. [source,java]
  189. ----
  190. // A cube
  191. Box box= new Box(Vector3f.ZERO, 1f,1f,1f);
  192. Geometry cube = new Geometry("box", box);
  193. Material mat = new Material(assetManager,"Path/To/My/materialDef.j3md");
  194. cube.setMaterial(mat);
  195. rootNode.attachChild(cube);
  196. ----
  197. === JME3 and OpenGL 3 & 4 compatibility
  198. GLSL 1.0 to 1.2 comes with built in attributes and uniforms (ie, gl_Vertex, gl_ModelViewMatrix, etc…). Those attributes are deprecated since GLSL 1.3 (opengl 3), hence JME3 global uniforms and attributes.
  199. Here is a list of deprecated attributes and their equivalent in JME3.
  200. [cols="2", options="header"]
  201. |===
  202. a|GLSL 1.2 attributes
  203. a|JME3 equivalent
  204. <a|gl_Vertex
  205. a|inPosition
  206. <a|gl_Normal
  207. a|inNormal
  208. <a|gl_Color
  209. a|inColor
  210. <a|gl_MultiTexCoord0
  211. a|inTexCoord
  212. <a|gl_ModelViewMatrix
  213. a|g_WorldViewMatrix
  214. <a|gl_ProjectionMatrix
  215. a|g_ProjectionMatrix
  216. <a|gl_ModelViewProjectionMatrix
  217. a|g_WorldViewProjectionMatrix
  218. <a|gl_NormalMatrix
  219. a|g_NormalMatrix
  220. |===
  221. === Useful links
  222. link:{attachmentsdir}/GLSL-ATI-Intro.pdf[GLSL-ATI-Intro.pdf]