A rough overview, analysis, and rust-lang rewrite of Torben Ægidius Mogensen's planet generator

Torben Ægidius Mogensen, a professor working at Copenhagen University's Department of Computer Science, made a brilliant planet generator available at https://topps.diku.dk/torbenm/maps.msp that I've been toying with on and off for a couple of years now. Mid 2022 a couple of friends and I decided to start a world building project together using one of the cooler looking worlds generated by this planet generator. I also wanted the world to be generated at a very high resolution which isn't possible through the web interface, but is possible via the cli tool you can download from Mogensen's website too. I also wanted the world to be explorable via a tiled web map (slippy map) that you can pan around in and zoom very far in and out of, like what is possible on https://www.openstreetmap.org/ . Open street map is built upon the leaflet JS tool, so that's what I wanted for my slippy map of the planet we had decided to worldbuild upon too. Mogensen's tool even provides zooming and latitudinal & longitudinal panning before generating an image, so if I could hook such a image generation query up to an API endpoint with a format expected from leaflet JS, panning around in our fantasy world should be possible! Sadly I very quickly found out that although longitudinal panning before projecting is equivalent to panning along an x axis on an already projected map, the same cannot be said of latitudinal panning and a y axis on a projected map. I was getting some pretty severe horizontal banding issues when using my leaflet applet for exploring the fantasy world, so we abandoned the endeavour as Mogensen's tool didn't support what I needed it to.

Luckily Mogensen's tool is source available and free to study, which means I can study the inner workings of how it all works, and even add features to it if I should so choose. However, it is written in c and with a pretty unconventional function signature (by other programming languages' standard) as well as very undescriptive variables all over the place. What that all means, is that maintaining or adding features to this is a lot harder for me than I'm comfortable with. At the very least I know for a fact that had the program been written in a way I'm more familiar with, adding features would be a lot easier. That fact, as well as the fact that I wanted to know how the planet generation algorithm actually worked (briefly described as "resursive polyhedral subdivision" but that meant little to me), meant that a rewrite in rust was due. However, I would only rewrite the generation algorithm as well as all other functions I was making use of from Mogensen's planet generator, i.e. projections, colouring, seeding, etc.

Overview of how the algorithm works

The algorithm is actually already explained by Torben Ægidius Mogensen himself at Mogensen's own sub page under Copenhagen University's Datalogical Institute. Feel free to cross-compare explanations. The algorithm for his tool begins on slide #9.


The Sphere of points

The algorithm is one that can be asked about a certain coordinate in 3D space and it will return an altitude-value which can be used on maps to determine what the altitude on that specific part of the globe should be. This jargonny named method "resursive polyhedral subdivision" is what lets points close to eachother have similarly produced altitude-values, such that the final globe will have terrain that looks like terrain rather than pure noise. To produce a map, the 3D points asked lie on a sphere.

Points asked for altitude

As you can see above, the density of points increase near the poles. This is to be expected from the equirectangular projection we are using here. On an equirectangular projection, a single degree of latitude of change is the same everywhere. The asked points above form equidistant circles from one another. A single degree of longitude of change is also the same everywhere, even near the poles where a single degree of longitudinal change is far shorter of a real distance, than near the poles. The asked points above form circles of the same amount of points, regardless of the circles real circumference. Here's how planet earth looks with an equirectangular projection:

The process of finding the altitude for a given point starts with generating a tetrahedron that is big enough to encompass the entire sphere of points, such that this "starter" tetrahedron is guarenteed to contain the point we are asking for, regardless of what point that may be. The tetrahedron is generated using a set seed such that we can be sure to generate the exact same tetrahedron however many times we will need it (we need it for every single point we ask altitude from).

The tetrahedron that contain every possible point asked about

The tetrahedron consists of 4 vertices/points (as hetrahedra do), that has a 3D coordinate associated with it which you can see visualised in the illustration above. However, what you cannot see, is that each vertex also has 2 other values associated with it, namely a "seed" and an "altitude". By default the "altitude" of all 4 vertices of the tetrahedron are set to -0.02. The colouring algorithm (which is not part of the algorithm I am explaining here) assumed to have 0.0 be exactly where the shores generate. Setting the beginning altitude to -0.02 means that, on average, a generated point of our world will have an altitude around -0.02 biasing it below sea level according to our colouring algorithm. This means that the worlds generated with this program will be biased towards ocean, much like our own blue marble we call home is more ocean than it is land. The the 4 seeds of the vertices of the tetrahedron are generated deterministically using the set seed passed to the entire algorithm. The algorithm does subdivision of tetrahedra in order to find a very small tetrahedron within which our asked-about point reside. In order to produce smaller tetrahedra, we take our current tetrahedron, divide it in two, and pick whichever of those two still contain the point we are asking about. When dividing a tetrahedron in 2, you only need produce a single new vertex. It too, of course, needs a new altitude and seed associated with it. The exact way that the pseudo random numbers are being generated are only really interesting if you intend to be able to generate exactly the same worlds as Torben Mogensen can with his generator with exactly the same seeds. How the pseudo random numbers are being generated is actually irrelevant to how generated worlds with this algorithm tend to look. The seeds of each new vertex we generate when we make subdivisions of tetrahedra, are deterministically generated from parent verteces' seeds, which you may recall are ultimately just from the "world" seed passed to the entire algorithm. Thus for the rest of the explanantion of the algorithm I shall instead treat it as if the verteces do NOT have an associated seed with them, but rather that the random number used for altitude determination and subdivision location determination are generated given parent verteces combined with the world in some way.

