README: document nit_env.sh
[nit.git] / lib / noise.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Noise generators `PerlinNoise` and `InterpolatedNoise`
16 module noise is serialize
17
18 import serialization
19
20 # 2D noise generator
21 abstract class Noise
22
23 # Get the noise value at `x`, `y`
24 #
25 # The coordinates `x`, `y` can be floats of any size.
26 #
27 # Returns a value between or equal to `min` and `max`.
28 fun [](x, y: Float): Float is abstract
29
30 # Lowest possible value returned by `[]`
31 #
32 # Default at `0.0`.
33 #
34 # Require: `min < max`
35 var min = 0.0 is writable
36
37 # Highest possible value returned by `[]`
38 #
39 # Default at `1.0`.
40 #
41 # Require: `min < max`
42 var max = 1.0 is writable
43
44 # Distance between reference points of the noise
45 #
46 # Higher values will result in smoother noise and
47 # lower values will result in steeper curves.
48 #
49 # Default at `1.0`.
50 var period = 1.0 is writable
51
52 # Amplitude of the values returned by `[]`
53 fun amplitude: Float do return max - min
54
55 # Set the desired amplitude of the values returned by `[]`
56 #
57 # Will only modify `max`, `min` stays the same.
58 fun amplitude=(value: Float) do max = min + value
59
60 # Frequency of this noise
61 fun frequency: Float do return 1.0/period
62
63 # Set the frequency if this noise
64 fun frequency=(value: Float) do period = 1.0/value
65
66 # Seed to the random number generator `gradient_vector`
67 #
68 # By default, `seed` has a random value created with `Int::rand`.
69 var seed: Int = 19511359.rand is lazy, writable
70 end
71
72 # 2D Perlin noise generator using layered `InterpolatedNoise`
73 #
74 # Get values at any coordinates with `[]`.
75 # The behavior of this generator can be customized using its attributes `min`,
76 # `max`, `period` and `seed`.
77 #
78 # This noise is more realistic and less smooth than the `InterpolatedNoise`.
79 #
80 # Due to implementation logic, the full amplitude cannot be reached.
81 # In practice, only `amplitude * (1.0 - 1.0 / n_levels)` is covered.
82 #
83 # This implementation uses a custom deterministic pseudo random number
84 # generator to set `InterpolatedNoise::seed` of the `layers`.
85 # It is seeded with the local `seed` and can be further customized by
86 # redefining `pseudo_random`.
87 # This process do not require any state, so this class only holds the
88 # attributes of the generator and does not keep any generated data.
89 #
90 # ## Usage example
91 #
92 # ~~~
93 # var map = new PerlinNoise
94 # map.min = 0.0
95 # map.max = 16.0
96 # map.period = 20.0
97 # map.seed = 0
98 #
99 # var max = 0.0
100 # var min = 100.0
101 # for y in 30.times do
102 # for x in 70.times do
103 # # Get a value at x, y
104 # var val = map[x.to_f, y.to_f]
105 # printn val.to_i.to_hex
106 #
107 # max = max.max(val)
108 # min = min.min(val)
109 # end
110 # print ""
111 # end
112 # assert max <= map.max
113 # assert min >= map.min
114 # ~~~
115 #
116 # ## Result at seed == 0
117 #
118 # ~~~raw
119 # 76666555444322234567789abbcbbaabbaa98777766665665566667888987655444444
120 # 776665554443322234567789abbbbbbbbba98777766666665556666788998654444444
121 # 777766544443322234566789abbbbbbbbaa99877777776665556666788888655444444
122 # 777776444443322244556679abbbccbbbaa99877777776655556666688888655444444
123 # 777766444444332244555678abbbccbbbaa99887787877655556666678888654444444
124 # 8887654344443333444456789abcccbbaa999877888886555555666688777654444455
125 # 8887654344443333444456789abbcdcbaa999887889887655555566677777654444456
126 # 7876654434444444444456778abbcccaaa999888899888655555566677777654444556
127 # 78765544344445544444567789bbccca99999888899988765555566666667654445566
128 # 77765444344455554445567889bbccba99999998999988765555566555666654445667
129 # 7765444334555665445556788abbbba988998999999988765555566545556554456677
130 # 87654444334556655455567899bbbba998888899999887766555566544556555456777
131 # 87655444334566665555567899bbbbba98888899988888776555566544556555556777
132 # 97655544334566665555567899abbbba98888899988888776555655544456555667777
133 # 97655544444566665556667899aaaaba98888999877777776555555444456666667777
134 # 866555444456666666566789999aaaaa98889998877777766556544443456667777777
135 # 976555445556776666666789aa99aaaa98889998876777666555544444456677887777
136 # 9765554556667777776667899999aaaa98889988876676666555443444446678888888
137 # 87655555666777788766678999899aaa99889988776666666554433344446789998888
138 # 876555566777788888766889998899a999889987776666666543333334456899a99899
139 # 766556677877889998877888888889a99998888777666666653222233345799aaa999a
140 # 6665556777777899998878988888899999999887777656666543222233446899aa999a
141 # 6655456777777899999888988888889999a988887776566666532222233457899a999a
142 # 665555677777789999998998888878899aa9888887765666655322222234578899aa9a
143 # 665555677777789999a98888888877899aa9888887766666655322222234467899aa9a
144 # 65666677667778999aaa988878877789aaa9888887776676654322222344467889aa9a
145 # 55566677767788899aaa987777777789aaa9888887776666654322222344567889aaa9
146 # 5566767777788889aaaa987777777789aaaa988887777666555432122344556899aaa9
147 # 5567777777788889aaaa977777777789aaaa99888777766555543212234555689aaaaa
148 # 5667877777889989aaa9876677777889aaaa99888777765554443212334555689aaaaa
149 # ~~~
150 class PerlinNoise
151 super Noise
152
153 # Desired number of `layers`
154 #
155 # This attribute must be assigned before any call to `layers` or `[]`.
156 #
157 # By default, it is the highest integer under the logarithm base 2
158 # of `amplitude`, or 4, whichever is the highest.
159 var n_layers: Int = 4.max(amplitude.abs.log_base(2.0).to_i) is lazy, writable
160
161 # Layers of `InterpolatedNoise` composing `self`
162 var layers: Array[InterpolatedNoise] is lazy do
163 var layers = new Array[InterpolatedNoise]
164
165 var max = max
166 var min = min
167 var period = period
168 var seed = seed
169 for l in n_layers.times do
170 min = min / 2.0
171 max = max / 2.0
172 seed = pseudo_random(seed)
173
174 var layer = new InterpolatedNoise
175 layer.min = min
176 layer.max = max
177 layer.period = period
178 layer.seed = seed
179 layers.add layer
180
181 period = period / 2.0
182 end
183 return layers
184 end
185
186 redef fun [](x, y)
187 do
188 var val = 0.0
189 for layer in layers do
190 val += layer[x, y]
191 end
192 return val
193 end
194
195 # Deterministic pseudo random number generator
196 #
197 # Used to get seeds for layers from the previous layers or `seed`.
198 protected fun pseudo_random(value: Int): Int
199 do
200 return (value * 3537391).mask % 1291377
201 end
202 end
203
204 # Simple interpolated noise
205 #
206 # Generates smoother noise than `PerlinNoise`.
207 #
208 # Each coordinates at a multiple of `period` defines a random vector and
209 # values in between are interpolated from these vectors.
210 #
211 # This implementation uses a custom deterministic pseudo random number
212 # generator seeded with `seed`.
213 # It can be further customized by redefining `gradient_vector`.
214 # This process do not require any state, so this class only holds the
215 # attributes of the generator and does not keep any generated data.
216 #
217 # ## Usage example
218 #
219 # ~~~
220 # var map = new InterpolatedNoise
221 # map.min = 0.0
222 # map.max = 16.0
223 # map.period = 20.0
224 # map.seed = 0
225 #
226 # var max = 0.0
227 # var min = 100.0
228 # for y in 30.times do
229 # for x in 70.times do
230 # # Get a value at x, y
231 # var val = map[x.to_f, y.to_f]
232 # printn val.to_i.to_hex
233 #
234 # max = max.max(val)
235 # min = min.min(val)
236 # end
237 # print ""
238 # end
239 # assert max <= map.max
240 # assert min >= map.min
241 # ~~~
242 #
243 # ## Result at seed == 0
244 #
245 # ~~~raw
246 # 89abcddeeeeeeeddcba9877666555555555666778766555544444555566789abcddeee
247 # 789abcddeeeeeeddccba887766655555555566677766555544444555566779abcddeee
248 # 689abcddeeeeeeeddcba988776655555555555667666555554455555566778abccdeee
249 # 678abccdeeeeeeeedccba988766655555555555666655555555555556666789abcddee
250 # 5789abcddeeeeeeeddcba998776655544444555666655555555555556666789abcddee
251 # 5689abcddeeeeeeeedccba98776655544444455566555555555555566666789abccdde
252 # 4679abccdeeeffeeeddcba98776655444444445565555555555555666666789abbcddd
253 # 4678abccdeeeffeeeedcba98876555444444444555555555566666666666689aabccdd
254 # 46789abcdeeeeffeeedccb988765544443344445555566666666666666666789abccdd
255 # 45789abcddeeeffeeeddcb987765544433334445555666666666666666666789abbccd
256 # 45789abcddeeeeeeeeddcb987665444333333445556666666777777777766789aabccc
257 # 45789abcddeeeeeeeeddca987655443333333445566666777777777777776789aabbcc
258 # 45789abcddeeeeeeeedcca9876544333333333455666777777788877777767899aabbc
259 # 46789abcddeeeeeeeddcba9876544333222333455667777888888888877767899aabbb
260 # 46789abcdddeeeeedddcba87655433222223334566777888889998888877778899aabb
261 # 5678aabcdddeeeedddccb987654332222222334566778889999999998887778899aaab
262 # 5689abbcddddeedddccba9865443222222223345677889999aaaa99998877788999aaa
263 # 6789abbcddddddddccbba8765432221111223345678899aaaaaaaaaa9988778889999a
264 # 6789abccdddddddccbba9865433221111122344577899aabbbbbbbaaa9987788889999
265 # 789abbccddddddccbba9876543211111111234567899aabbbccccbbbaa987788888899
266 # 889abbccdddddccbba9886543211000001123456889abbcccccccccbba988888888888
267 # 899abbcccddddcccbaa9875432211000011223457899abbcccccccccbba98888888888
268 # 899abbccccddccccbba9876533211000001123456789aabccccddcccbbaa9998888888
269 # 899abbccccccccccbbaa9765432111000011223456899abbcccdddcccbba9999988888
270 # 899abbbcccccccccbbaa9865432211000011123456789abbccdddddcccbba999988888
271 # 899aabbcccccccccbbaa9875433211100001122346789abbccddddddcccbaa99988888
272 # 899aabbbcccccccbbbbaa876543211100001122345689aabccdddddddccbaaa9988887
273 # 899aabbbbbbccbbbbbbaa876543221110001112335679aabccddddddddcbbaa9988877
274 # 899aaabbbbbbbbbbbbbaa9765433211111111123356789abccddddddddccbaa9988777
275 # 8999aaaabbbbbbbbbbaaa9765433221111111122356789abccdddeedddccbaa9988777
276 # ~~~
277 class InterpolatedNoise
278 super Noise
279
280 redef fun [](x, y)
281 do
282 x = x/period
283 y = y/period
284
285 # Get grid coordinates
286 var x0 = if x > 0.0 then x.to_i else x.to_i - 1
287 var x1 = x0 + 1
288 var y0 = if y > 0.0 then y.to_i else y.to_i - 1
289 var y1 = y0 + 1
290
291 # Position in grid
292 var sx = x - x0.to_f
293 var sy = y - y0.to_f
294
295 # Interpolate
296 var n0 = gradient_dot_product(x0, y0, x, y)
297 var n1 = gradient_dot_product(x1, y0, x, y)
298 var ix0 = sx.lerp(n0, n1)
299 n0 = gradient_dot_product(x0, y1, x, y)
300 n1 = gradient_dot_product(x1, y1, x, y)
301 var ix1 = sx.lerp(n0, n1)
302 var val = sy.lerp(ix0, ix1)
303
304 # Return value in [min...max] from val in [-1.0...1.0]
305 val /= 2.0
306 val += 0.5
307 return val.lerp(min, max)
308 end
309
310 # Get the component `w` of the gradient unit vector at `x`, `y`
311 #
312 # `w` at 0 targets the X axis, at 1 the Y axis.
313 #
314 # Returns a value between -1.0 and 1.0.
315 #
316 # Require: `w == 0 or w == 1`
317 protected fun gradient_vector(x, y, w: Int): Float
318 do
319 assert w == 0 or w == 1
320
321 # Use our own deterministic pseudo random number generator
322 #
323 # These magic prime numbers were determined good enough by
324 # non-emperical experimentation. They may need to be changed/improved.
325 var seed = 817721 + self.seed
326 var i = seed * (x+seed) * 25111217 * (y+seed) * 72233613
327 var mod = 137121
328 var angle = (i.mask.abs%mod).to_f*2.0*pi/mod.to_f
329
330 # Debug code to evaluate the efficiency of the random angle generator
331 # The average of the produced angles should be at pi
332 #
333 #var sum = once new Container[Float](0.0)
334 #var count = once new Container[Float](0.0)
335 #sum.item += angle
336 #count.item += 1.0
337 #if count.item.to_i % 1000 == 0 then print "avg:{sum.item/count.item}/{count.item} i:{i} a:{angle} ({x}, {y}: {seed})"
338
339 if w == 0 then return angle.cos
340 return angle.sin
341 end
342
343 private fun gradient_dot_product(ix, iy: Int, x, y: Float): Float
344 do
345 var dx = x - ix.to_f
346 var dy = y - iy.to_f
347
348 return dx*gradient_vector(ix, iy, 0) + dy*gradient_vector(ix, iy, 1)
349 end
350 end
351
352 redef universal Int
353 # The value of the least-significant 30 bits of `self`
354 #
355 # This mask is used as compatibility with 32 bits architecture.
356 # The missing 2 bits are used to tag integers by the Nit system.
357 private fun mask: Int
358 do
359 return self & 0x3FFF_FFFF
360 end
361 end