hex_ground source

← hex_ground · API reference · version 0.1.4

2 file(s), 787 lines. This is the source the published version ships, and it is loft — the library is written in the same language you call it from.

Public items

A worked example is a call site the author chose as the thing to read first. Call sites are every line naming the item, found mechanically over the source with comments excluded — so an item with no worked example is not an item nobody uses.

ItemDefinedWorked exampleCall sites
Ground struct34—46 49 155 167 183 192 … (12 total)
ground_new fn46—41 81 91 103 128 185 … (10 total)
ground_unit fn54—193 266 61 140
ground_centre fn57—70 158 170 206 338 427 … (17 total)
ground_cell_near fn62—426 483 52
GroundMeasures struct85—93 94 127 155 183 192 … (7 total)
ground_measures fn93—71 113 130 190
GroundSteps struct101—111 127 155 70
steps_level fn111—134 138
terrace_height fn127—159 72 73 74 77 84
ground_terraces fn155—82
ground_hill fn167—93 203 204
ground_seat fn183—114
ground_dig fn192—131
sides_distance fn216—207 147
GroundCliff struct244—265 267 294
GroundBox struct253—265 306 325 334 165 175 … (8 total)
ground_cliffs fn264—166 177 183
ground_box_distance fn325—341 194
ground_sharpen fn334—190
ground_corner_height fn367—448 449 229 250 251
ground_height_at fn425—208 232 237 238 246 276
ground_height_on fn481—272 273

src/hex_ground.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
// hex_ground — THE GROUND STRUCTURES STAND ON: A HEIGHT AND A SURFACE KIND PER CELL, AND THE
// ROUTINES THAT SHAPE IT.
//
// `hex_terrain` GENERATES land: an overland lattice, hydrology, rivers, a kernel blend sampled
// anywhere.  This is the other thing — the ground of one PLACE, authored: a town's terraces, the
// hill a house stands on, the bed a stream runs in, the cliff behind the market.  It is
// `hex_field`'s `Heights` and `Labels` over a window of cells, and five ways to shape them:
//
//   ground_terraces   a stepped height map (levels on a square grid) made smooth: each step up
//                     a slope across where its front stood, the flat tops left flat
//   ground_hill       a round hill, a cosine from its top to its foot
//   ground_seat       a structure seated: its footprint level, the ground round it blended back
//   ground_dig        a structure dug in (a stream's bed), its bank along its STRAIGHT sides
//   ground_cliffs /   where a front must not slope: the straight sides of the cells of a level
//   ground_sharpen    and up, as cliffs, and the ground stood at its level's height beside them
//
// The straight sides are `hex_draw::cells_outlines`' — the same lines a road's edge or a house's
// wall is drawn along — so a bank and a cliff run straight, not along the cells' zigzag.
//
// UNITS.  A ground carries its `step`: the distance between two neighbouring cell centres in
// the caller's unit, the unit heights are in too.  sqrt(3) is the lattice's own world unit; 1.5
// is a ground in metres where a hex step is 1.5 m.  A centre is then at (k * step/2,
// m * step*sqrt(3)/6) for doubled coordinates (k, m), y growing north.
//
// From tile-world-game (its hexterrain.loft), whose rules these routines keep and cite by tag
// (the HG rules of its `formal/hex-houses.md`).
use hex_field::*;
use hex_draw::*;
use hex_place::*;

// The ground over a window of cells: a height and a surface kind per cell, and its `step`.
pub struct Ground {
  pub gr_heights: Heights,
  pub gr_kinds:   Labels,
  pub gr_q0:      integer,
  pub gr_r0:      integer,
  pub gr_w:       integer,
  pub gr_h:       integer,
  pub gr_step:    float,
}

// @FR-HG-Surface: a height and a surface kind per cell
// Flat ground at height 0 over the window, every cell of surface `kind`, centres `step` apart.
pub fn ground_new(q0: integer, r0: integer, w: integer, h: integer, step: float, kind: integer) -> Ground {
  kinds = labels_new(q0, r0, w, h);
  for r in r0..r0 + h { for q in q0..q0 + w { label_set(kinds, q, r, kind); } }
  Ground { gr_heights: heights_new(q0, r0, w, h), gr_kinds: kinds, gr_q0: q0, gr_r0: r0, gr_w: w, gr_h: h, gr_step: step }
}

// The ground's unit per lattice world unit (a hex's circumradius): what a point of
// `hex_draw`'s outlines is multiplied by to lie on the ground.
pub fn ground_unit(step: float) -> float { 2.0 * (step * 0.28867513459481287) }

// A cell's centre, in a ground's unit.
pub fn ground_centre(step: float, q: integer, r: integer) -> (float, float) {
  ((lattice_k(q, r) as float) * (step * 0.5), (lattice_m(q, r) as float) * (step * 0.28867513459481287))
}

// The cell whose centre is nearest (x, y), in a ground's unit.
pub fn ground_cell_near(step: float, x: float, y: float) -> (integer, integer) {
  r = round((y / (3.0 * (step * 0.28867513459481287))) ?? 0.0) as integer;
  q = round(((((x / (step * 0.5)) ?? 0.0)) - ((r & 1) as float)) * 0.5) as integer;
  best_q = q;
  best_r = r;
  best = -1.0;
  for dr in -1..2 {
    for dq in -1..2 {
      (cx, cy) = ground_centre(step, q + dq, r + dr);
      d = (cx - x) * (cx - x) + (cy - y) * (cy - y);
      if best < 0.0 || d < best {
        best = d;
        best_q = q + dq;
        best_r = r + dr;
      }
    }
  }
  (best_q, best_r)
}

