1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Multi-language Perlin noise benchmark.
12 // See https://github.com/nsf/pnoise for timings and alternative implementations.
14 use std::f32::consts::PI;
15 use std::rand::{Rng, StdRng};
22 fn lerp(a: f32, b: f32, v: f32) -> f32 { a * (1.0 - v) + b * v }
24 fn smooth(v: f32) -> f32 { v * v * (3.0 - 2.0 * v) }
26 fn random_gradient<R: Rng>(r: &mut R) -> Vec2 {
27 let v = PI * 2.0 * r.gen();
28 Vec2 { x: v.cos(), y: v.sin() }
31 fn gradient(orig: Vec2, grad: Vec2, p: Vec2) -> f32 {
32 (p.x - orig.x) * grad.x + (p.y - orig.y) * grad.y
35 struct Noise2DContext {
36 rgradients: [Vec2, ..256],
37 permutations: [i32, ..256],
41 fn new() -> Noise2DContext {
42 let mut rng = StdRng::new().unwrap();
44 let mut rgradients = [Vec2 { x: 0.0, y: 0.0 }, ..256];
45 for x in rgradients.mut_iter() {
46 *x = random_gradient(&mut rng);
49 let mut permutations = [0i32, ..256];
50 for (i, x) in permutations.mut_iter().enumerate() {
53 rng.shuffle(permutations);
55 Noise2DContext { rgradients: rgradients, permutations: permutations }
58 fn get_gradient(&self, x: i32, y: i32) -> Vec2 {
59 let idx = self.permutations[(x & 255) as uint] +
60 self.permutations[(y & 255) as uint];
61 self.rgradients[(idx & 255) as uint]
64 fn get_gradients(&self, x: f32, y: f32) -> ([Vec2, ..4], [Vec2, ..4]) {
75 ([self.get_gradient(x0, y0), self.get_gradient(x1, y0),
76 self.get_gradient(x0, y1), self.get_gradient(x1, y1)],
77 [Vec2 { x: x0f, y: y0f }, Vec2 { x: x1f, y: y0f },
78 Vec2 { x: x0f, y: y1f }, Vec2 { x: x1f, y: y1f }])
81 fn get(&self, x: f32, y: f32) -> f32 {
82 let p = Vec2 {x: x, y: y};
83 let (gradients, origins) = self.get_gradients(x, y);
85 let v0 = gradient(origins[0], gradients[0], p);
86 let v1 = gradient(origins[1], gradients[1], p);
87 let v2 = gradient(origins[2], gradients[2], p);
88 let v3 = gradient(origins[3], gradients[3], p);
90 let fx = smooth(x - origins[0].x);
91 let vx0 = lerp(v0, v1, fx);
92 let vx1 = lerp(v2, v3, fx);
93 let fy = smooth(y - origins[0].y);
100 let symbols = [' ', '░', '▒', '▓', '█', '█'];
101 let mut pixels = [0f32, ..256*256];
102 let n2d = Noise2DContext::new();
104 for _ in range(0, 100) {
105 for y in range(0u, 256) {
106 for x in range(0u, 256) {
107 let v = n2d.get(x as f32 * 0.1, y as f32 * 0.1);
108 pixels[y*256+x] = v * 0.5 + 0.5;
113 for y in range(0u, 256) {
114 for x in range(0u, 256) {
115 let idx = (pixels[y*256+x] / 0.2) as uint;
116 print!("{:c}", symbols[idx]);