title: OpenGL Shader Storage Buffer / memoryBarrierBuffer
body: <p>I currently created two SSBO's to handle some lights because the VS-FS <code>in</code> <code>out</code> interface can't handle a lot of lights (Im using forward shading).
  For the first one I only pass the values to the shader (basically a read only one) [cpp]:</p>
  
  <pre><code>struct GLightProperties
  {
      unsigned int numLights;
      LightProperties properties[];
  };
  
  ...
  
  glp = (GLightProperties*)malloc(sizeof(GLightProperties) + sizeof(LightProperties) * lastSize);
  
  ...
  
  glGenBuffers(1, &amp;ssbo);
  glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
  glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GLightProperties) + sizeof(LightProperties) * lastSize, glp, GL_DYNAMIC_COPY);
  glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, ssbo);
  glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  </code></pre>
  
  <p>Shader file [GLSL]:</p>
  
  <pre><code>layout(std430, binding = 1) buffer Lights
  {
      uint numLights;
      LightProperties properties[];
  }lights;
  </code></pre>
  
  <p>So this first SSBO turns out to work fine. However, in the other one, which purpose is VS-FS interface, has some issues:</p>
  
  <pre><code>glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo2);
  glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(float) * 4 * 3 * lastSize, nullptr, GL_DYNAMIC_COPY);
  glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  </code></pre>
  
  <p>GLSL:</p>
  
  <pre><code>struct TangentProperties
  {
      vec4 TangentLightPos;
      vec4 TangentViewPos;
      vec4 TangentFragPos;
  };
  
  layout(std430, binding = 0) buffer TangentSpace
  {
      TangentProperties tangentProperties[];
  }tspace;
  </code></pre>
  
  <p>So here you notice I pass <code>nullptr</code> to the <code>glBufferData</code> because the vs will write in the buffer and the fs will read its contents.
  Like so in the VS Stage:</p>
  
  <pre><code>for(int i = 0; i &lt; lights.numLights; i++)
  {
      tspace.tangentProperties[index].TangentLightPos.xyz = TBN * lights.properties[index].lightPosition.xyz;
      tspace.tangentProperties[index].TangentViewPos.xyz  = TBN * camPos;
      tspace.tangentProperties[index].TangentFragPos.xyz  = TBN * vec3(worldPosition);
      memoryBarrierBuffer();
  }
  </code></pre>
  
  <p>After this the FS reads the values, which turn out to be just garbage. Am I doing something wrong with memory barriers?</p>
  
  <p>The output turns out this way:
  <a href="https://i.stack.imgur.com/5Z68n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Z68n.png" alt="Pixels bugging"></a></p>