// The ground's measurements, in its unit: a storey (the height between two levels), how wide a
// hillside is between two terraces, how wide a bank, and how far round a seated structure the
// ground blends back to its own height.
pub struct GroundMeasures {
  pub gm_storey:   float,
  pub gm_hillside: float,
  pub gm_bank:     float,
  pub gm_blend:    float,
}

// The four measurements.
pub fn ground_measures(storey: float, hillside: float, bank: float, blend: float) -> GroundMeasures {
  GroundMeasures { gm_storey: storey, gm_hillside: hillside, gm_bank: bank, gm_blend: blend }
}

// ── terraces made smooth ────────────────────────────────────────────────────

// A stepped height map on a square grid: a level per square (`level[j * nx + i]`), squares
// `size` units a side, square (0, 0) with its south-west corner at (x0, y0), j growing north.
pub struct GroundSteps {
  pub gs_x0:    float,
  pub gs_y0:    float,
  pub gs_size:  float,
  pub gs_nx:    integer,
  pub gs_ny:    integer,
  pub gs_level: vector<integer>,
}

// The level of square (i, j), the nearest square's beyond the map.
pub fn steps_level(s: const GroundSteps, i: integer, j: integer) -> integer {
  ci = if i < 0 { 0 } else if i >= s.gs_nx { s.gs_nx - 1 } else { i };
  cj = if j < 0 { 0 } else if j >= s.gs_ny { s.gs_ny - 1 } else { j };
  s.gs_level[cj * s.gs_nx + ci] ?? 0
}

fn ground_smooth(t: float) -> float {
  c = if t < 0.0 { 0.0 } else if t > 1.0 { 1.0 } else { t };
  c * c * (3.0 - 2.0 * c)
}

// @FR-HG-Terrace: each step up a smooth slope across its edge; the flat tops stay flat
// The smooth height at (x, y) units of the stepped map `s`: its lowest level's height, and for
// every step up a smooth rise of a storey across the step's edge, `hillside` wide and centred on
// it (a step up from below level 0, a stream's bank, `bank` wide).  Away from the edges the
// terraces stay flat at their storeys; across one, the ground climbs a storey without a cliff.
pub fn terrace_height(s: const GroundSteps, x: float, y: float, m: const GroundMeasures, lo: integer, hi: integer) -> float {
  i = floor((x - s.gs_x0) / s.gs_size ?? 0.0) as integer;
  j = floor((y - s.gs_y0) / s.gs_size ?? 0.0) as integer;
  h = (lo as float) * m.gm_storey;
  for step in lo + 1..hi + 1 {
    wide = if step <= 0 { m.gm_bank } else { m.gm_hillside };
    reach = (ceil((wide * 0.5) / s.gs_size ?? 1.0) as integer) + 1;
    inside = steps_level(s, i, j) >= step;
    near = wide;
    for dj in -reach..reach + 1 {
      for di in -reach..reach + 1 {
        if (steps_level(s, i + di, j + dj) >= step) == inside { continue; }
        // the distance from (x, y) to square (i + di, j + dj)
        ax = s.gs_x0 + ((i + di) as float) * s.gs_size;
        ay = s.gs_y0 + ((j + dj) as float) * s.gs_size;
        dx = if x < ax { ax - x } else if x > ax + s.gs_size { x - ax - s.gs_size } else { 0.0 };
        dy = if y < ay { ay - y } else if y > ay + s.gs_size { y - ay - s.gs_size } else { 0.0 };
        d = sqrt(dx * dx + dy * dy);
        if d < near { near = d; }
      }
    }
    signed = if inside { near } else { -near };
    h += m.gm_storey * ground_smooth(((signed + wide * 0.5) / wide) ?? 0.0);
  }
  h
}

// Every cell of the ground at the smooth height of the stepped map.
pub fn ground_terraces(g: Ground, s: const GroundSteps, m: const GroundMeasures, lo: integer, hi: integer) {
  for r in g.gr_r0..g.gr_r0 + g.gr_h {
    for q in g.gr_q0..g.gr_q0 + g.gr_w {
      (x, y) = ground_centre(g.gr_step, q, r);
      height_set(g.gr_heights, q, r, terrace_height(s, x, y, m, lo, hi));
    }
  }
}

// @FR-HG-Hill: a smooth round hill
// A round hill `height` units high, `radius` units across from its top at (x, y) to its foot:
// added to the ground, its sides a cosine, level at the top and at the foot.
pub fn ground_hill(g: Ground, x: float, y: float, radius: float, height: float) {
  for r in g.gr_r0..g.gr_r0 + g.gr_h {
    for q in g.gr_q0..g.gr_q0 + g.gr_w {
      (cx, cy) = ground_centre(g.gr_step, q, r);
      d = sqrt((cx - x) * (cx - x) + (cy - y) * (cy - y));
      if d >= radius { continue; }
      bump = height * 0.5 * (1.0 + cos((PI * d / radius) ?? 0.0));
      height_set(g.gr_heights, q, r, height_get(g.gr_heights, q, r) + bump);
    }
  }
}

// @FR-HG-Seat: a structure's footprint level, the ground round it blended back
// Seat a structure on the ground: its cells at height `z`, and the ground round it blended from
// that height back to its own over `m.gm_blend` from the footprint's edge (`hex_place::seat_blend`).
// Answers the lowest the ground was under the footprint, where its walls go down to.
pub fn ground_seat(g: Ground, cells: HexSet, z: float, m: const GroundMeasures) -> float {
  seat_blend(cells, g.gr_heights, z, m.gm_blend, g.gr_step)
}

