Skip to content

Commit d198e42

Browse files
committedNov 1, 2015
Fix Noise compiled under clang >= 3.7.x with -O2 or higher
When compiled with optimizations, the most recent versions of clang seem to 'optimize' out a crucial "and %reg, 0x7FFFFFFF" instruction in noise2d(), probably because it somehow assumed the variable n would never become greater than that amount. Indeed, signed integer underflow is undefined behavior in C and C++, so while this optimization is "correct" in that sense, it breaks lots of existing code. Solved by changing n to an unsigned type, making behavior well-defined.
1 parent 9269a0e commit d198e42

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed
 

‎src/noise.cpp

+4-4
Original file line numberDiff line numberDiff line change
@@ -158,21 +158,21 @@ s32 PcgRandom::randNormalDist(s32 min, s32 max, int num_trials)
158158

159159
float noise2d(int x, int y, int seed)
160160
{
161-
int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y
161+
unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y
162162
+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
163163
n = (n >> 13) ^ n;
164164
n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
165-
return 1.f - (float)n / 0x40000000;
165+
return 1.f - (float)(int)n / 0x40000000;
166166
}
167167

168168

169169
float noise3d(int x, int y, int z, int seed)
170170
{
171-
int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z
171+
unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z
172172
+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
173173
n = (n >> 13) ^ n;
174174
n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
175-
return 1.f - (float)n / 0x40000000;
175+
return 1.f - (float)(int)n / 0x40000000;
176176
}
177177

178178

0 commit comments

Comments
 (0)
Please sign in to comment.