Alright, I threw a lot of terms at you just now in my justification for why I am not going over the specific implementation of the "seed" associated with each vertex. Let's not loose track of these terms. I have highlighted them and made them hyperlinks in the text above so you know that you aren't yet meant to understand what I mean by any of those. Otherwise we'll just go over all 3 one by one.

Subdivision Location & Parent Verteces

When subdividing the current tetrahedron, we create a single vertex, that will be one of the corners in the two resulting tetrahedra, of which only the tetrahedron containing our target point will be kept. The longest side of the tetrahedron is found as part of the algorithm, and then a point along that line is picked as the coordinate (location) of our new vertex. This location is near but not exactly at the midpoint of that line. The location will be somewhere between 40% to 60% of the way from the starting point to the endpoint of the line. I call these two points the "parent vertexes" as it is the two corners of the current tetrahedon that are at either end of the longest line of the tetrahedron. They "parent" this newly born vertex that's near their midpoint. The formula is a fairly trivial 0.5 + 1.0*{rnumber}. "rnumber" here representing a random number generated from a random number generator, where given the world seed combined with the parent verteces' coordinates, will produce a number between 0 and 1.

New point and its parents

After this we use something called the determinant to figure out if the point we are asking about lies within one or the other tetrahedron. The determinant has several uses in mathematics, but the use we are interested in here, is that we can figure out which side of a flat plane a point is, and thus also what side of a triangle a point is. We first consider the triangle abc (a being one of the parent verteces, and both b and c being the 2 verteces on our tetrahedron that are not parent verteces to our new point). In laymans terms, We figure out if the new-born vertex falls on the right or left side of this triangle. Likewise we figure out if the new-born vertex falls on the right or left side of the triangle tcd (t being the "target" point that we are asking about, and both c and d being the same as before). If the new vertex fell on the same side of both triangles, we have determined that our new tetrahedron should have the four corners ancd, but if it fell on different sides of the triangles, our new tetrahedron should instead be nbcd (n here being the new-born vertex).

Two points asked for in the following illustration


Planes (or triangles) formed from the points in the illustration above, and how they relate to the new-born vertex and tetrahedron faces


Planes (or triangles) formed from the points in the illustration above, and how they relate to the new-born vertex and tetrahedron faces

Now with color coding!

  1. Take a point in 3D space, for example, the turqouise point.
  2. Form a triangle form it + the two non parent tetrahedron corners (aka connect the turqouise point to the one line on the tetrahedron that does not connect to any red dots, and is opposite the purple point)
  3. Ask if the purple point falls on the left or the right of this triangle.
  4. Ask if the purple point falls on the left or the right of the thick green triangle.
  5. If the answers were the same. Consider the green tetrahedron the new tetrahedron, and repeat the algorithm. If the answers were not the same, consider the orange tetrahedron the new tetrahedron, and repeat the algorithm.

You could take another point and do the same. There is a yellow dot that is also illustrated with a dotted triangle so you can see both its triangle and the thick green one. The step-by-step guide from above goes for any point however.

Altitude Determination

Obviously the most exciting of these 3 concepts. Determining these values is what ultimately leads us to a final altitude which the algorithm will then respond with for an asked-about point.

If the altitude of the new vertex was a perfect average between the two parent verteces, we would have a very boring generated world. The first tetrahedron starts with its four corner vertexes having the exact same starting altitude (by default -0.2 so that the world will be biased towards ocean as discussed earlier). Any new verteces from parents would then inherit the average between those parent altitudes, which in this case is exactly the same as either parent altitude. Any subsequent subdivisions and new verteces suffer the same problem. The world would generate with an entirely uniform altitude.

Let us go over how the algorithm shakes randomness into it. The algorithm first calculates an average of the two parent altitudes, but it adds two more terms. An "altitude contribution" and a "distance contribution". Both added directly onto this average to produce the new vertex' final altitude.

The "altitude contribution" calculates the difference in altitude between the two parent altitudes and multiplies it by a randomly generated number between 0.0 and 0.45.

The "distance contribution" calculates the distance in 3D space between the two parent verteces, multiplies it by a randomly generated number between 0.035 and finally takes this number to the power of 0.47. These units are completely meaningless without considering how big the distances between our verteces might be. The absolute longest distance between two verteces would be from the initial tetrahedron where the biggest distance between two corners is approx. 5.52. This is far under the 28.57 length that would be needed to produce a number after multiplication with 0.035. This means that all our distance contributions are well below 1.0 even before taking it to the power of 0.47. The smallest tetrahedra once we have subdivided approx. 100 times, have distances between their corners much much smaller, and thus far far below 1.0 before taking it to the power of 0.47.

The effect of taking these small numbers to the power of 0.47, is that they will grow. The smallest numbers grow the fastest. The longest line of lenght 5.52 get to grow 2.3x compared to if the distance contribution didn't take things to the power of 0.47. The distance between the north pole and south pole points one could ask for is 2.0 which grows 4.1x due to the power of 0.47. The distance between the north pole and any point at 89N latitude (a single degree latitude difference; real distance of 0.0175) grows 50x due to the power of 0.47.

The potential contribution to the final altitude thus comes in much larger part from small tetrahedron subdivision over large tetrahedron subdivison, than had it simply had a linear correlation in contribution. This is however crutially different than mistakenly concluding the small tetrahedron subdivision has more contribution than large tetrahedron. Although distances of 0.0175 grow approx. 12x as much as distances of 2.0 grow, it is still worth remembering that 2.0 is also approx. 115x as big of a number in the first place.

