add: seed option in perlinNoise constructor

This commit is contained in:
loic 2024-12-14 01:45:58 +01:00
parent c882cbf80e
commit eeefa48a78
2 changed files with 17 additions and 15 deletions

View file

@ -7,9 +7,11 @@
class PerlinNoise {
public:
PerlinNoise();
PerlinNoise(int seed);
float noise(float x, float y);
private:
int seed;
void initializeGradients();
Vector2 grad[512];
Vector2 randoGradient(int ix, int iy);

View file

@ -6,12 +6,16 @@
PerlinNoise::PerlinNoise() {
PerlinNoise::PerlinNoise() : seed(0) {
initializeGradients();
}
PerlinNoise::PerlinNoise(int seed) : seed(seed) {
initializeGradients();
}
void PerlinNoise::initializeGradients() {
std::mt19937 gen(512);
std::mt19937 gen(seed);
std::uniform_real_distribution<float> dis(0.0, 2 * M_PI);
for (int i = 0; i < 512; ++i) {
@ -22,14 +26,13 @@ void PerlinNoise::initializeGradients() {
Vector2 PerlinNoise::randoGradient(int ix, int iy) {
uint32_t hash = ix * 7385451 ^ iy * 19349663;
return grad[hash & 0xFF];
return grad[hash & 512];
}
float PerlinNoise::dotGridGradient(int ix, int iy, float x, float y) {
Vector2 gradient = randoGradient(ix, iy);
float dx = x - (float)ix;
float dy = y - (float)iy;
return dx * gradient.getX() + dy * gradient.getY();
Vector2 d(x - (float)ix, y - (float)iy);
return d.getX() * gradient.getX() + d.getY() * gradient.getY();
}
float PerlinNoise::interpolate(float a, float a1, float w) {
@ -42,16 +45,13 @@ float PerlinNoise::noise(float x, float y) {
int x1 = x0 + 1;
int y1 = y0 + 1;
float sx = x - (float)x0;
float sy = y - (float)y0;
Vector2 s(x - (float)x0, y - (float)y0);
Vector2 n(dotGridGradient(x0, y0, x, y), dotGridGradient(x1, y0, x, y));
float n0 = dotGridGradient(x0, y0, x, y);
float n1 = dotGridGradient(x1, y0, x, y);
float ix0 = interpolate(n0, n1, sx);
float ix0 = interpolate(n.getX(), n.getY(), s.getX());
n0 = dotGridGradient(x0, y1, x, y);
n1 = dotGridGradient(x1, y1, x, y);
float ix1 = interpolate(n0, n1, sx);
n = Vector2(dotGridGradient(x0, y1, x, y), dotGridGradient(x1, y1, x, y));
float ix1 = interpolate(n.getX(), n.getY(), s.getX());
return interpolate(ix0, ix1, sy);
return interpolate(ix0, ix1, s.getY());
}