Check int multiplication overflow in GLSL

243 views Asked by At

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

1

There are 1 answers

2
mystery On BEST ANSWER

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:

  • Halve the sizes of things: instead of 64-bit types, use 32-bit types; halve the shift constants; instead of casting from 64-bit to 32-bit ((uint32_t)), convert from 32-bit to 16-bit using & 0xffff.
  • Make it valid GLSL 3.0 (e.g. use out instead of &, and uint instead of uint32_t)

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.