// @FR-HG-Dig: a structure dug in, its bank centred on its straight sides
// Dig a structure into the ground (a stream's bed): the ground inside its sides `depth` units
// lower, across a bank `m.gm_bank` wide centred on its sides (`hex_draw::cells_outlines`, the same straight
// sides the view draws its edge along), shaped by a smoothstep.  So the bank runs along the sides,
// not along the cells' zigzag or the square map's staircase.
pub fn ground_dig(g: Ground, cells: HexSet, depth: float, m: const GroundMeasures) {
  unit = ground_unit(g.gr_step);
  sides: vector<(float, float, float, float)> = [];
  for o in cells_outlines(cells, 0) {
    n = len(o.co_corners);
    for i in 0..n {
      (x1, y1) = o.co_corners[(i + n - 1) % n ?? 0] ?? (0.0, 0.0);
      (x2, y2) = o.co_corners[i] ?? (0.0, 0.0);
      sides += [(x1 * unit, y1 * unit, x2 * unit, y2 * unit)];
    }
  }
  if len(sides) == 0 { return; }
  for r in g.gr_r0..g.gr_r0 + g.gr_h {
    for q in g.gr_q0..g.gr_q0 + g.gr_w {
      (x, y) = ground_centre(g.gr_step, q, r);
      d = sides_distance(sides, x, y);
      z = height_get(g.gr_heights, q, r);
      height_set(g.gr_heights, q, r, z - depth * ground_smooth((d + m.gm_bank * 0.5) / m.gm_bank ?? 0.0));
    }
  }
}

// How far (x, y) lies from the nearest of the sides, positive inside them (counted over all their
// loops), negative outside.
pub fn sides_distance(sides: const vector<(float, float, float, float)>, x: float, y: float) -> float {
  inside = false;
  near = 1000000.0;
  for sd in sides {
    (x1, y1, x2, y2) = sd;
    if (y1 > y) != (y2 > y) {
      cx = x1 + (y - y1) * (x2 - x1) / (y2 - y1) ?? x1;
      if x < cx { inside = !inside; }
    }
    dx = x2 - x1;
    dy = y2 - y1;
    l2 = dx * dx + dy * dy;
    t = if l2 > 0.0 { ((x - x1) * dx + (y - y1) * dy) / l2 ?? 0.0 } else { 0.0 };
    if t < 0.0 { t = 0.0; }
    if t > 1.0 { t = 1.0; }
    ex = x - x1 - t * dx;
    ey = y - y1 - t * dy;
    e = ex * ex + ey * ey;
    if e < near { near = e; }
  }
  far = sqrt(near) ?? 0.0;
  if inside { far } else { -far }
}

// ── cliffs ──────────────────────────────────────────────────────────────────

// A stretch of cliff (the ground's unit): a straight side of the ground of `level` and up, walked with that
// ground on its left from (ax, ay) to (bx, by); the ground drops a storey across it.
pub struct GroundCliff {
  pub gc_level: integer,
  pub gc_ax:    float,
  pub gc_ay:    float,
  pub gc_bx:    float,
  pub gc_by:    float,
}

// An area where fronts are cliffs, in units: x0 .. x1 east, y0 .. y1 north.
pub struct GroundBox {
  pub gb_x0: float,
  pub gb_y0: float,
  pub gb_x1: float,
  pub gb_y1: float,
}

// @FR-HG-Cliff: a cliff where the ground steps a level within a cliff area, along its straight sides
// The cliffs of ground whose cells stand at `levels` (lo .. hi): for each level, the straight
// sides of the cells at it and above (`hex_draw::cells_outlines`), the stretches of them inside the
// cliff areas.  Elsewhere the fronts slope.
pub fn ground_cliffs(levels: Labels, q0: integer, r0: integer, w: integer, h: integer,
                     lo: integer, hi: integer, areas: const vector<GroundBox>, step: float) -> vector<GroundCliff> {
  unit = ground_unit(step);
  out: vector<GroundCliff> = [];
  if len(areas) == 0 { return out; }
  for level in lo + 1..hi + 1 {
    cells = hexset_chunk(q0, r0, w, h);
    any = false;
    for r in r0..r0 + h {
      for q in q0..q0 + w {
        if label_get(levels, q, r) >= level {
          hexset_set(cells, q, r, true);
          any = true;
        }
      }
    }
    if !any { continue; }
    for o in cells_outlines(cells, 0) {
      n = len(o.co_corners);
      for i in 0..n {
        (x1, y1) = o.co_corners[(i + n - 1) % n ?? 0] ?? (0.0, 0.0);
        (x2, y2) = o.co_corners[i] ?? (0.0, 0.0);
        for a in areas {
          c = box_clip(x1 * unit, y1 * unit, x2 * unit, y2 * unit, a);
          if len(c) == 4 {
            ax = c[0] ?? 0.0;
            ay = c[1] ?? 0.0;
            bx = c[2] ?? 0.0;
            by = c[3] ?? 0.0;
            if (bx - ax) * (bx - ax) + (by - ay) * (by - ay) > 0.0001 {
              out += [GroundCliff { gc_level: level, gc_ax: ax, gc_ay: ay, gc_bx: bx, gc_by: by }];
            }
          }
        }
      }
    }
  }
  out
}

