# OpenGL GLSL modulo strange behavior with negative number

This topic is 944 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello everyone, I have been having an issue with the modulo implementation in GLSL

I'm running version 4.5 Core and have the following problem:

Even though mod is defined as

x - y * floor(x/y)

(source: https://www.opengl.org/sdk/docs/man4/html/mod.xhtml) which, when you plot it for y = 3, looks like this:

http://fooplot.com/#W3sidHlwZSI6MCwiZXEiOiJ4LTMqZmxvb3IoeC8zKSIsImNvbG9yIjoiIzAwMDAwMCJ9LHsidHlwZSI6MTAwMH1d

I am running into an issue where the result of -1 % 3 is apparently not within the domain [0, 2].

To be precise, the reduced code causing the error message is this:

vec3 barycentric;
vec3 barycentric_verts_sequence[3] = vec3[](vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
barycentric = barycentric_verts_sequence[-1 % 3];

The error reads: error C1068: array index out of bounds.

If shaders were easily debuggable, I probably wouldn't be asking this question, but since there's no way to step through the shader code while it's running, I was hoping that someone more experienced with GLSL could help me out!

Marvin

##### Share on other sites

Looking at the GLSL spec, it doesn't seem to specify how operator% should be implemented... which means that behavior for negative inputs could well be implementation defined -- either using the floor definition, or the truncation definition which rounds towards zero instead of rounding towards negative infinity.

##### Share on other sites

Could you do something like

while (n < 0)
n += 3;


before using %?

##### Share on other sites

Yeah, that must be it, thanks kolrabi!

Guess I'll only use modulo with positives from now on...

1. 1
2. 2
3. 3
Rutin
18
4. 4
5. 5
JoeJ
13

• 9
• 14
• 10
• 25
• 9
• ### Forum Statistics

• Total Topics
632644
• Total Posts
3007625
• ### Who's Online (See full list)

There are no registered users currently online

×