0

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

BlobKat
  • 88
  • 1
  • 8

1 Answers1

0

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.

Andrea
  • 19,134
  • 4
  • 43
  • 65
  • How does out and in work with function parameters? Does it pass a reference instead of copying? Can it be used with arrays? – BlobKat Oct 08 '22 at 13:44
  • `in` is the default behaviour you're used to. `out` means that instead of passing a value into the function, it passes a value out, so it's like an extra return value. `inout` is like `out` but it first copies the value passed in, it's kinda similar in concept to a reference in C++. It can be used with arrays, though I'm not sure what the performance is like. – Andrea Oct 08 '22 at 13:58