It is by far the first few big tetrahedon subdivisions that contribute to the randomness of the final altitude, the power simply helps to make the smaller tetrahedron subdivisions have a not-insignificant contribution too.

Sidequest: Could it run on the GPU?

Torben Ægidius Mogensen's implementation runs on the CPU, evaluating every point of interest (ultimately every pixel) one by one. Calculating the final altitude starting with the big starting tetrahedron (the one in all the illustrations above) and subdividing it approx. 100 times, is quite a few instructions for the CPU to work through. Nearby pixels are largely within the same tetrahedra, and only once subdivided many times do nearby pixels fall inside different tetrahedra. Mogensen actually saves on quite a bit of compute by caching the tetrahedron once there are only 11 subdivisions left to do. For the following pixel that needs an altitude computed his algorithm first checks to see if the point of interest is within this cached tetrahedron, and for the next few points of interest, the point is likely within that cached tetrahedron. If it is not, then the point of interest is instead within the starting tetrahedron which needs not 11 more subdivisions but rather approx. 100. The cached tetrahedron is then replaced by the 11th-last subdivision of this point of interest.

Still, this algorithm has great potential to be parallelised on GPU hardware. The algorithm is simple (but a lot of) arithmetic, each point of interest can have its altitude calculated entirely independent from knowledge of other points of interest. These properties make an algorithm well suited for GPU parallelisation. In principle at least. There needs to be enough compute to justify instanciating a "compute shader" on the GPU and delegating work to that piece of hardware rather than keeping it close to home by the CPU where there wont be delays in executing.

And turns out, there are great news, and terrible news.

The great news is, we can save quite a lot of time by delegating it to a GPU! A 2048x2048 pixel image generated on the CPU (without caching in all fairness) takes approx 11 seconds on my i5-12600KF, however it only took 1.5 seconds with GPU on my Nvidia GTX 3060 Ti. There is of course most time saving available by producing large images. Only 350ms out of the 1.5 seconds on the GPU accelerated planet generation was actual GPU work. The rest of the time the CPU was busy doing its responsibilities in the program such as instantiating everything, collecting GPU generated altitudes, translating them into colours and saving as a png. If the image is too small we gain less from the faster GPU than we loose from having to get things ready for the GPU such as instantiating the compute shader and collecting the GPU generated pixel data, both of which would not be the case had we stuck to generating on the CPU, so there is a trade of. For instance, a 256x256 pixel image generated on the CPU vs GPU the CPU gets the job done in 200ms, whereas it takes the GPU accelerated planet generation 460ms. The CPU is inactive for 300ms of those 460ms too.

The terrible news is that GPUs aren't designed with 64-bit precision floating point numbers in mind. There is a lot of floating point operations in the algorithm Mogensen designed and GPUs are certainly designed with those in mind (GPUs often benchmarked against eachother in FLOPS; floating point operations per second), but they are not designed with 64-bit precision, and that is what Mogensen has been using for his algorithm. My own GPU doesn't support them at all meaning I had to write the GPU accelerated version of the program with 32-bit precision. My hope was that 32-bit precision made for negligible differences between identically seeded worlds generated with the two methods. I was terribly wrong.

This is how the world seed 0.55 is supposed to render

This is how the same world seed 0.55 rendered with the GPU. Completely same settings.

If you really really squint, the two worlds have features in common in a very very broad sense, but everything is completely different on small and even medium scales.

I don't even think the 32-bit precision world generated on the GPU is a terrible looking world, it's just entirely different from what was generated on the CPU with the same seed. It means that the 32-bit precision version is not an equivalent program to Torben Ægedius Mogensen's program and my GPU accelerated method won't be of use to my friends' and my ongoing world building project.

So the GPU side quest was a dead end for this rewrite. I am however happy to have tried GPU programming (with the progamming language WGSL) as I have high hopes that highly parallelisable tasks will present themselves to me again where GPU acceleration will be the right choice. It brings me great hope knowing that changing Mogensen's planet generator to use 32-bit precision numbers on the CPU generate identical worlds to the 32-bit precision GPU accelerated method I have, so my GPU is a reliable piece of hardware.

My Rust rewrite source code

The code below is the entire rust rewrite of the parts of the original planet generator by Torben Ægedius Mogensen that I needed. That is to say there are missing colours schemes available, missing projections, and certain settings such as latitudinal and longitudinal panning which I make no use of in my own world building. The feature of saving to a png image, and using the GPU are in different files, while this main.rs file focuses on the algorithm itself.


main.rs