// The part of the segment from (ax, ay) to (bx, by) inside the box, as [ax, ay, bx, by]; empty
// when it misses.
fn box_clip(ax: float, ay: float, bx: float, by: float, b: const GroundBox) -> vector<float> {
  t0 = 0.0;
  t1 = 1.0;
  dx = bx - ax;
  dy = by - ay;
  for e in [(-dx, ax - b.gb_x0), (dx, b.gb_x1 - ax), (-dy, ay - b.gb_y0), (dy, b.gb_y1 - ay)] {
    (p, qv) = e;
    if p == 0.0 {
      if qv < 0.0 { return []; }
      continue;
    }
    t = (qv / p) ?? 0.0;
    if p < 0.0 { if t > t0 { t0 = t; } } else { if t < t1 { t1 = t; } }
  }
  if t0 >= t1 { return []; }
  [ax + dx * t0, ay + dy * t0, ax + dx * t1, ay + dy * t1]
}

// How far (x, y) lies outside the box (0 inside).
pub fn ground_box_distance(b: const GroundBox, x: float, y: float) -> float {
  dx = if x < b.gb_x0 { b.gb_x0 - x } else if x > b.gb_x1 { x - b.gb_x1 } else { 0.0 };
  dy = if y < b.gb_y0 { b.gb_y0 - y } else if y > b.gb_y1 { y - b.gb_y1 } else { 0.0 };
  sqrt(dx * dx + dy * dy)
}

// Make the ground's fronts sharp in the cliff areas: each cell at its level's height, `sharp`
// (its level's storey), within them, the smooth ground it has beyond `m.gm_blend` from them, blended
// between.
pub fn ground_sharpen(g: Ground, sharp: Heights, areas: const vector<GroundBox>, m: const GroundMeasures) {
  if len(areas) == 0 { return; }
  for r in g.gr_r0..g.gr_r0 + g.gr_h {
    for q in g.gr_q0..g.gr_q0 + g.gr_w {
      (x, y) = ground_centre(g.gr_step, q, r);
      d = 1000000.0;
      for a in areas {
        e = ground_box_distance(a, x, y);
        if e < d { d = e; }
      }
      if d >= m.gm_blend { continue; }
      t = ground_smooth(d / m.gm_blend ?? 1.0);
      z = height_get(g.gr_heights, q, r);
      zs = height_get(sharp, q, r);
      height_set(g.gr_heights, q, r, zs + (z - zs) * t);
    }
  }
}

// ── THE GROUND READ: A SMOOTH SURFACE THROUGH THE CELLS ────────────────────
//
// The cells hold one height each; the ground they stand for is smooth.  It is read as it is
// drawn: each cell a fan of six triangles from its centre, each corner of the fan at the MEAN
// height of the cells round it.  A corner is shared by three cells, so the three fans agree
// there and the surface has no crack — along a fan's rim, between two cells, both read the line
// between the same two corner heights.
//
// A corner on the window's rim has fewer than three cells in the window; it takes the mean of
// those it has, and a corner none of whose cells are in the window reads 0.

// @FR-HG-Surface: a corner's height is the mean of the cells round it
// The height of the corner at doubled coordinates (k, m): the mean of the cells round it that
// the ground's window holds, 0 when it holds none.  (k, m) must be a corner of the lattice.
pub fn ground_corner_height(g: const Ground, k: integer, m: integer) -> float {
  // the three cells whose corner this is, each a corner offset back from it; those the window
  // holds are kept in row order, then along the row, so the sum is taken in one order whoever
  // asks (no list is built: this is asked six times a cell when a ground is drawn)
  n = 0;
  qa = 0;
  ra = 0;
  qb = 0;
  rb = 0;
  qc = 0;
  rc = 0;
  for i in 0..6 {
    ck = k - corner_k(i);
    cm = m - corner_m(i);
    if ((cm % 3) + 3) % 3 != 0 { continue; }
    (q, r) = lattice_to_cell(ck, cm);
    if lattice_k(q, r) != ck || lattice_m(q, r) != cm { continue; }
    if q < g.gr_q0 || q >= g.gr_q0 + g.gr_w || r < g.gr_r0 || r >= g.gr_r0 + g.gr_h { continue; }
    if n == 0 {
      qa = q;
      ra = r;
    } else if n == 1 {
      if r < ra || (r == ra && q < qa) {
        qb = qa;
        rb = ra;
        qa = q;
        ra = r;
      } else {
        qb = q;
        rb = r;
      }
    } else if r < ra || (r == ra && q < qa) {
      qc = qb;
      rc = rb;
      qb = qa;
      rb = ra;
      qa = q;
      ra = r;
    } else if r < rb || (r == rb && q < qb) {
      qc = qb;
      rc = rb;
      qb = q;
      rb = r;
    } else {
      qc = q;
      rc = r;
    }
    n += 1;
  }
  if n == 0 { return 0.0; }
  sum = height_get(g.gr_heights, qa, ra);
  if n > 1 { sum += height_get(g.gr_heights, qb, rb); }
  if n > 2 { sum += height_get(g.gr_heights, qc, rc); }
  (sum / (n as float)) ?? 0.0
}

// The ground's height at (x, y), in its unit, as it is drawn: within the triangle of its cell's
// fan that holds the point, between the cell's centre and two of its corners.
pub fn ground_height_at(g: const Ground, x: float, y: float) -> float {
  (q, r) = ground_cell_near(g.gr_step, x, y);
  (cx, cy) = ground_centre(g.gr_step, q, r);
  k = lattice_k(q, r);
  m = lattice_m(q, r);
  // the corner the point lies past, going round anticlockwise from corner 0 (north): corner j
  // sits at 90 + 60 j degrees
  a = atan2(y - cy, x - cx) * 180.0 / PI;
  j0 = (((floor((a - 90.0) / 60.0) as integer?) % 6) + 6) % 6 ?? 0;
  j1 = (j0 + 1) % 6 ?? 0;
  kx = g.gr_step * 0.5;
  my = g.gr_step * 0.28867513459481287;
  ax = (corner_k(j0) as float) * kx;
  ay = (corner_m(j0) as float) * my;
  bx = (corner_k(j1) as float) * kx;
  by = (corner_m(j1) as float) * my;
  // barycentric in the triangle (centre, a, b)
  px = x - cx;
  py = y - cy;
  det = ax * by - ay * bx;
  wa = ((px * by - py * bx) / det) ?? 0.0;
  wb = ((ax * py - ay * px) / det) ?? 0.0;
  wc = 1.0 - wa - wb;
  wc * height_get(g.gr_heights, q, r) + wa * ground_corner_height(g, k + corner_k(j0), m + corner_m(j0))
    + wb * ground_corner_height(g, k + corner_k(j1), m + corner_m(j1))
}

