Swift中的Perlin噪声发生器 [英] Perlin noise generator in Swift

查看:130
本文介绍了Swift中的Perlin噪声发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码用于在obj-c中生成1D噪声,它运行得非常好:

I have this code for generating 1D noise in obj-c, it's working perfectly well:

- (float)makeNoise1D:(int)x {
    x = (x >> 13) ^ x;
    x = (x * (x * x * (int)_seed + 19990303) + 1376312589) & RAND_MAX;
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & RAND_MAX) / 1073741824.0);
}

现在我试图在Swift中重现它,但它总是失败,返回时显示EXEC_BAD_INSTRUCTION。这就是它现在的样子,我不得不吐出最后的表达,但我很确定这不是问题。

Now I'm trying to reproduce it in Swift, but it always fail and shows EXEC_BAD_INSTRUCTION on return. This is how it looks like now, I had to spit the final expression, but I'm pretty sure that's not the problem.

func makeNoise1D(var x : Int) -> Float{
    x = (x >> 13) ^ x;
    x = (x * (x * x * seed! + 19990303) + 1376312589) & 0x7fffffff
    var inner = (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff
    return ( 1.0 - ( Float(inner) ) / 1073741824.0)
}

我已经尝试了很多不同的演员表并分成子表达式,但仍然失败了。我唯一能想到的是第一行和最后一行。
(我的大部分测试用例x都设置为20,种子为10,只是为了简化)

I've already tried out many different casts and splitting into sub expressions, but still fails. The only thing I've figured out that the first and the last line works. (Most of my test cases x was set to 20 and seed to 10, just to make it simple)

感谢您的帮助!

推荐答案

异常是由于计算结果的
结果无法表示为算术溢出引起的code> Int 。

The exception is caused by an "arithmetic overflow" that occurs if the result of one your calculations cannot be represented as an Int.

与(Objective-)C不同,在Swift中添加和乘以整数不会环绕
或truncate,但如果结果不适合数据类型,则会导致错误。

Unlike (Objective-)C, adding and multiplying integers in Swift does not "wrap around" or "truncate", but causes an error if the result does not fit into the data type.

但是你可以使用Swift 溢出运算符 & * & + 相反,它总是截断结果:

But you can use the Swift "overflow operators" &* and &+ instead, which always truncate the result:

func makeNoise1D(x : Int) -> Float{
    var x = x
    x = (x >> 13) ^ x;
    x = (x &* (x &* x &* seed! &+ 19990303) &+ 1376312589) & 0x7fffffff
    let inner = (x &* (x &* x &* 15731 &+ 789221) &+ 1376312589) & 0x7fffffff
    return ( 1.0 - ( Float(inner) ) / 1073741824.0)
}

这篇关于Swift中的Perlin噪声发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