| 13 | const G2: f32 = (3.0 - SQRT3) / 6.0; |
| 14 | |
| 15 | pub fn open_simplex_2d(permutation: &Permutation, x: f32, y: f32) -> f32 { |
| 16 | let s = (x + y) * F2; |
| 17 | let xs = x + s; |
| 18 | let ys = y + s; |
| 19 | |
| 20 | let i = xs.floor() as isize; |
| 21 | let j = ys.floor() as isize; |
| 22 | |
| 23 | // Unskew to get original coordinates |
| 24 | let t = (i + j) as f32 * G2; |
| 25 | let x0 = x - (i as f32 - t); |
| 26 | let y0 = y - (j as f32 - t); |
| 27 | |
| 28 | // Determine simplex corner order |
| 29 | let (i1, j1) = if x0 > y0 { (1, 0) } else { (0, 1) }; |
| 30 | |
| 31 | // Second corner coordinates |
| 32 | let x1 = x0 - i1 as f32 + G2; |
| 33 | let y1 = y0 - j1 as f32 + G2; |
| 34 | |
| 35 | // Third corner coordinates |
| 36 | let x2 = x0 - 1.0 + 2.0 * G2; |
| 37 | let y2 = y0 - 1.0 + 2.0 * G2; |
| 38 | |
| 39 | // Hash gradient indices |
| 40 | let ii = (i & 255) as usize; |
| 41 | let jj = (j & 255) as usize; |
| 42 | let gi0 = permutation.get(ii + permutation.get(jj)) & 7; |
| 43 | let gi1 = permutation.get(ii + i1 + permutation.get(jj + j1)) & 7; |
| 44 | let gi2 = permutation.get(ii + 1 + permutation.get(jj + 1)) & 7; |
| 45 | |
| 46 | // Computate dot products |
| 47 | let mut n0 = 0.0; |
| 48 | let mut n1 = 0.0; |
| 49 | let mut n2 = 0.0; |
| 50 | |
| 51 | let t0 = 0.5 - x0 * x0 - y0 * y0; |
| 52 | if t0 > 0.0 { |
| 53 | let g = GRADIENTS_2D[gi0]; |
| 54 | n0 = (t0 * t0) * (t0 * t0) * (g.0 * x0 + g.1 * y0); |
| 55 | } |
| 56 | |
| 57 | let t1 = 0.5 - x1 * x1 - y1 * y1; |
| 58 | if t1 > 0.0 { |
| 59 | let g = GRADIENTS_2D[gi1]; |
| 60 | n1 = (t1 * t1) * (t1 * t1) * (g.0 * x1 + g.1 * y1); |
| 61 | } |
| 62 | |
| 63 | let t2 = 0.5 - x2 * x2 - y2 * y2; |
| 64 | if t2 > 0.0 { |
| 65 | let g = GRADIENTS_2D[gi2]; |
| 66 | n2 = (t2 * t2) * (t2 * t2) * (g.0 * x2 + g.1 * y2); |
| 67 | } |
| 68 | |
| 69 | // Sum contributions and scale |
| 70 | // 18.541 was the value I found to scale the best. It's not perfect, but there is no perfect value. It's close enough. |
| 71 | 18.541 * (n0 + n1 + n2) |
| 72 | } |