// A cell's level: `levels`' label within the ground's window, 0 beyond it.
fn ground_level(g: const Ground, levels: const Labels, q: integer, r: integer) -> integer {
  if q < g.gr_q0 || q >= g.gr_q0 + g.gr_w || r < g.gr_r0 || r >= g.gr_r0 + g.gr_h { return 0; }
  label_get(levels, q, r)
}

// Corner (k, m), the j-th of a cell, as the mean of the cells round it on one side of the cliff
// of `level`: the cells lie away from it along corner offsets j, j + 2 and j + 4.
fn corner_on_side(g: const Ground, levels: const Labels, k: integer, m: integer, j: integer, level: integer,
                  high: boolean, own: float) -> float {
  sum = 0.0;
  n = 0;
  for t in 0..3 {
    i = (j + 2 * t) % 6 ?? 0;
    (q, r) = lattice_to_cell(k - corner_k(i), m - corner_m(i));
    if (ground_level(g, levels, q, r) >= level) == high {
      sum += height_get(g.gr_heights, q, r);
      n += 1;
    }
  }
  if n == 0 { own } else { (sum / (n as float)) ?? own }
}

// @FR-HG-Cliff: either side of a cliff its own surface, from the cells on that side only
// The ground's height at (x, y) on one side of a cliff of `level`: on its high side (`high`, the
// cells of `level` and up, by `levels`) or its low one.  Each corner is the mean of the cells
// round it on that side only, so the ground does not slope down the cliff.  A corner with no
// cell on that side, or the centre of a cell on the other, takes that side's own height: its
// level times `storey`.
pub fn ground_height_on(g: const Ground, levels: const Labels, x: float, y: float, level: integer, high: boolean,
                        storey: float) -> float {
  (q, r) = ground_cell_near(g.gr_step, x, y);
  (cx, cy) = ground_centre(g.gr_step, q, r);
  k = lattice_k(q, r);
  m = lattice_m(q, r);
  a = atan2(y - cy, x - cx) * 180.0 / PI;
  j0 = (((floor((a - 90.0) / 60.0) as integer?) % 6) + 6) % 6 ?? 0;
  j1 = (j0 + 1) % 6 ?? 0;
  own = (if high { level } else { level - 1 } as float) * storey;
  hc = if (ground_level(g, levels, q, r) >= level) == high { height_get(g.gr_heights, q, r) } else { own };
  ha = corner_on_side(g, levels, k + corner_k(j0), m + corner_m(j0), j0, level, high, own);
  hb = corner_on_side(g, levels, k + corner_k(j1), m + corner_m(j1), j1, level, high, own);
  kx = g.gr_step * 0.5;
  my = g.gr_step * 0.28867513459481287;
  ax = (corner_k(j0) as float) * kx;
  ay = (corner_m(j0) as float) * my;
  bx = (corner_k(j1) as float) * kx;
  by = (corner_m(j1) as float) * my;
  px = x - cx;
  py = y - cy;
  det = ax * by - ay * bx;
  wa = ((px * by - py * bx) / det) ?? 0.0;
  wb = ((ax * py - ay * px) / det) ?? 0.0;
  (1.0 - wa - wb) * hc + wa * ha + wb * hb
}

tests/01-hex-ground.loft

// Copyright (c) 2026 Jurjen Stellingwerff
// SPDX-License-Identifier: LGPL-3.0-or-later
// hex_ground — the conformance tests: the ground of a place, shaped by terraces, a hill, a seat,
// a dig and cliffs.  Contract only; the consumer's check is tile-world-game's town, which
// regenerates byte for byte from these routines.
use hex_ground::*;
use hex_field::*;
use hex_form::*;
use hex_draw::*;

// A box of cells about (0, 0), w by d hex steps.
fn box(w: integer, d: integer, reach: integer) -> HexSet {
  cells = hexset_chunk(0 - reach, 0 - reach, 2 * reach + 1, 2 * reach + 1);
  types = labels_new(0 - reach, 0 - reach, 2 * reach + 1, 2 * reach + 1);
  draw_floor(plan_new(0, 0, w, d, 0, false), cells, types, 1);
  cells
}

// The smallest step a `float` of this build can take at 1: about 2.2e-16 where it has 64 bits,
// 1.2e-7 where it has 32 (a 32-bit program).
fn step_at_one() -> float {
  e = 1.0;
  while 1.0 + e * 0.5 > 1.0 { e = e * 0.5; }
  e
}

// Whether two values are the same as far as this build's `float` can tell: within a thousand
// millionth, or within 64 of its steps at their size where that is wider — which it is in a
// 32-bit program, where a float holds about seven digits.
fn near(a: float, b: float) -> boolean {
  size = if a < 0.0 { -a } else { a };
  other = if b < 0.0 { -b } else { b };
  if other > size { size = other; }
  if size < 1.0 { size = 1.0; }
  room = 64.0 * step_at_one() * size;
  if room < 0.000000001 { room = 0.000000001; }
  a - b < room && b - a < room
}

