c# - 用于噪声生成的散列函数
问题描述
我正在制作价值噪声生成器,我发现我当前的哈希在图像中产生了一种模式:
所以我正在寻找一个更好的哈希函数,不可预测/可重复。
我使用哈希而不是随机数,因为我希望它是确定性的。给定一个 (x, y) 坐标,它应该总是产生相同的结果。
如果可以扩展散列函数以轻松接受更多参数,例如 (x, y, z) 或 (x, y, z, t),而不仅仅是两个,这也很好,但不是强制性的。
我当前的哈希是:
public static class Hash
{
public static float GetHash(int x)
{
x = x ^ 61 ^ (x >> 16);
x += x << 3;
x ^= x >> 4;
x *= 0x27d4eb2d;
x ^= x >> 15;
return x / (float)int.MaxValue;
}
public static float GetHash(int x, int y) => GetHash((y << 8) + x);
}
我添加了这一行x / (float)int.MaxValue
,因为我想要一个从 0 到 1 的浮点结果。
但我必须承认我只是从某个地方复制粘贴它。按位运算(和哈希)不是我的强项。
解决方案
原始答案:我会使用像https://github.com/Auburns/FastNoise_CSharp这样的库 也许您可以从该 FastNoise.cs 文件中的源代码中学习
修改后的答案,包括来自参考来源“Copyright(c) 2017 Jordan Peck”的代码、散列函数
private const int X_PRIME = 1619;
private const int Y_PRIME = 31337;
private const int Z_PRIME = 6971;
private const int W_PRIME = 1013;
private static int Hash2D(int seed, int x, int y)
{
int hash = seed;
hash ^= X_PRIME * x;
hash ^= Y_PRIME * y;
hash = hash * hash * hash * 60493;
hash = (hash >> 13) ^ hash;
return hash;
}
private static int Hash3D(int seed, int x, int y, int z)
{
int hash = seed;
hash ^= X_PRIME * x;
hash ^= Y_PRIME * y;
hash ^= Z_PRIME * z;
hash = hash * hash * hash * 60493;
hash = (hash >> 13) ^ hash;
return hash;
}
private static int Hash4D(int seed, int x, int y, int z, int w)
{
int hash = seed;
hash ^= X_PRIME * x;
hash ^= Y_PRIME * y;
hash ^= Z_PRIME * z;
hash ^= W_PRIME * w;
hash = hash * hash * hash * 60493;
hash = (hash >> 13) ^ hash;
return hash;
}
推荐阅读
- javascript - 使用 Vue 在 p 标签内渲染 HTML
- webhooks - 在 IFTTT 中发送和接收事件/通知
- python - 在 Windows 终端 Python 中打印表情符号
- c# - 如何编写将 DBNull 值转换为 Nullable 的通用方法?
- javascript - @firebase/database:无法确定 Firebase 数据库 URL。请务必在调用 firebase.initializeApp() 时包含项目 ID。角
- python - Python根据列表中的条件更改字符串的一部分
- javascript - 如何根据 HTML 输出清除 CSS?
- flutter - 如何限制任何人在颤振中使用谷歌登录进行登录?
- go - 如何将类型值传递给类型为 reflect.Type Golang 的变量
- java - Kafka 的 SSL 属性的动态更新不起作用