Module: Worldgen::Algorithms

Defined in:
ext/worldgen/diamondsquare.c

Class Method Summary collapse

Class Method Details

.diamond_square!(*args) ⇒ Object

Generate terrain using a diamond square algorithm. Arguments: ‘heightmap` - The heightmap to use for the algorithm `roughness` (optional) - How “rough” to make the surface

Return value: nil



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
# File 'ext/worldgen/diamondsquare.c', line 26

VALUE diamond_square(int argc, VALUE *argv, VALUE self) {
  int x, y;
  double ratio = 500.0;
  VALUE heightmap_obj, vroughness;
  int size, side_size;
  double roughness;
  heightmap_points heights;

  rb_scan_args(argc, argv, "11", &heightmap_obj, &vroughness);
    
  size = get_size(heightmap_obj);
  side_size = size - 1;

  roughness = vroughness == Qnil ? DEFAULT_ROUGHNESS : NUM2DBL(vroughness);

  heights = (heightmap_points)malloc(sizeof(double) * num_points(size));

  memset(heights, 0.0, sizeof(double) * num_points(size));

  ARR(heights, 0, 0) = ARR(heights, 0, size - 1) =
    ARR(heights, size - 1, 0) = ARR(heights, size - 1, size - 1) =
    diamond_shift(roughness);

  while (side_size >= 2) {
    int half_side = side_size / 2;

    // Square step
    for (x = 0; x < size - 1; x += side_size) {
      for (y = 0; y < size - 1; y += side_size) {
        double avg = (ARR(heights, x, y) +
          ARR(heights, x + side_size, y) +
          ARR(heights, x, y + side_size) +
          ARR(heights, x + side_size, y + side_size)) / 4.0;

        ARR(heights, x + half_side, y + half_side) = avg + diamond_shift(roughness);
      }
    }

    for (x = 0; x < size - 1; x += half_side) {
      for (y = (x + half_side) % side_size; y < size - 1; y += side_size) {
        double avg = (ARR(heights, (x - half_side + size - 1) % (size - 1), y) +
          ARR(heights, (x + half_side) % (size - 1), y) +
          ARR(heights, x, (y + half_side) % (size - 1)) +
          ARR(heights, x, (y - half_side + size - 1) % (size - 1))) / 4.0;

        avg += diamond_shift(roughness);

        ARR(heights, x, y) = avg;

        if (x == 0) {
          ARR(heights, size - 1, y) = avg;
        }
        if (y == 0) {
          ARR(heights, x, size - 1) = avg;
        }
      }
    }

    side_size /= 2.0;
    ratio /= 2.0;
  }

  // normalize
  normalize(heights, size);

  // copy into the array
  set_heights(heightmap_obj, heights);

  return Qnil;
}