fn main() {
  g = ground_new(-4, -4, 9, 9, 1.5, 3);
  assert(height_get(g.gr_heights, 0, 0) == 0.0 && label_get(g.gr_kinds, 2, -3) == 3, "flat ground of one kind");
}

// A centre and the cell nearest it are inverse, at a step of 1.5 (metres) and of sqrt(3) (the
// lattice's world unit, where it is `hex_form::cell_x` / `cell_y` and `hex_field::hex_at`).
fn test_a_centre_and_its_cell() {
  for step in [1.5, 1.7320508075688772] {
    for r in -9..10 {
      for q in -9..10 {
        (x, y) = ground_centre(step, q, r);
        (cq, cr) = ground_cell_near(step, x + 0.2, y - 0.2);
        assert(cq == q && cr == r, "step {step}: the cell near {q},{r}'s centre is it");
      }
    }
  }
  (x, y) = ground_centre(1.7320508075688772, 5, 3);
  assert(near(x, cell_x(5, 3)) && near(y, cell_y(5, 3)), "at sqrt(3) a centre is the lattice's own");
  (mx, my) = ground_centre(1.5, 5, 3);
  assert(mx == 8.25 && near(my, 9.0 * 0.4330127018922193), "at 1.5 a centre is 0.75 a doubled k: {mx} {my}");
  assert(near(ground_unit(1.5), 0.8660254037844386) && near(ground_unit(1.7320508075688772), 1.0), "the unit per world unit");
}

// Terraces: a map of two levels, the upper one east of x = 0.  Far up the terrace the ground is a
// storey high, far below it is 0, on the step's edge half way, and it only climbs between
// (@FR-HG-Terrace); the flat tops stay flat.
fn test_terraces_are_smooth_and_their_tops_flat() {
  level: vector<integer> = [];
  for _j in 0..20 { for i in 0..20 { level += [if i >= 10 { 1 } else { 0 }]; } }
  s = GroundSteps { gs_x0: -15.0, gs_y0: -15.0, gs_size: 1.5, gs_nx: 20, gs_ny: 20, gs_level: level };
  m = ground_measures(2.6, 6.0, 2.5, 2.5);
  assert(near(terrace_height(s, 8.0, 0.0, m, 0, 1), 2.6), "well up the terrace: a storey");
  assert(near(terrace_height(s, -8.0, 0.0, m, 0, 1), 0.0), "well below it: 0");
  assert(near(terrace_height(s, 0.0, 0.0, m, 0, 1), 1.3), "on the step's edge: half a storey, {terrace_height(s, 0.0, 0.0, m, 0, 1)}");
  last = -1.0;
  for i in 0..81 {
    h = terrace_height(s, -4.0 + (i as float) * 0.1, 0.0, m, 0, 1);
    assert(h >= last, "it only climbs going east");
    last = h;
  }
  g = ground_new(-12, -12, 25, 25, 1.5, 0);
  ground_terraces(g, s, m, 0, 1);
  (x, y) = ground_centre(1.5, 6, 0);
  assert(height_get(g.gr_heights, 6, 0) == terrace_height(s, x, y, m, 0, 1), "each cell at its centre's height");
  assert(near(height_get(g.gr_heights, 6, 0), 2.6) && near(height_get(g.gr_heights, 7, 3), 2.6), "the top flat");
}

// A hill: its height at its top, half of it half way down, nothing at its foot and beyond
// (@FR-HG-Hill); added to the ground that is there.
fn test_a_hill_is_a_cosine() {
  g = ground_new(-12, -12, 25, 25, 1.5, 0);
  for r in -12..13 { for q in -12..13 { height_set(g.gr_heights, q, r, 1.0); } }
  ground_hill(g, 0.0, 0.0, 6.0, 4.0);
  assert(near(height_get(g.gr_heights, 0, 0), 5.0), "its top: the ground's 1 and its 4");
  assert(near(height_get(g.gr_heights, 2, 0), 3.0), "3 from the top of a hill 6 across: half, {height_get(g.gr_heights, 2, 0)}");
  assert(near(height_get(g.gr_heights, 4, 0), 1.0) && near(height_get(g.gr_heights, 8, 5), 1.0), "its foot and beyond: the ground's own");
}

// A structure seated on a slope: its footprint level at its floor, the lowest the ground was
// under it answered, the ground far off untouched and the ground beside it between the two
// (@FR-HG-Seat).
fn test_a_seat_levels_the_footprint_and_blends() {
  g = ground_new(-20, -20, 41, 41, 1.5, 0);
  for r in -20..21 {
    for q in -20..21 {
      (x, _y) = ground_centre(1.5, q, r);
      height_set(g.gr_heights, q, r, 0.2 * x);
    }
  }
  cells = box(5, 4, 20);
  lowest = 1000.0;
  for r in -20..21 { for q in -20..21 { if hexset_get(cells, q, r) && height_get(g.gr_heights, q, r) < lowest { lowest = height_get(g.gr_heights, q, r); } } }
  m = ground_measures(2.6, 6.0, 2.5, 2.5);
  low = ground_seat(g, cells, 3.0, m);
  assert(low == lowest && low < 0.0, "the lowest the ground was under it: {low}");
  for r in -20..21 { for q in -20..21 { if hexset_get(cells, q, r) { assert(height_get(g.gr_heights, q, r) == 3.0, "the footprint at its floor"); } } }
  (fx, _fy) = ground_centre(1.5, 12, 0);
  assert(near(height_get(g.gr_heights, 12, 0), 0.2 * fx), "far off: the ground's own");
  (bx, _by) = ground_centre(1.5, 4, 0);
  beside = height_get(g.gr_heights, 4, 0);
  assert(!hexset_get(cells, 4, 0) && beside < 3.0 && beside > 0.2 * bx, "beside it: between its floor and the slope, {beside}");
}

