glslwebgl2glsles

Check int multiplication overflow in GLSL


I know that in C or C++, you can see how much a multiplication overflowed by using a long E.g

int[] multiply(int a, int b){
  long long r = a * b;
  int result = r;
  int overflow = r >> 32;
  return {result, overflow};
}

However, in GLSL, there are no 64 bit integers. Is there a way to achieve the same result in GLSL without longs?

Context: GLSL 3.0, running in my browser via WebGL 2


Solution

  • You would have to break up the multiplication into pieces yourself.

    Here is an algorithm that tries to do this for 64-bit multiplication: https://stackoverflow.com/a/51587262/736162

    The same principles apply to 32-bit. You would need to change the code in a few ways:

    I haven't tested this, but I think it should work.

    By the way, you'll want to be sure you have highp precision on everything. precision highp int; at the top of your shader is enough.