title: Get accurate integer modulo in WebGL shader
body: <p>I want to get an accurate modulo of <code>x</code> and <code>y</code> in a WebGL fragment shader. <code>x</code> and <code>y</code> are integers.</p>
  
  <p>Graphing <code>mod(x,y)</code>, we get the following:
  <a href="https://i.stack.imgur.com/V10Ge.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V10Ge.png" alt="a choppy, irregular chart"></a></p>
  
  <p>The actual code used to generate the red-and-black rectangle is:</p>
  
  <pre><code>gl_FragColor = vec4(mod(
    float(int(v_texCoord[0]*15.))/15.,
    float(int(v_texCoord[1]*15.))/15.
  ), 0, 0, 1);
  </code></pre>
  
  <p>Where v_texCoord is a vec2 ranging from <code>0,0</code> at the top-left to <code>1,1</code> at the bottom-right. Precision is set to mediump for both float and int.</p>
  
  <p>Reading the chart, we see that although <code>mod(6,6)</code> is correctly <code>0</code>, <code>mod(7,7)</code> is actually <code>7</code>! <strong>How do I fix this?</strong></p>
  
  <p>I tried to implement my own mod() function. However, it has the same errors, and produces the same graph.</p>
  
  <pre><code>int func_mod(int x, int y) {
      return int(float(x)-float(y)*floor(float(x)/float(y)));
  }
  </code></pre>
  
  <p>In Javascript, where I can debug it, the function works perfectly. I then tried an iterative approach, because I was worried I was going insane and I didn't trust the floating-point division anyway.</p>
  
  <pre><code>int iter_mod(int x, int y) {
      x = int(abs(float(x))); y = int(abs(float(y)));
      for(int i=0; i&gt;-1; i++) {
          if(x &lt; y) break;
          x = x - y;
      }
      return x;
  }
  </code></pre>
  
  <p>This worked, but I can't graph it because it crashes linux with an error in ring 0 when I try. It works fine for the spritesheet calculations I need it for, but I really feel it's an incorrect solution.</p>
  
  <p>(Update: It works perfectly on my phone. It's not my code in error now, it's just my problem…)</p>