// A bed dug: well inside its straight sides the ground lies `depth` lower, well outside it is
// untouched, and across a side it is half way down (@FR-HG-Dig) — the bank on the straight side,
// which `sides_distance` measures from.
fn test_a_dig_follows_the_straight_sides() {
  g = ground_new(-24, -24, 49, 49, 1.5, 0);
  cells = box(12, 6, 24);
  m = ground_measures(2.6, 6.0, 2.0, 2.5);
  ground_dig(g, cells, 2.0, m);
  assert(near(height_get(g.gr_heights, 0, 0), -2.0), "its middle: the depth down, {height_get(g.gr_heights, 0, 0)}");
  assert(near(height_get(g.gr_heights, 0, 12), 0.0) && near(height_get(g.gr_heights, 16, 0), 0.0), "well outside: untouched");
  sides: vector<(float, float, float, float)> = [];
  for o in cells_outlines(cells, 0) {
    n = len(o.co_corners);
    for i in 0..n {
      a = o.co_corners[(i + n - 1) % n ?? 0] ?? (0.0, 0.0);
      b = o.co_corners[i] ?? (0.0, 0.0);
      sides += [(a.0 * ground_unit(1.5), a.1 * ground_unit(1.5), b.0 * ground_unit(1.5), b.1 * ground_unit(1.5))];
    }
  }
  assert(len(sides) == 4, "a box's four straight sides");
  for r in -24..25 {
    for q in -24..25 {
      (x, y) = ground_centre(1.5, q, r);
      d = sides_distance(sides, x, y);
      z = height_get(g.gr_heights, q, r);
      if d > 1.0 { assert(near(z, -2.0), "a bank's half inside its sides: the bed"); }
      if d < -1.0 { assert(near(z, 0.0), "a bank's half outside them: the ground"); }
      if d > -1.0 && d < 1.0 { assert(z < 0.000000001 && z > -2.000000001, "on the bank: between"); }
      assert(hexset_get(cells, q, r) == (d > 0.0), "inside the sides is the bed's cells");
    }
  }
}

// Cliffs: a terrace a level up, a box of 12 by 6 hex steps.  With the whole of it a cliff area,
// its four straight sides come back as cliffs of level 1, the ground on their left; clipped to
// its east half, less of them; with no area, none (@FR-HG-Cliff).  And the ground made sharp:
// in the area each cell at its level's height, beyond the blend untouched.
fn test_cliffs_run_along_the_straight_sides() {
  cells = box(12, 6, 24);
  levels = labels_new(-24, -24, 49, 49);
  for r in -24..25 { for q in -24..25 { label_set(levels, q, r, if hexset_get(cells, q, r) { 1 } else { 0 }); } }
  all = [GroundBox { gb_x0: -100.0, gb_y0: -100.0, gb_x1: 100.0, gb_y1: 100.0 }];
  cs = ground_cliffs(levels, -24, -24, 49, 49, 0, 1, all, 1.5);
  assert(len(cs) == 4, "four cliffs round the terrace, got {len(cs)}");
  total = 0.0;
  for c in cs {
    assert(c.gc_level == 1, "each the cliff of level 1");
    // the terrace's middle on its left
    assert((c.gc_bx - c.gc_ax) * (0.0 - c.gc_ay) - (c.gc_by - c.gc_ay) * (0.0 - c.gc_ax) > 0.0, "the higher ground on its left");
    total += sqrt((c.gc_bx - c.gc_ax) * (c.gc_bx - c.gc_ax) + (c.gc_by - c.gc_ay) * (c.gc_by - c.gc_ay)) ?? 0.0;
  }
  east = [GroundBox { gb_x0: 0.0, gb_y0: -100.0, gb_x1: 100.0, gb_y1: 100.0 }];
  half = 0.0;
  for c in ground_cliffs(levels, -24, -24, 49, 49, 0, 1, east, 1.5) {
    assert(c.gc_ax >= -0.000000001 && c.gc_bx >= -0.000000001, "clipped to the area");
    half += sqrt((c.gc_bx - c.gc_ax) * (c.gc_bx - c.gc_ax) + (c.gc_by - c.gc_ay) * (c.gc_by - c.gc_ay)) ?? 0.0;
  }
  assert(near(half, total * 0.5), "the east half of a terrace about 0: half its cliffs, {half} of {total}");
  none: vector<GroundBox> = [];
  assert(len(ground_cliffs(levels, -24, -24, 49, 49, 0, 1, none, 1.5)) == 0, "no cliff area, no cliff");

  g = ground_new(-24, -24, 49, 49, 1.5, 0);
  for r in -24..25 { for q in -24..25 { height_set(g.gr_heights, q, r, 0.7); } }
  sharp = heights_new(-24, -24, 49, 49);
  for r in -24..25 { for q in -24..25 { height_set(sharp, q, r, 2.6 * (label_get(levels, q, r) as float)); } }
  area = [GroundBox { gb_x0: -6.0, gb_y0: -6.0, gb_x1: 6.0, gb_y1: 6.0 }];
  ground_sharpen(g, sharp, area, ground_measures(2.6, 6.0, 2.5, 2.5));
  assert(near(height_get(g.gr_heights, 0, 0), 2.6), "in the area, on the terrace: its level's height");
  assert(near(height_get(g.gr_heights, 12, 0), 0.7) && near(height_get(g.gr_heights, 0, 10), 0.7), "beyond the blend: the ground it had");
  (ex, ey) = ground_centre(1.5, 5, 0);
  assert(ground_box_distance(area[0]!, ex, ey) > 0.0 && height_get(g.gr_heights, 5, 0) > 0.7 && height_get(g.gr_heights, 5, 0) < 2.6,
         "just outside the area: blended between, {height_get(g.gr_heights, 5, 0)}");
}

