Page 1 of 1

### GLSL Math

Posted: Fri Aug 30, 2013 4:13 pm
Could someone provide GLSL logic?
Why doesn't:

Code: Select all

``````a - ((a / b) * b)
``````
equal zero?
see line 17 of grid.lua shader.

### Re: GLSL Math

Posted: Fri Aug 30, 2013 4:29 pm
Simple: foating point math has some degree of error, and it tends to accumulate along the computations.

### Re: GLSL Math

Posted: Sat Aug 31, 2013 12:48 pm
Raidho is wrong, as usual.

On the serious note. Your function signature is :

Code: Select all

``int mod(int a, int b) { return a - ((a / b) * b); }``
GLSL acts like the C language.
In C,C++, Java (that's the languages I have observed with this behaviour) an int divided by int ALWAYS return an integer.

4/3 = 1 (not 1.(3) ). That has to do with type casting. If both arguments are integers none gets promoted to a float or double, hence the return value is an integer aswell.

### Re: GLSL Math

Posted: Sat Aug 31, 2013 1:08 pm
Previous statement wasn't wrong, just not exactly related. When people are talking about GLSL, it is assumed that any numbers are floats, so did I.

It is true that integer division always results in integer result rounded down. You can cast values at any time by prefixing them with desired cast type (or use function-like syntax):

Code: Select all

``````float myfloat = (float)myint
float myfloat = float(myint)
float mod ( int a, int b ) { return (float)a - ( ( (float)a / (float)b ) * (float)b ); }``````
Last line is what you should probably use. You can omit some of the explicit typecasts, but that only would result in implicit typecast. Implicit things may not work the way you expect it, and it's side-effects could be evil, so make sure you avoid it.

### Re: GLSL Math

Posted: Sat Aug 31, 2013 1:13 pm
Also, if I remember correctly some video cards just hate implicit casts and won't compile any shader that uses them

### Re: GLSL Math

Posted: Sat Aug 31, 2013 1:21 pm
Even more unrelated, GLSL already defines a modulo function, see here.

### Re: GLSL Math

Posted: Sat Aug 31, 2013 1:26 pm
Nixola wrote:Also, if I remember correctly some video cards just hate implicit casts and won't compile any shader that uses them
Quite the opposite. A lot of ATI drivers require implcit casting as they are often reluctant to cast on their own.

@Vrld
Just my thought

### Re: GLSL Math

Posted: Sat Aug 31, 2013 1:46 pm
RedHot wrote:A lot of ATI drivers require implcit casting as they are often reluctant to cast on their own.
Aren't you confusing "implicit" with "explicit" there?

### Re: GLSL Math

Posted: Sat Aug 31, 2013 2:01 pm
Robin wrote:
RedHot wrote:A lot of ATI drivers require implcit casting as they are often reluctant to cast on their own.
Aren't you confusing "implicit" with "explicit" there?
I most certainly am! My bad. Robin is of course right. Dunno why I confused the two.

### Re: GLSL Math

Posted: Sat Aug 31, 2013 10:12 pm
``float mod ( int a, int b ) { return (float)a - ( ( (float)a / (float)b ) * (float)b ); }``