mod tests;
mod gpu_render;
mod save;
--[[ EMPTY LINE ]]--
use clap::Parser;
use wgpu::util::DeviceExt;
use std::{f64::consts::PI, ops::{Add, Mul, Sub}, sync::mpsc::channel};
--[[ EMPTY LINE ]]--
const INITIAL_ALT: f64 = -0.02;   /* initial altitude (slightly below sea level) */
const ALT_DIFF_WEIGHT: f64 = 0.45;  /* weight for altitude difference */
const DIST_WEIGHT: f64 = 0.035; /* weight for distance */
const POW_ALTITUDE: f64 = 1.0; /* power for altitude difference */
const POW_DIST: f64 = 0.47;  /* power for distance function */
--[[ EMPTY LINE ]]--
#[derive(Parser, Debug)]
#[command(about)]
struct GenerationParams {
  // Seed of your world. 0.0 - 1.0.
  #[arg(short, long, default_value_t = 0.123)]
  seed: f64,
--[[ EMPTY LINE ]]--
  // width of your image. The program deals in square images, so this is also the height
  #[arg(short, long, default_value_t = 256)]
  width: usize,
--[[ EMPTY LINE ]]--
  // Horizontal panning. -1.0 - 1.0 across the entire world, regardless of zoom
  #[arg(short('H'), long, allow_hyphen_values = true, default_value_t = 0.0)]
  hor_pan: f64,
  // vertical panning. -1.0 - 1.0 across the entire world, regardless of zoom
  #[arg(short('V'), long, allow_hyphen_values = true, default_value_t = 0.0)]
  vert_pan: f64,
  // Zoom of your image upon the world
  #[arg(short, long, default_value_t = 1.0)]
  zoom: f64,
--[[ EMPTY LINE ]]--
  // color scheme to use
  #[arg(short, long, value_enum, default_value_t = ColorScheme::Olsson)]
  color_scheme: ColorScheme,
--[[ EMPTY LINE ]]--
  // projection to use
  #[arg(short, long, value_enum, default_value_t = Projection::Mercator)]
  projection: Projection,
--[[ EMPTY LINE ]]--
  // The path to which the generated image should be saved
  #[arg(short, long, default_value_t = "/dev/stdout".to_string())]
  filepath: String,
--[[ EMPTY LINE ]]--
  // minimum length of AB before we no longer split and just return as is
  // This will make for a mosaic-like effect on scales proportional to the value
  // given.
  // The default behaviour is letting Depth / level dictate when the tetrahedron
  // shall no longer split, giving no mosaic-like effects at any scale.
  #[arg(short('d'), long, default_value_t = 0.0)]
  minimum_split_distance: f64,
--[[ EMPTY LINE ]]--
  // output the altitudes as is, byte for byte, without colorizing and PNG
  // encoding it.
  // You still need to carefully consider color scheme anyway, as the altitudes
  // as bytes are still translated to integers from their origianal floating
  // point format, and the color scheme dictates its mapping to integer. If
  // confused, use --color-scheme highly-discrete
  // Useful for stdout output when used in other programs such as erosion
  // simulators.
  #[arg(short('r'), long, action)]
  raw: bool,
--[[ EMPTY LINE ]]--
  // print how far along in the process we are
  #[arg(short('v'), long, action)]
  print_progress: bool,
--[[ EMPTY LINE ]]--
  // Whether or not to GPU acccelerate
  // GPU only supports Olsson color scheme. TODO: fix that
  #[arg(short('G'), long, action)]
  use_gpu: bool
}
--[[ EMPTY LINE ]]--
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
enum ColorScheme {
  Olsson,
  MapsForFree,
  HighlyDiscrete,
}
--[[ EMPTY LINE ]]--
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
enum Projection {
  Square,
  Mercator,
}
--[[ EMPTY LINE ]]--
#[derive(Default, Clone, Copy, Debug)]
struct Coordinate {
  x: f64,
  y: f64,
  z: f64,
}
--[[ EMPTY LINE ]]--
impl Sub for Coordinate {
  type Output = Self;
--[[ EMPTY LINE ]]--
  fn sub(self, rhs: Self) -> Self::Output {
    Self {
      x: self.x - rhs.x,
      y: self.y - rhs.y,
      z: self.z - rhs.z,
    }
  }
}
--[[ EMPTY LINE ]]--
impl Mul<f64> for Coordinate {
  type Output = Self;
--[[ EMPTY LINE ]]--
  fn mul(self, multiplier: f64) -> Self::Output {
    Self {
      x: self.x * multiplier,
      y: self.y * multiplier,
      z: self.z * multiplier,
    }
  }
}
--[[ EMPTY LINE ]]--
impl Add for Coordinate {
  type Output = Self;
--[[ EMPTY LINE ]]--
  fn add(self, rhs: Self) -> Self::Output {
    Self {
      x: self.x + rhs.x,
      y: self.y + rhs.y,
      z: self.z + rhs.z,
    }
  }
}
--[[ EMPTY LINE ]]--
impl Coordinate {
  fn points_on_same_side_of_plane(coord: Self, other: Self, plane: [Self; 3]) -> bool {
    let coord_plane0 = coord - plane[0];
    let plane_01 = plane[1] - plane[0];
    let plane_02 = plane[2] - plane[0];
    let other_plane0 = other - plane[0];
    let plane_x_coord_determinant = Self::matrix_determinant([coord_plane0, plane_01, plane_02]);
    let other_x_coord_determinant = Self::matrix_determinant([other_plane0, plane_01, plane_02]);
    plane_x_coord_determinant * other_x_coord_determinant > 0.0
  }
--[[ EMPTY LINE ]]--
  /* https://en.wikipedia.org/wiki/Determinant */
  fn matrix_determinant(coords: [Self; 3]) -> f64 {
    let Self { x: a, y: b, z: c } = coords[0];
    let Self { x: d, y: e, z: f } = coords[1];
    let Self { x: g, y: h, z: i } = coords[2];
--[[ EMPTY LINE ]]--
    a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h
  }
--[[ EMPTY LINE ]]--
  fn interpolate(self, other: Self, t: f64) -> Self {
    self*t + other*(1.0 - t)
  }
}
--[[ EMPTY LINE ]]--
#[derive(Default, Clone, Copy, Debug)]
#[repr(C)]
struct Vertex {
  altitude: f64, /* altitude */
  seed: f64, /* seed */
--[[ EMPTY LINE ]]--
  coordinate: Coordinate
}
--[[ EMPTY LINE ]]--
impl Vertex {
  fn dist(&self, b: Self) -> f64 {
    let x = self.coordinate.x-b.coordinate.x;
    let y = self.coordinate.y-b.coordinate.y;
    let z = self.coordinate.z-b.coordinate.z;
    return x*x + y*y + z*z;
  }
}
--[[ EMPTY LINE ]]--
#[derive(Default, Clone, Copy, Debug, Hash, PartialEq, Eq)]
struct Color {
  r: u8,
  g: u8,
  b: u8,
}
--[[ EMPTY LINE ]]--
struct Swatch {
  altitude_index: u16,
  color: Color,
}
--[[ EMPTY LINE ]]--
#[tokio::main]
async fn main() {
  let params = GenerationParams::parse();
--[[ EMPTY LINE ]]--
  if params.print_progress && params.filepath == "/dev/stdout" {
    panic!("print_progress should not be used together with stdout");
  }
--[[ EMPTY LINE ]]--
  let (colors, highest) = interpolate_colors(
    match params.color_scheme {
      ColorScheme::Olsson => { olsson() }
      ColorScheme::MapsForFree => { maps_for_free() }
      ColorScheme::HighlyDiscrete => { highly_discrete() }
    }
  );
  if params.use_gpu {
    let _ = gpu_render::generate_with_gpu(&params, highest, colors).await;
  } else {
    let altitudes = get_alts_projected(&params, highest);
--[[ EMPTY LINE ]]--
    save::finalize_output(
      &params,
      altitudes,
      colors,
    );
  }
}
--[[ EMPTY LINE ]]--
fn initial_tetrahedron(seed: f64) -> [Vertex; 4] {
  let mut tetra = [Vertex::default(); 4];
  tetra[0].coordinate.x = -3.0f64.sqrt()-0.20;
  tetra[0].coordinate.y = -3.0f64.sqrt()-0.22;
  tetra[0].coordinate.z = -3.0f64.sqrt()-0.23;
--[[ EMPTY LINE ]]--
  tetra[1].coordinate.x = -3.0f64.sqrt()-0.19;
  tetra[1].coordinate.y = 3.0f64.sqrt()+0.18;
  tetra[1].coordinate.z = 3.0f64.sqrt()+0.17;
--[[ EMPTY LINE ]]--
  tetra[2].coordinate.x = 3.0f64.sqrt()+0.21;
  tetra[2].coordinate.y = -3.0f64.sqrt()-0.24;
  tetra[2].coordinate.z = 3.0f64.sqrt()+0.15;
--[[ EMPTY LINE ]]--
  tetra[3].coordinate.x = 3.0f64.sqrt()+0.24;
  tetra[3].coordinate.y = 3.0f64.sqrt()+0.22;
  tetra[3].coordinate.z = -3.0f64.sqrt()-0.25;
--[[ EMPTY LINE ]]--
  let r1 = seed;
--[[ EMPTY LINE ]]--
  let r1 = rand2(r1,r1);
  let r2 = rand2(r1,r1);
  let r3 = rand2(r1,r2);
  let r4 = rand2(r2,r3);
--[[ EMPTY LINE ]]--
  tetra[0].seed = r1;
  tetra[1].seed = r2;
  tetra[2].seed = r3;
  tetra[3].seed = r4;
--[[ EMPTY LINE ]]--
  tetra[0].altitude = INITIAL_ALT;
  tetra[1].altitude = INITIAL_ALT;
  tetra[2].altitude = INITIAL_ALT;
  tetra[3].altitude = INITIAL_ALT;
--[[ EMPTY LINE ]]--
  tetra
}
--[[ EMPTY LINE ]]--
fn get_alts_projected(params: &GenerationParams, highest: usize) -> Vec<Vec<usize>> {
  let mut alts = vec![vec![Default::default(); params.width]; params.width];
--[[ EMPTY LINE ]]--
  let width = params.width as f64;
  let height = width;
--[[ EMPTY LINE ]]--
  let zoom = params.zoom as f64;
--[[ EMPTY LINE ]]--
  for j in 0..height as usize {
    if params.print_progress {
      println!("so far: {} / {}", j, height);
    }
    let adj_j = (j as f64)/zoom+height/2.0-height/zoom/2.0+params.vert_pan*height/2.0;
    for i in 0..params.width {
      let adj_i = (i as f64)/zoom+width/2.0-width/zoom/2.0+params.hor_pan*width/2.0;
      let altitude_float = match params.projection {
        Projection::Square => {
          square_proj(
            adj_i / width, adj_j / height,
            width,
            zoom,
            params.seed,
            params.minimum_split_distance,
          )
        }
        Projection::Mercator => {
          mercator_proj(
            adj_i / width, adj_j / height,
            width,
            zoom,
            params.seed,
            params.minimum_split_distance,
          )
        }
      };
      alts[i][j] = get_corresponding_integer_altitude(altitude_float, highest);
    }
  }
  alts
}
fn original_olsson() -> Vec<Swatch> {
  vec![
    /* These have special meaning in the original c program by Torben Ægidius
     * Mogensen. But we don't use them for anything here. */
    Swatch { altitude_index: 0, color: Color { r: 0, g: 0, b: 0 } },
    Swatch { altitude_index: 1, color: Color { r: 255, g: 255, b: 255 } },
    Swatch { altitude_index: 2, color: Color { r: 255, g: 255, b: 255 } },
    Swatch { altitude_index: 3, color: Color { r: 0, g: 0, b: 0 } },
    Swatch { altitude_index: 4, color: Color { r: 0, g: 0, b: 0 } },
    Swatch { altitude_index: 5, color: Color { r: 255, g: 0, b: 0 } },
--[[ EMPTY LINE ]]--
    /* actual altitude indexes */
--[[ EMPTY LINE ]]--
    Swatch { altitude_index: 6, color: Color { r: 0, g: 51, b: 119 } },
    Swatch { altitude_index: 36, color: Color { r: 187, g: 255, b: 255 } },
--[[ EMPTY LINE ]]--
    Swatch { altitude_index: 37, color: Color { r: 0, g: 68, b: 0 } },
    Swatch { altitude_index: 39, color: Color { r: 34, g: 102, b: 0 } },
    Swatch { altitude_index: 41, color: Color { r: 34, g: 136, b: 0 } },
    Swatch { altitude_index: 43, color: Color { r: 119, g: 170, b: 0 } },
    Swatch { altitude_index: 45, color: Color { r: 187, g: 221, b: 0 } },
    Swatch { altitude_index: 47, color: Color { r: 255, g: 187, b: 34 } },
    Swatch { altitude_index: 49, color: Color { r: 238, g: 170, b: 34 } },
    Swatch { altitude_index: 51, color: Color { r: 221, g: 136, b: 34 } },
--[[ EMPTY LINE ]]--
    Swatch { altitude_index: 52, color: Color { r: 204, g: 136, b: 34 } },
    Swatch { altitude_index: 53, color: Color { r: 187, g: 102, b: 34 } },
    Swatch { altitude_index: 54, color: Color { r: 170, g: 85, b: 34 } },
    Swatch { altitude_index: 55, color: Color { r: 153, g: 85, b: 34 } },
    Swatch { altitude_index: 56, color: Color { r: 136, g: 68, b: 34 } },
    Swatch { altitude_index: 57, color: Color { r: 119, g: 51, b: 34 } },
    Swatch { altitude_index: 58, color: Color { r: 85, g: 51, b: 17 } },
    Swatch { altitude_index: 59, color: Color { r: 68, g: 34, b: 0 } },
--[[ EMPTY LINE ]]--
    Swatch { altitude_index: 60, color: Color { r: 255, g: 255, b: 255 } },
    Swatch { altitude_index: 66, color: Color { r: 185, g: 185, b: 185 } },
  ]
}
--[[ EMPTY LINE ]]--
fn olsson() -> Vec<Swatch> {
  let mut ret = vec![];
  for Swatch { altitude_index: altish_index, color } in original_olsson() {
    if altish_index >= 6 {
      ret.push(Swatch { altitude_index: altish_index - 6, color});
    }
  }
  ret
}
--[[ EMPTY LINE ]]--
fn maps_for_free() -> Vec<Swatch> {
  vec![
    /* every point approximates 1/3 m (I'm European, I have no idea what feet
     * are shhh) */
--[[ EMPTY LINE ]]--
    /* 2000m below sea level */
    Swatch { altitude_index: 0, color: Color { r: 38, g: 16, b: 123 } },
    /* ocean end */
    Swatch { altitude_index: 6000, color: Color { r: 176, g: 205, b: 255 } },
    /* beeah begin */
    Swatch { altitude_index: 6001, color: Color { r: 250, g: 230, b: 135 } },
    /* beach end (3m) / grassy begin */
    Swatch { altitude_index: 6009, color: Color { r: 99, g: 150, b: 100 } },
    /* 500m above sea level */
    Swatch { altitude_index: 7500, color: Color { r: 252, g: 235, b: 137 } },
    /* 2000m above sea level */
    Swatch { altitude_index: 12000, color: Color { r: 193, g: 80, b: 0 } },
    // /* 2800m above sea level */
    // Swatch { altitude_index: 38400, color: Color { r: 87, g: 32, b: 13 } },
    // /* 4800m above sea level */
    // Swatch { altitude_index: 44400, color: Color { r: 135, g: 135, b: 135 } },
    // /* 8000m above sea level */
    // Swatch { altitude_index: 54000, color: Color { r: 205, g: 205, b: 205 } },
    // /* 10000m above sea level, to match the below */
    // Swatch { altitude_index: 60000, color: Color { r: 205, g: 205, b: 205 } },
  ]
}
--[[ EMPTY LINE ]]--
fn highly_discrete() -> Vec<Swatch> {
  let mut swatches = vec![];
  // water. 0 - 32767
  for i in 0..=255u8 {
    for j in 0..=15u8 {
      swatches.push(
        Swatch { altitude_index: i as u16 * 128 + j as u16 * 8 + 7, color: Color { r: j, g: 0, b: i } }
      );
      swatches.push(
        Swatch { altitude_index: i as u16 * 128 + j as u16 * 8 + 7, color: Color { r: j, g: 7, b: i } }
      );
    }
  }
  // land. 32768 - 65535
  for i in 0..=255u8 {
    for j in 0..=15u8 {
      swatches.push(
        Swatch { altitude_index: i as u16 * 128 + j as u16 * 8 + 32768, color: Color { r: i, g: 248, b: j } }
      );
      swatches.push(
        Swatch { altitude_index: i as u16 * 128 + j as u16 * 8 + 32768 + 7, color: Color { r: i, g: 255, b: j } }
      );
    }
  }
  swatches
}
--[[ EMPTY LINE ]]--
fn square_proj(
  u: f64,
  v: f64,
  img_width: f64,
  zoom: f64,
  initial_seed: f64,
  minimum_distance: f64,
) -> f64 {
  let tetra = initial_tetrahedron(initial_seed);
--[[ EMPTY LINE ]]--
  let theta = -0.5*PI+PI*(2.0*u-1.0);
  let phi = (2.*v - 1.)*PI;
  let cos2 = phi.cos();
  let scale1 = zoom*img_width/cos2/PI;
  let depth = 3*(((scale1*1.0).log2()) as usize)+3;
--[[ EMPTY LINE ]]--
  /* threat pixel out of bounds as bottom of the ocean */
  if (phi+phi).abs() > PI || cos2 <= 0.0 { return -1.0; }
--[[ EMPTY LINE ]]--
  let target = Coordinate { x: theta.cos()*cos2,  y: phi.sin(),  z: -theta.sin()*cos2 };
--[[ EMPTY LINE ]]--
  seek_altitude(
    target, /* coordinates of point we want colour of */
    tetra, /* vertices of tetrahedron */
    depth,
    minimum_distance
  )
}
--[[ EMPTY LINE ]]--
fn mercator_proj(
  u: f64,
  v: f64,
  img_width: f64,
  zoom: f64,
  initial_seed: f64,
  minimum_distance: f64,
) -> f64 {
  let tetra = initial_tetrahedron(initial_seed);
--[[ EMPTY LINE ]]--
  let theta = -0.5*PI+PI*(2.0*u-1.0);
  // let mut y = sin(v);
  // y = (1.0+y)/(1.0/y);
  // y = 0.5*y.ln();
  let mut y = PI*(2.0*v-1.0);
  y = (2.*y).exp();
  y = (y-1.)/(y+1.);
--[[ EMPTY LINE ]]--
--[[ EMPTY LINE ]]--
  let cos2 = (1.0-y*y).sqrt();
  let scale1 = zoom*img_width/cos2/PI;
  let depth = 3*(((scale1*1.0).log2()) as usize)+3;
--[[ EMPTY LINE ]]--
  /* threat pixel out of bounds as bottom of the ocean */
  if cos2 <= 0.0 { return -1.0; }
--[[ EMPTY LINE ]]--
  let target = Coordinate { x: theta.cos()*cos2,  y: y,  z: -theta.sin()*cos2 };
--[[ EMPTY LINE ]]--
  seek_altitude(
    target, /* coordinates of point we want colour of */
    tetra, /* vertices of tetrahedron */
    depth,
    minimum_distance
  )
}
--[[ EMPTY LINE ]]--
fn get_corresponding_integer_altitude(
  altitude_as_float: f64,
  highest: usize,
) -> usize {
  let sea = highest/2;
  let land = sea+1;
  let mut corresponding_integer_altitude;
  if altitude_as_float <= 0.0 {
    corresponding_integer_altitude = (sea as isize + ((sea+1) as f64 * (10.*altitude_as_float)) as isize) as usize;
  } else {
    if altitude_as_float >= 0.1 {
      corresponding_integer_altitude = highest;
    } else {
      corresponding_integer_altitude = (land as isize + ((highest-land+1) as f64 * (10.*altitude_as_float)) as isize) as usize;
      if corresponding_integer_altitude > highest { corresponding_integer_altitude = highest; }
    }
  }
  corresponding_integer_altitude
}
--[[ EMPTY LINE ]]--
/* recursive concour and devide of tetrahedron approach to finding an altitude
 * for given target coordinate */
