glslregl

Glsl error when trying to increment a variable inside a for loop


Context : I pass a uniform array of float to my fragment shader, then initialize a float with a value from this array, and finally try to increment this float in for loop, with this code :

var regl = createREGL()

var drawTriangle = regl({
  vert: `
  precision mediump float;
  attribute vec2 position;

  void main () {
    gl_Position = vec4(position, 0, 1);
  }
  `,

  frag: `
  precision mediump float;
  uniform float refPoints[3];
  varying vec3 fcolor;

  void main () {
    float a_value = refPoints[1];
    for(int i=0;i<3;++i) {
      a_value += 1.; // <-- this line is causing the error
    }
    gl_FragColor = vec4(1, 1, 1, 1);
  }
  `,
  attributes: {
    position: [
      [1, 0],
      [0, 1],
      [-1, -1]
    ],
  },
  uniforms : {
    refPoints : [0., 1., 0., 2.]
  },
  count: 3
})

regl.frame(function () {
  regl.clear({
    color: [0, 0, 0, 1],
    depth: 1
  })
  drawTriangle()
})
<script src="https://npmcdn.com/regl/dist/regl.js"></script>

I am having a weird error :

Error: (regl) bad data or missing for uniform "refPoints[0]".  invalid type, expected number in command unknown

I don't understand why this increment in this particular loop is causing so much trouble. Do you have any ideas ?


Solution

  • AFAICT it's a bug in regl? It works if you use

        uniforms: { 
          "refPoints[0]": 0.,
          "refPoints[1]": 1.,
          "refPoints[2]": 0.,
        }
    

    var regl = createREGL()
    
    var drawTriangle = regl({
      vert: `
      precision mediump float;
      attribute vec2 position;
    
      void main () {
        gl_Position = vec4(position, 0, 1);
      }
      `,
    
      frag: `
      precision mediump float;
      uniform float refPoints[3];
      varying vec3 fcolor;
    
      void main () {
        float a_value = refPoints[1];
        for(int i=0;i<3;++i) {
          a_value += 1.; // <-- this line is causing the error
        }
        gl_FragColor = vec4(1, 1, 1, 1);
      }
      `,
      attributes: {
        position: [
          [1, 0],
          [0, 1],
          [-1, -1]
        ],
      },
      uniforms : {
        "refPoints[0]" : 0.,
        "refPoints[1]" : 1.,
        "refPoints[2]" : 0.,
      },
      count: 3
    })
    
    regl.frame(function () {
      regl.clear({
        color: [0, 0, 0, 1],
        depth: 1
      })
      drawTriangle()
    })
    <script src="https://npmcdn.com/regl/dist/regl.js"></script>