nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
noise.cc
Go to the documentation of this file.
1#include "terrain/noise.h"
2
3#include <cmath>
4#include <cstdint>
5
6namespace nanommo {
7
8namespace {
9
10float Value(uint32_t seed, int32_t x, int32_t z) {
11 // The top 24 bits, as many as a float holds exactly.
12 return static_cast<float>(Hash(seed, x, z) >> 8) * (2.0f / 16777215.0f) -
13 1.0f;
14}
15
16float Smooth(float t) { return t * t * (3.0f - 2.0f * t); }
17
18float Mix(float a, float b, float t) { return a + (b - a) * t; }
19
20} // namespace
21
22uint32_t Hash(uint32_t seed, int32_t x, int32_t z) {
23 uint32_t hash = seed ^ (static_cast<uint32_t>(x) * 0x9E3779B1u) ^
24 (static_cast<uint32_t>(z) * 0x85EBCA77u);
25 // MurmurHash3's last step, which mixes each bit into all the others.
26 hash ^= hash >> 16;
27 hash *= 0x85EBCA6Bu;
28 hash ^= hash >> 13;
29 hash *= 0xC2B2AE35u;
30 hash ^= hash >> 16;
31 return hash;
32}
33
34float Noise(uint32_t seed, float x, float z) {
35 const float left = std::floor(x);
36 const float top = std::floor(z);
37 const auto i = static_cast<int32_t>(left);
38 const auto j = static_cast<int32_t>(top);
39 const float across = Smooth(x - left);
40 const float down = Smooth(z - top);
41 const float upper = Mix(Value(seed, i, j), Value(seed, i + 1, j), across);
42 const float lower =
43 Mix(Value(seed, i, j + 1), Value(seed, i + 1, j + 1), across);
44 return Mix(upper, lower, down);
45}
46
47float Fractal(uint32_t seed, float x, float z, int octaves) {
48 float sum = 0.0f;
49 float total = 0.0f;
50 float strength = 1.0f;
51 float scale = 1.0f;
52 for (int octave = 0; octave < octaves; ++octave) {
53 sum += strength * Noise(seed + octave, x * scale, z * scale);
54 total += strength;
55 strength *= 0.5f;
56 scale *= 2.0f;
57 }
58 return sum / total;
59}
60
61} // namespace nanommo
Definition chat.cc:9
float Fractal(uint32_t seed, float x, float z, int octaves)
Definition noise.cc:47
uint32_t Hash(uint32_t seed, int32_t x, int32_t z)
Definition noise.cc:22
float Noise(uint32_t seed, float x, float z)
Value noise: from -1 to 1, random at whole numbers, and smooth between them.
Definition noise.cc:34
void Mix(Samples &mix, const Samples &sound, float at, float gain)
Definition synth.cc:69