fn seek_altitude(
  target: Coordinate,
  tetra: [Vertex; 4],
  start_level: usize,
  minimum_distance: f64,
) -> f64 {
  let mut a = tetra[0];
  let mut b = tetra[1];
  let mut c = tetra[2];
  let mut d = tetra[3];
  let mut level = start_level;
  while level > 0 {
    /* make sure ab is longest edge */
    let length_ab = a.dist(b);
    let length_ac = a.dist(c);
    let length_ad = a.dist(d);
    let length_bc = b.dist(c);
    let length_bd = b.dist(d);
    let length_cd = c.dist(d);
--[[ EMPTY LINE ]]--
    let mut maxlength = length_ab;
    if length_ac > maxlength { maxlength = length_ac; }
    if length_ad > maxlength { maxlength = length_ad; }
    if length_bc > maxlength { maxlength = length_bc; }
    if length_bd > maxlength { maxlength = length_bd; }
    if length_cd > maxlength { maxlength = length_cd; }
--[[ EMPTY LINE ]]--
    if maxlength <= minimum_distance {
      break;
    }
--[[ EMPTY LINE ]]--
    {
      let shoving_arr = &mut [&mut a, &mut b, &mut c, &mut d];
      // push c back to b's current position
      if length_ac == maxlength { shove('c', 'b', shoving_arr); continue; };
      // push d back to b's current positon
      if length_ad == maxlength { shove('d', 'b', shoving_arr); continue; };
      // push b back to a's current position, then c to b's original position
      if length_bc == maxlength { shove('b', 'a', shoving_arr); shove('c', 'b', shoving_arr); continue; };
      // push b back to a's current position, then d to b's original position
      if length_bd == maxlength { shove('b', 'a', shoving_arr); shove('d', 'b', shoving_arr); continue; };
      // push c back to a's current position, then d to b's original position
      if length_cd == maxlength { shove('c', 'a', shoving_arr); shove('d', 'b', shoving_arr); continue; };
    }
--[[ EMPTY LINE ]]--
    /* ab is longest, so cut ab */
    let mut cut = Vertex::default();
    cut.seed = rand2(a.seed,b.seed);
    let cut_seed_for_maxlength_contrib_to_alt = rand2(cut.seed,cut.seed);
    let lerp_amount = 0.5+0.1*rand2(
      cut_seed_for_maxlength_contrib_to_alt,
      cut_seed_for_maxlength_contrib_to_alt
    );  /* find cut point */
--[[ EMPTY LINE ]]--
    if a.seed < b.seed {
      cut.coordinate = Coordinate::interpolate(a.coordinate, b.coordinate, lerp_amount);
    } else if a.seed > b.seed {
      let lerp_amount = 1.0-lerp_amount;
      cut.coordinate = Coordinate::interpolate(a.coordinate, b.coordinate, lerp_amount);
    } else { /* aseed==bseed, very unlikely to ever happen */
      cut.coordinate = Coordinate::interpolate(a.coordinate, b.coordinate, 0.5);
    }
--[[ EMPTY LINE ]]--
    /* new altitude is: */
    if maxlength > 1.0 { maxlength = maxlength.powf(0.5); }
    /* decrease contribution for very long distances */
    cut.altitude = 0.5*(a.altitude+b.altitude) /* average of end points */
      + cut.seed*ALT_DIFF_WEIGHT*(a.altitude-b.altitude).abs().powf(POW_ALTITUDE)
      /* plus contribution for altitude diff */
      + cut_seed_for_maxlength_contrib_to_alt*DIST_WEIGHT*maxlength.powf(POW_DIST); /* plus contribution for distance */
--[[ EMPTY LINE ]]--
    /* find out in which new tetrahedron target point is */
    if Coordinate::points_on_same_side_of_plane(a.coordinate, target, [cut.coordinate, c.coordinate, d.coordinate])
    {
      /* point is inside acde */
      level -= 1;
      let new_tetra = (c, d, a, cut);
      a = new_tetra.0;
      b = new_tetra.1;
      c = new_tetra.2;
      d = new_tetra.3;
      continue;
    } else {
      /* point is inside bcde */
      level -= 1;
      let new_tetra = (c, d, b, cut);
      a = new_tetra.0;
      b = new_tetra.1;
      c = new_tetra.2;
      d = new_tetra.3;
      continue;
    }
  }
  /* level == 0 */
  0.25*(a.altitude+b.altitude+c.altitude+d.altitude)
}
--[[ EMPTY LINE ]]--
//                                               Colors        , highest
fn interpolate_colors(swatches: Vec<Swatch>) -> ([Color; 65536], usize) {
  let mut colors = [Color::default(); 65536];
  let mut swatch_index = 0;
  for Swatch { altitude_index: altish_index, color: Color { r, g, b } } in swatches {
    let old_swatch_index = swatch_index;
    swatch_index = altish_index as usize;
--[[ EMPTY LINE ]]--
    if swatch_index < old_swatch_index { swatch_index = old_swatch_index; }
    if swatch_index > 65535 { swatch_index = 65535; }
    colors[swatch_index].r = r;
    colors[swatch_index].g = g;
    colors[swatch_index].b = b;
    /* interpolate colours between oldcNum and cNum */
    for i in old_swatch_index+1..swatch_index {
      colors[i] = lerp_color(colors[old_swatch_index], colors[swatch_index], old_swatch_index, swatch_index, i);
    }
  }
--[[ EMPTY LINE ]]--
  // Where there are no colors specified in the Vec
  let nocols = if swatch_index+1>=10 {
    swatch_index+1
  } else {
    10
  };
--[[ EMPTY LINE ]]--
  // There may be cols entries that were missed.
  // Fill the last ones.
  for i in swatch_index..nocols {
    colors[i] = colors[swatch_index];
  }
  (colors, nocols - 1)
}
--[[ EMPTY LINE ]]--
fn lerp_color(a: Color, b: Color, from: usize, to: usize, between: usize) -> Color{
  Color {
    r: lerp_byte(a.r, b.r, from, to, between),
    g: lerp_byte(a.g, b.g, from, to, between),
    b: lerp_byte(a.b, b.b, from, to, between), 
  }
}
--[[ EMPTY LINE ]]--
/* interpolates between two bytes given a 'between' value that lies between
 * 'from' and 'to'.
 * 'from' and 'to' should be the indeces that 'a' and 'b' has */