// The ground read as a smooth surface: at a cell's centre its own height; at a corner the mean
// of the three cells round it; along the rim between two cells the same height from either
// side, so the fans leave no crack; and flat ground reads flat everywhere (@FR-HG-Surface).
fn test_the_ground_reads_as_one_smooth_surface() {
  g = ground_new(-10, -10, 21, 21, 1.5, 0);
  ground_hill(g, 1.0, -2.0, 11.0, 5.0);
  ground_hill(g, -6.0, 4.0, 5.0, -2.0);
  for r in -6..7 {
    for q in -6..7 {
      (cx, cy) = ground_centre(1.5, q, r);
      assert(near(ground_height_at(g, cx, cy), height_get(g.gr_heights, q, r)), "at {q},{r}'s centre: its height");
      k = lattice_k(q, r);
      m = lattice_m(q, r);
      for j in 0..6 {
        // corner j, and the three cells round it: this one and its neighbours across the two edges at j
        ck = k + corner_k(j);
        cm = m + corner_m(j);
        sum = 0.0;
        cells = 0;
        for rr in r - 1..r + 2 {
          for qq in q - 1..q + 2 {
            dk = ck - lattice_k(qq, rr);
            dm = cm - lattice_m(qq, rr);
            if 3 * dk * dk + dm * dm == 4 {
              sum += height_get(g.gr_heights, qq, rr);
              cells += 1;
            }
          }
        }
        assert(cells == 3, "a corner has three cells round it, got {cells}");
        want = sum / 3.0 ?? 0.0;
        assert(near(ground_corner_height(g, ck, cm), want), "corner {j} of {q},{r}: the mean of its three cells");
        x = (ck as float) * 0.75;
        y = (cm as float) * 0.4330127018922193;
        assert(near(ground_height_at(g, x, y), want), "and the surface passes through it");
        // the middle of the rim to the next corner, read a hair inside this cell and a hair beyond it
        j1 = (j + 1) % 6 ?? 0;
        mx = cx + ((corner_k(j) + corner_k(j1)) as float) * 0.375;
        my = cy + ((corner_m(j) + corner_m(j1)) as float) * 0.21650635094610965;
        inner = ground_height_at(g, cx + (mx - cx) * 0.999999, cy + (my - cy) * 0.999999);
        outer = ground_height_at(g, cx + (mx - cx) * 1.000001, cy + (my - cy) * 1.000001);
        assert(inner - outer < 0.00001 && outer - inner < 0.00001, "the rim of {q},{r} past corner {j}: no crack ({inner}, {outer})");
      }
    }
  }
  flat = ground_new(-6, -6, 13, 13, 1.7320508075688772, 0);
  for r in -6..7 { for q in -6..7 { height_set(flat.gr_heights, q, r, 4.25); } }
  for i in 0..40 {
    assert(near(ground_height_at(flat, -3.0 + (i as float) * 0.17, 2.0 - (i as float) * 0.11), 4.25), "flat ground reads flat, at any step");
  }
  rim = ground_new(0, 0, 3, 3, 1.5, 0);
  for r in 0..3 { for q in 0..3 { height_set(rim.gr_heights, q, r, 6.0); } }
  assert(near(ground_corner_height(rim, lattice_k(0, 0) + corner_k(3), lattice_m(0, 0) + corner_m(3)), 6.0), "a corner on the rim: the mean of the cells it has");
  assert(ground_corner_height(rim, lattice_k(9, 9) + corner_k(0), lattice_m(9, 9) + corner_m(0)) == 0.0, "a corner beyond the window: 0");
}

// Either side of a cliff its own surface: a terrace a storey up, its ground at 2.6 and the
// ground below at 0.  Read as one surface the ground would slope between them; read on the
// cliff's high side it is 2.6 right up to the edge, on its low side 0 (@FR-HG-Cliff).
fn test_either_side_of_a_cliff_its_own_surface() {
  cells = box(12, 6, 24);
  g = ground_new(-24, -24, 49, 49, 1.5, 0);
  levels = labels_new(-24, -24, 49, 49);
  for r in -24..25 {
    for q in -24..25 {
      up = hexset_get(cells, q, r);
      label_set(levels, q, r, if up { 1 } else { 0 });
      height_set(g.gr_heights, q, r, if up { 2.6 } else { 0.0 });
    }
  }
  sloped = 0;
  for i in 0..120 {
    x = -12.0 + (i as float) * 0.2;
    for y in [0.0, 1.1, -2.3] {
      hi = ground_height_on(g, levels, x, y, 1, true, 2.6);
      lo = ground_height_on(g, levels, x, y, 1, false, 2.6);
      assert(near(hi, 2.6), "the high side at {x},{y}: the terrace's height, {hi}");
      assert(near(lo, 0.0), "the low side at {x},{y}: the ground below, {lo}");
      one = ground_height_at(g, x, y);
      if one > 0.1 && one < 2.5 { sloped += 1; }
    }
  }
  assert(sloped > 0, "read as one surface, the ground slopes across the edge");
}