/
std_library_noise.cmajor
127 lines (110 loc) · 3.53 KB
/
std_library_noise.cmajor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//
// ,ad888ba, 88
// d8"' "8b
// d8 88,dba,,adba, ,aPP8A.A8 88 The Cmajor Standard Library
// Y8, 88 88 88 88 88 88
// Y8a. .a8P 88 88 88 88, ,88 88 (C)2024 Cmajor Software Ltd
// '"Y888Y"' 88 88 88 '"8bbP"Y8 88 https://cmajor.dev
// ,88
// 888P"
//
// The Cmajor standard library may be used under the terms of the ISC license:
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or
// without fee is hereby granted, provided that the above copyright notice and this permission
// notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/// std.noise
/**
These processors can be used to generate various flavours of noise.
*/
namespace std::noise
{
/// Simple white noise generator.
/// See https://en.wikipedia.org/wiki/White_noise
processor White
{
output stream float32 out;
std::random::RNG rng;
void init()
{
rng.seed (201L + processor.id);
}
void main()
{
loop
{
out <- rng.getBipolar();
advance();
}
}
}
/// Brown (a.k.a. Brownian) noise generator.
/// See https://en.wikipedia.org/wiki/Brownian_noise
processor Brown
{
output stream float32 out;
std::random::RNG rng;
float32 lastLevel;
let filter = 0.998f;
let scale = 32.0f;
void init()
{
rng.seed (301L + processor.id);
}
void main()
{
loop
{
let next = rng.getBipolar();
var level = lastLevel + next;
if (level < -scale || level > scale)
level -= next;
level *= filter;
lastLevel = level;
out <- (1.0f / scale) * level;
advance();
}
}
}
/// Pink noise generator
/// See https://en.wikipedia.org/wiki/Pink_noise
processor Pink
{
output stream float32 out;
std::random::RNG rng;
float[12] values;
int32 sampleCount;
float32 lastLevel;
void init()
{
rng.seed (401L + processor.id);
}
void main()
{
loop
{
let next = rng.getBipolar();
let count = ++sampleCount;
var level = lastLevel;
for (wrap<values.size> i)
{
if (((count >> i) & 1) != 0)
{
level -= values[i];
values[i] = next;
level += next;
break;
}
}
lastLevel = level;
out <- (1.0f / float32 (values.size - 1)) * level;
advance();
}
}
}
}