fn lerp_byte(a: u8, b: u8, from: usize, to: usize, between: usize) -> u8 {
  (
    (
      a as usize * (to     -between) +
      b as usize * (between-from   )
    ) /
    (to-from)
  ) as u8
}
--[[ EMPTY LINE ]]--
fn rand2(p: f64, q: f64) -> f64 /* random number generator taking two seeds */
                                /* rand2(p,q) = rand2(q,p) is important     */
{
  let rng_offset = 3.14159265;
  let r = (p+rng_offset)*(q+rng_offset);
  return 2.*r.fract()-1.
}
--[[ EMPTY LINE ]]--
fn shove<T: Clone + Sized>(shove_from_index: char, shove_to_index: char, arr: &mut [&mut T; 4]) {
  let from: usize = shove_from_index as usize - 'a' as usize;
  let to: usize = shove_to_index as usize - 'a' as usize;
  shove_with_indexes(from, to, arr);
}
--[[ EMPTY LINE ]]--
fn shove_with_indexes<T: Clone + Sized>(shove_from_index: usize, shove_to_index: usize, arr: &mut [&mut T; 4]) {
  let mut pos_now = shove_from_index;
  while pos_now != shove_to_index {
    let offset: isize;
    if pos_now > shove_to_index {
      offset = -1;
    }  else {
      offset = 1;
    }
    let new_pos = pos_now.checked_add_signed(offset).unwrap();
    // swap
    let tmp = arr[new_pos].clone();
    *arr[new_pos] = arr[pos_now].clone();
    *arr[pos_now] = tmp;
--[[ EMPTY LINE ]]--
    pos_now = pos_now.checked_add_signed(offset).unwrap();
  }
}
--[[ EMPTY LINE ]]--