lay out rivers as the Rivers mod does

Every stored riverDistance column matches. Plates are built from 25
ocean samples per zone rather than a region map per zone, and the
ocean distance from a ring search that finds what the mod's BFS does,
so a plate costs 0.08 s; workers cache a few, as a wide view spans
several.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 18:40:53 +03:00
parent 5ad62524f1
commit 517d279c8d
10 changed files with 1257 additions and 38 deletions

809
src/rivers.sex Normal file
View File

@@ -0,0 +1,809 @@
;;; The Rivers mod (5.0.3) river layout, and sampling it per column.
;;;
;;; Rivers lays out a whole "plate" of 128 x 128 zones of 256 blocks
;;; at once: which zones are ocean, how far each land zone is from the
;;; ocean, and then rivers grown uphill from the coast, node by node,
;;; from one LCGRandom(0) positioned at the plate. The world seed only
;;; enters through the ocean map, sampled without forced land.
;;;
;;; Positions are plate-local doubles, as in the mod. The order of
;;; every RNG call is the mod's: it is what the layout depends on.
(include stdlib.h string.h math.h)
(import maps)
(import lcg)
(import noise)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(pub record river-config
((min-fork-angle int) (fork-variation int) (normal-angle int)
(min-size float) (max-size float) (min-nodes int) (max-nodes int) (river-growth float)
(downhill-error int) (min-length int) (length-variation int) (zone-size int)
(zones-in-region int) (river-spawn-chance float) (river-split-chance float)
(lake-chance float) (segments-in-river int) (segment-offset double) (base-depth double)
(river-depth double) (river-padding-blocks int) (river-octaves int)
(river-frequency float) (river-lacunarity float) (river-gain float)
(river-distortion-strength int) (max-valley-width double) (ocean-threshold float)
(valley-strength-max float) (valley-strength-min float) (noise-expansion float)
(height-boost int) (top-factor float)))
(pub fn river-config/defaults () river-config
(var c river-config)
(memset (& c) 0 (sizeof c))
(= (. c min-fork-angle) 10)
(= (. c fork-variation) 35)
(= (. c normal-angle) 20)
(= (. c valley-strength-max) 1)
(= (. c valley-strength-min) (cast 0.4 float))
(= (. c noise-expansion) (cast 1.5 float))
(= (. c river-padding-blocks) 128)
(= (. c min-size) 14)
(= (. c max-size) 50)
(= (. c min-nodes) 8)
(= (. c max-nodes) 20)
(= (. c river-growth) 3)
(= (. c downhill-error) 1)
(= (. c min-length) 150)
(= (. c length-variation) 200)
(= (. c zone-size) 256)
(= (. c zones-in-region) 128)
(= (. c river-spawn-chance) (cast 0.2 float))
(= (. c river-split-chance) (cast 0.35 float))
(= (. c lake-chance) (cast 0.1 float))
(= (. c segments-in-river) 3)
(= (. c segment-offset) 40)
(= (. c base-depth) 0.1)
(= (. c river-depth) 0.022)
(= (. c height-boost) 8)
(= (. c top-factor) 1)
(= (. c river-octaves) 3)
(= (. c river-frequency) (cast 0.0075 float))
(= (. c river-lacunarity) 3)
(= (. c river-gain) (cast 0.3 float))
(= (. c river-distortion-strength) 10)
(= (. c max-valley-width) 150)
(= (. c ocean-threshold) 30)
(return c))
(fn json-get ((o (* cJSON)) (key (* const char)) (out (* double))) bool
(var v (* cJSON) (cJSON-GetObjectItem o key))
(if (! (cJSON-IsNumber v))
(return false))
(= (* out) (cJSON-GetNumberValue v))
(return true))
;;; ModConfig/rivers.json over the defaults.
(pub fn river-config/load ((path (* const char)) (c (* river-config))) bool
(var json (* cJSON) (json-load path))
(if (! json)
(return false))
(var v double)
(if (json-get json "minForkAngle" (& v)) (= (. c min-fork-angle) (cast v int)))
(if (json-get json "forkVariation" (& v)) (= (. c fork-variation) (cast v int)))
(if (json-get json "normalAngle" (& v)) (= (. c normal-angle) (cast v int)))
(if (json-get json "valleyStrengthMax" (& v)) (= (. c valley-strength-max) (cast v float)))
(if (json-get json "valleyStrengthMin" (& v)) (= (. c valley-strength-min) (cast v float)))
(if (json-get json "noiseExpansion" (& v)) (= (. c noise-expansion) (cast v float)))
(if (json-get json "riverPaddingBlocks" (& v)) (= (. c river-padding-blocks) (cast v int)))
(if (json-get json "minSize" (& v)) (= (. c min-size) (cast v float)))
(if (json-get json "maxSize" (& v)) (= (. c max-size) (cast v float)))
(if (json-get json "minNodes" (& v)) (= (. c min-nodes) (cast v int)))
(if (json-get json "maxNodes" (& v)) (= (. c max-nodes) (cast v int)))
(if (json-get json "riverGrowth" (& v)) (= (. c river-growth) (cast v float)))
(if (json-get json "downhillError" (& v)) (= (. c downhill-error) (cast v int)))
(if (json-get json "minLength" (& v)) (= (. c min-length) (cast v int)))
(if (json-get json "lengthVariation" (& v)) (= (. c length-variation) (cast v int)))
(if (json-get json "zoneSize" (& v)) (= (. c zone-size) (cast v int)))
(if (json-get json "zonesInRegion" (& v)) (= (. c zones-in-region) (cast v int)))
(if (json-get json "riverSpawnChance" (& v)) (= (. c river-spawn-chance) (cast v float)))
(if (json-get json "riverSplitChance" (& v)) (= (. c river-split-chance) (cast v float)))
(if (json-get json "lakeChance" (& v)) (= (. c lake-chance) (cast v float)))
(if (json-get json "segmentsInRiver" (& v)) (= (. c segments-in-river) (cast v int)))
(if (json-get json "segmentOffset" (& v)) (= (. c segment-offset) v))
(if (json-get json "baseDepth" (& v)) (= (. c base-depth) v))
(if (json-get json "riverDepth" (& v)) (= (. c river-depth) v))
(if (json-get json "heightBoost" (& v)) (= (. c height-boost) (cast v int)))
(if (json-get json "topFactor" (& v)) (= (. c top-factor) (cast v float)))
(if (json-get json "riverOctaves" (& v)) (= (. c river-octaves) (cast v int)))
(if (json-get json "riverFrequency" (& v)) (= (. c river-frequency) (cast v float)))
(if (json-get json "riverLacunarity" (& v)) (= (. c river-lacunarity) (cast v float)))
(if (json-get json "riverGain" (& v)) (= (. c river-gain) (cast v float)))
(if (json-get json "riverDistortionStrength" (& v))
(= (. c river-distortion-strength) (cast v int)))
(if (json-get json "maxValleyWidth" (& v)) (= (. c max-valley-width) v))
(if (json-get json "oceanThreshold" (& v)) (= (. c ocean-threshold) (cast v float)))
(cJSON-Delete json)
(return true))
;;; Geometry -----------------------------------------------------------
(pub record vec2 ((x double) (y double)))
(fn v2 ((x double) (y double)) vec2 (return #(vec2 : x y)))
(fn v-add ((a vec2) (b vec2)) vec2 (return (v2 (+ (. a x) (. b x)) (+ (. a y) (. b y)))))
(fn v-sub ((a vec2) (b vec2)) vec2 (return (v2 (- (. a x) (. b x)) (- (. a y) (. b y)))))
(fn v-mul ((a vec2) (f double)) vec2 (return (v2 (* (. a x) f) (* (. a y) f))))
(fn v-eq ((a vec2) (b vec2)) bool (return (&& (== (. a x) (. b x)) (== (. a y) (. b y)))))
;;; OpenTK's Normalized: scaled by the reciprocal of the length, so a
;;; zero vector comes out NaN.
(fn v-normalized ((a vec2)) vec2
(var scale double (/ 1.0 (sqrt (+ (* (. a x) (. a x)) (* (. a y) (. a y))))))
(return (v2 (* (. a x) scale) (* (. a y) scale))))
(fn degrees-to-normal ((degrees double)) vec2
(var radians double (* degrees (/ M-PI 180)))
(return (v2 (cos radians) (sin radians))))
(fn normal-to-degrees ((n vec2)) double
(return (* (atan2 (. n y) (. n x)) (/ 180 M-PI))))
;;; RiverMath.GetProjection: how far along START..END POINT projects,
;;; clamped to 0..1.
(fn projection ((p vec2) (start vec2) (end vec2)) float
(var dx double (- (. end x) (. start x)))
(var dy double (- (. end y) (. start y)))
(var v double (+ (* (- (. p x) (. start x)) dx) (* (- (. p y) (. start y)) dy)))
(/= v (+ (* dx dx) (* dy dy)))
(return (cast (if (< v 0) 0 (if (> v 1) 1 v)) float)))
(fn distance-to-line ((p vec2) (s vec2) (e vec2)) double
(if (<= (+ (* (- (. s x) (. e x)) (- (. p x) (. e x))) (* (- (. s y) (. e y)) (- (. p y) (. e y)))) 0)
(return (sqrt (+ (* (- (. p x) (. e x)) (- (. p x) (. e x)))
(* (- (. p y) (. e y)) (- (. p y) (. e y)))))))
(if (<= (+ (* (- (. e x) (. s x)) (- (. p x) (. s x))) (* (- (. e y) (. s y)) (- (. p y) (. s y)))) 0)
(return (sqrt (+ (* (- (. p x) (. s x)) (- (. p x) (. s x)))
(* (- (. p y) (. s y)) (- (. p y) (. s y)))))))
(var num double (fabs (+ (- (* (- (. e y) (. s y)) (. p x)) (* (- (. e x) (. s x)) (. p y)))
(- (* (. e x) (. s y)) (* (. e y) (. s x))))))
(return (/ num (sqrt (+ (* (- (. s y) (. e y)) (- (. s y) (. e y)))
(* (- (. s x) (. e x)) (- (. s x) (. e x))))))))
(fn lines-intersect ((sa vec2) (ea vec2) (sb vec2) (eb vec2)) bool
(var c1 bool (> (* (- (. eb y) (. sa y)) (- (. sb x) (. sa x)))
(* (- (. sb y) (. sa y)) (- (. eb x) (. sa x)))))
(var c2 bool (> (* (- (. eb y) (. ea y)) (- (. sb x) (. ea x)))
(* (- (. sb y) (. ea y)) (- (. eb x) (. ea x)))))
(var c3 bool (> (* (- (. sb y) (. sa y)) (- (. ea x) (. sa x)))
(* (- (. ea y) (. sa y)) (- (. sb x) (. sa x)))))
(var c4 bool (> (* (- (. eb y) (. sa y)) (- (. ea x) (. sa x)))
(* (- (. ea y) (. sa y)) (- (. eb x) (. sa x)))))
(return (&& (!= c1 c2) (!= c3 c4))))
(pub record envelope ((min-x double) (min-y double) (max-x double) (max-y double)))
(fn intersects ((a (* const envelope)) (b (* const envelope))) bool
(return (&& (<= (. a min-x) (. b max-x)) (<= (. a min-y) (. b max-y))
(>= (. a max-x) (. b min-x)) (>= (. a max-y) (. b min-y)))))
;;; .NET 10 converts out-of-range doubles to int by saturating, and NaN
;;; to 0. A zero-length river direction relies on it.
(fn saturating-int ((v double)) int
(if (!= v v) (return 0))
(if (<= v -2147483648.0) (return INT32_MIN))
(if (>= v 2147483647.0) (return INT32_MAX))
(return (cast v int)))
;;; The layout --------------------------------------------------------
(pub record river-node
((start vec2) (end vec2) (parent int) (river int) (end-size float) (start-size float)
(is-end bool) (first-segment int) (segment-count int) (is-lake bool) (bounds envelope)))
(pub record river-segment
((start vec2) (end vec2) (mid vec2) (node int) (parent int)
(first-child int) (last-child int) (next-sibling int) (parent-invalid bool)
(bounds envelope)))
(pub record river ((start vec2) (first-node int) (alive bool)))
;;; Nodes of one river, in order: `river-nodes' threads them.
(pub record request ((angle double) (start vec2) (stage int) (parent int) (river int) (error int)))
(pub define PLATE-GRID 64)
(pub record river-plate
((config river-config) (px int) (pz int)
(ocean (* bool)) (ocean-distance (* double))
(nodes (* river-node)) (node-count int) (node-cap int)
(node-next (* int))
(segments (* river-segment)) (segment-count int) (segment-cap int)
(rivers (* river)) (river-count int) (river-cap int) (river-last (* int))
(queue (* request)) (queue-head int) (queue-tail int) (queue-cap int)
(rng lcg)
;; A 64 x 64 grid over the plate, each cell listing the segments
;; whose sampling bounds touch it.
(grid-start (* int)) (grid-items (* int))))
(fn zone-index ((p (* const river-plate)) (x int) (z int)) int
(return (+ (* z (. p config zones-in-region)) x)))
(fn zone-center ((p (* const river-plate)) (x int) (z int)) vec2
(var size int (. p config zone-size))
(return (v2 (+ (* x size) (/ size 2)) (+ (* z size) (/ size 2)))))
(fn zone-at ((p (* const river-plate)) (x double) (z double)) int
(var n int (. p config zones-in-region))
(var zx int (saturating-int (fmin (fmax (/ x (. p config zone-size)) 0) (- n 1))))
(var zz int (saturating-int (fmin (fmax (/ z (. p config zone-size)) 0) (- n 1))))
;; Math.Clamp keeps NaN, which then converts to 0.
(if (!= x x) (= zx 0))
(if (!= z z) (= zz 0))
(return (zone-index p zx zz)))
(fn plate-size ((p (* const river-plate))) int
(return (* (. p config zone-size) (. p config zones-in-region))))
(fn within ((p (* const river-plate)) (v vec2) (padding double)) bool
(var size double (plate-size p))
(return (&& (>= (. v x) padding) (<= (. v x) (- size padding))
(>= (. v y) padding) (<= (. v y) (- size padding)))))
;;; SetZoneOceanicity: the blurred ocean map, without forced land, at
;;; the chunk of the zone's centre, scaled by world height.
(fn zone-is-ocean ((p (* const river-plate)) (oceans (* ocean-layer)) (size-y int) (x int) (z int)) bool
(var size int (. p config zone-size))
(var world-x int (+ (* (. p px) (plate-size p)) (* x size) (/ size 2)))
(var world-z int (+ (* (. p pz) (plate-size p)) (* z size) (/ size 2)))
(var value int (.blurred-at oceans (/ world-x 32) (/ world-z 32)))
(var factor float (* (/ size-y 256) (cast 0.33333 float)))
(return (> (cast (* (cast value float) factor) double) (. p config ocean-threshold))))
;;; The distance from each land zone's centre to the nearest ocean
;;; zone's, capped at two plates. The mod finds it with a pruned BFS
;;; that reaches exactly the nearest ocean; rings around the zone find
;;; the same one without visiting every zone.
(fn ocean-distances ((p (* river-plate))) void
(var n int (. p config zones-in-region))
(var cap double (* 2 (plate-size p)))
(for (var x int 0) (< x n) (++ x)
(for (var z int 0) (< z n) (++ z)
(var i int (zone-index p x z))
(if [(. p ocean) i]
(do (= [(. p ocean-distance) i] -1) (continue)))
(var best i64 INT64_MAX)
(for (var r int 1) (< r n) (++ r)
;; Nothing in ring r is closer than r zones.
(if (<= (* (cast r i64) r) best)
(for (var dx int (- r)) (<= dx r) (++ dx)
(for (var dz int (- r)) (<= dz r) (++ dz)
(if (&& (!= (abs dx) r) (!= (abs dz) r))
(continue))
(var ox int (+ x dx))
(var oz int (+ z dz))
(if (|| (< ox 0) (>= ox n) (< oz 0) (>= oz n))
(continue))
(if [(. p ocean) (zone-index p ox oz)]
(do
(var d2 i64 (+ (* (cast dx i64) dx) (* (cast dz i64) dz)))
(if (< d2 best) (= best d2))))))
(break)))
;; Zone centres are whole multiples of the zone size apart, so
;; this is exactly the mod's sqrt(pow(dx, 2) + pow(dz, 2)).
(var size double (. p config zone-size))
(var d double (if (== best INT64_MAX) INFINITY (sqrt (* (cast best double) size size))))
(= [(. p ocean-distance) i] (fmin d cap)))))
;;; Growing storage -----------------------------------------------------
(fn grow-array ((data (* void)) (cap (* int)) (need int) (item size-t)) (* void)
(if (< need (* cap))
(return data))
(var new-cap int (if (> (* cap) 0) (* 2 (* cap)) 64))
(while (<= new-cap need) (*= new-cap 2))
(= (* cap) new-cap)
(return (realloc data (* (cast new-cap size-t) item))))
(fn add-segment ((p (* river-plate)) (start vec2) (end vec2) (node int)) int
(= (. p segments) (grow-array (. p segments) (& (. p segment-cap)) (. p segment-count)
(sizeof river-segment)))
(var s (* river-segment) (& [(. p segments) (. p segment-count)]))
(memset s 0 (sizeof river-segment))
(= (. s start) start)
(= (. s end) end)
;; startPos + ((endPos - startPos) / 2), as OpenTK divides
(= (. s mid) (v-add start (v2 (/ (- (. end x) (. start x)) 2) (/ (- (. end y) (. start y)) 2))))
(= (. s node) node)
(= (. s parent) -1)
(= (. s first-child) -1)
(= (. s last-child) -1)
(= (. s next-sibling) -1)
(++ (. p segment-count))
(return (- (. p segment-count) 1)))
(fn add-child ((p (* river-plate)) (parent int) (child int)) void
(var ps (* river-segment) (& [(. p segments) parent]))
(if (< (. ps last-child) 0)
(= (. ps first-child) child)
(= (. [(. p segments) (. ps last-child)] next-sibling) child))
(= (. ps last-child) child)
(= (. [(. p segments) child] parent) parent))
(fn node-envelope ((p (* const river-plate)) (start vec2) (end vec2)) envelope
(var pad double (. p config river-padding-blocks))
(return #(envelope : (- (fmin (. start x) (. end x)) pad) (- (fmin (. start y) (. end y)) pad)
(+ (fmax (. start x) (. end x)) pad) (+ (fmax (. start y) (. end y)) pad))))
;;; new RiverNode(...) without custom segments: three segments, the
;;; inner joints pushed sideways by up to segmentOffset at random.
(fn add-node ((p (* river-plate)) (start vec2) (end vec2) (river int) (parent int)) int
(= (. p nodes) (grow-array (. p nodes) (& (. p node-cap)) (. p node-count) (sizeof river-node)))
(var cap int (. p node-cap))
(= (. p node-next) (realloc (. p node-next) (* (cast cap size-t) (sizeof int))))
(var index int (. p node-count))
(++ (. p node-count))
(var n (* river-node) (& [(. p nodes) index]))
(memset n 0 (sizeof river-node))
(= (. n start) start)
(= (. n end) end)
(= (. n parent) parent)
(= (. n river) river)
(= (. n end-size) 0)
(= (. n start-size) 1)
(= (. n is-end) true)
(= (. n bounds) (node-envelope p start end))
(= [(. p node-next) index] -1)
(var count int (. p config segments-in-river))
(var dir vec2 (v-normalized (v-sub end start)))
(var side vec2 (v2 (- (. dir y)) (. dir x)))
(= (. n first-segment) (. p segment-count))
(= (. n segment-count) count)
(var previous-end vec2 start)
(for (var i int 0) (< i count) (++ i)
(var r double (.next-double (& (. p rng))))
(var offset double (+ (- (. p config segment-offset)) (* (* r (. p config segment-offset)) 2)))
(var seg-end vec2 end)
(if (!= i (- count 1))
(do
(var t double (/ (cast (+ i 1) double) count))
(= seg-end (v2 (+ (. start x) (* (- (. end x) (. start x)) t))
(+ (. start y) (* (- (. end y) (. start y)) t))))
(+= (. seg-end x) (* offset (. side x)))
(+= (. seg-end y) (* offset (. side y)))))
(add-segment p previous-end seg-end index)
(= previous-end seg-end))
;; ConnectSegments
(var first int (. n first-segment))
(for (var i int 0) (< i count) (++ i)
(if (> i 0)
(add-child p (+ first i -1) (+ first i))
(>= parent 0)
(add-child p (+ (. [(. p nodes) parent] first-segment)
(. [(. p nodes) parent] segment-count) -1)
first)))
;; ValidateSegments
(for (var i int 0) (< i count) (++ i)
(var s (* river-segment) (& [(. p segments) (+ first i)]))
(if (== i 0)
(do
(if (< parent 0)
(do (= (. s parent-invalid) true) (continue)))
(var pn (* river-node) (& [(. p nodes) parent]))
(var last (* river-segment)
(& [(. p segments) (+ (. pn first-segment) (. p config segments-in-river) -1)]))
(var pr float (projection (. s start) (. s mid) (. last mid)))
(if (|| (< pr (cast 0.2 float)) (> pr (cast 0.8 float)))
(= (. s parent-invalid) true))
(continue)))
(var pr float (projection (. s start) (. s mid) (. [(. p segments) (+ first i -1)] mid)))
(if (|| (< pr (cast 0.2 float)) (> pr (cast 0.8 float)))
(= (. s parent-invalid) true)))
(return index))
(fn river-append-node ((p (* river-plate)) (river int) (node int)) void
(var last int [(. p river-last) river])
(if (< last 0)
(= (. [(. p rivers) river] first-node) node)
(= [(. p node-next) last] node))
(= [(. p river-last) river] node))
(fn enqueue ((p (* river-plate)) (r request)) void
(= (. p queue) (grow-array (. p queue) (& (. p queue-cap)) (. p queue-tail) (sizeof request)))
(= [(. p queue) (. p queue-tail)] r)
(++ (. p queue-tail)))
;;; RiverRegion.GenerateRiver: one node of a river, or false where the
;;; mod refuses it. The RNG draws are the mod's, in its order.
(fn generate-river ((p (* river-plate)) (angle double) (start vec2) (stage int) (parent int)
(river int) (error int)) bool
(var c (* river-config) (& (. p config)))
(if (> stage (. c max-nodes))
(return false))
(var normal vec2 (degrees-to-normal angle))
(var length int (+ (. c min-length) (.next-int (& (. p rng)) (. c length-variation))))
(var end vec2 (v-add start (v-mul normal length)))
(var intersecting bool false)
(var probe vec2 (v-add (v-mul (v-sub end start) 0.5) end))
(for (var n int (. [(. p rivers) river] first-node)) (>= n 0) (= n [(. p node-next) n])
(var other (* river-node) (& [(. p nodes) n]))
(if (|| (v-eq start (. other end)) (v-eq start (. other start)))
(continue))
(if (lines-intersect start probe (. other start) (. other end))
(do (= intersecting true) (break))))
(var padding double (+ (+ (. c segment-offset) (. c max-valley-width)) (. c max-size)))
(if (! (&& (within p start padding) (within p end padding)))
(= intersecting true))
(var start-dist double [(. p ocean-distance) (zone-at p (. start x) (. start y))])
(var end-zone int (zone-at p (. end x) (. end y)))
(var end-dist double [(. p ocean-distance) end-zone])
(if (> start-dist end-dist)
(do
(if (== error 0) (= intersecting true))
(-- error)))
(if (&& [(. p ocean) end-zone] (> stage 2))
(= intersecting true))
(if intersecting
(return false))
(var bounds envelope (node-envelope p start end))
(for (var n int 0) (< n (. p node-count)) (++ n)
(var other (* river-node) (& [(. p nodes) n]))
(if (&& (! (. other is-lake)) (intersects (& (. other bounds)) (& bounds))
(!= (. other river) river))
(return false)))
(var node int (add-node p start end river parent))
(river-append-node p river node)
(if (>= parent 0)
(= (. [(. p nodes) parent] is-end) false))
(var split float (.next-float (& (. p rng))))
(if (&& (< split (. c river-split-chance)) (>= parent 0))
(do
(var a1 double (+ angle (+ (. c min-fork-angle) (.next-int (& (. p rng)) (. c fork-variation)))))
(var a2 double (- angle (+ (. c min-fork-angle) (.next-int (& (. p rng)) (. c fork-variation)))))
(enqueue p #(request : a1 end (+ stage 1) node river error))
(enqueue p #(request : a2 end (+ stage 1) node river error)))
(do
(var sign int 0)
(while (== sign 0)
(= sign (+ -1 (.next-int (& (. p rng)) 3))))
(var a1 double (- angle (* (.next-int (& (. p rng)) (. c normal-angle)) sign)))
(enqueue p #(request : a1 end (+ stage 1) node river error))))
(return true))
;;; FindHighestZone: up to HOPS steps to the neighbour (or self) with
;;; the greatest ocean distance, ties to the first in x, then z order.
(fn find-highest ((p (* const river-plate)) (x int) (z int) (hops int)) int
(var n int (. p config zones-in-region))
(var best-x int x)
(var best-z int z)
(var best double (- INFINITY))
(var found bool false)
(for (var dx int -1) (<= dx 1) (++ dx)
(for (var dz int -1) (<= dz 1) (++ dz)
(var ox int (+ x dx))
(var oz int (+ z dz))
(if (|| (< ox 0) (> ox (- n 1)) (< oz 0) (> oz (- n 1)))
(continue))
(var d double [(. p ocean-distance) (zone-index p ox oz)])
(if (|| (! found) (> d best))
(do (= best d) (= best-x ox) (= best-z oz) (= found true)))))
(if (|| (&& (== best-x x) (== best-z z)) (== hops 0))
(return (zone-index p x z)))
(return (find-highest p best-x best-z (- hops 1))))
(fn assign-size ((p (* river-plate)) (node int) (end-size float)) void
(var c (* river-config) (& (. p config)))
(while (>= node 0)
(var n (* river-node) (& [(. p nodes) node]))
(if (> (. n start-size) end-size)
(return))
(= (. n end-size) end-size)
(= (. n start-size) (+ end-size (. c river-growth)))
(= (. n start-size) (fmaxf (. n start-size) (. c min-size)))
(= (. n start-size) (fminf (. n start-size) (. c max-size)))
(= end-size (. n start-size))
(= node (. n parent))))
(fn add-lake ((p (* river-plate)) (river int) (parent int) (angle double)) void
(var c (* river-config) (& (. p config)))
(var pn (* river-node) (& [(. p nodes) parent]))
(= (. pn end-size) (/ (. c min-size) 2))
(var size int (+ (.next-int (& (. p rng)) (- 75 50)) 50))
(var end vec2 (v-add (. pn end) (v-mul (degrees-to-normal angle) 100)))
(var padding double (+ (. c max-valley-width) size))
(if (! (&& (within p (. pn end) padding) (within p end padding)))
(return))
(var start vec2 (. pn end))
(var parent-start-size float (. pn end-size))
(var last-segment int (+ (. pn first-segment) (. c segments-in-river) -1))
(= (. p nodes) (grow-array (. p nodes) (& (. p node-cap)) (. p node-count) (sizeof river-node)))
(= (. p node-next) (realloc (. p node-next) (* (cast (. p node-cap) size-t) (sizeof int))))
(var index int (. p node-count))
(++ (. p node-count))
(var n (* river-node) (& [(. p nodes) index]))
(memset n 0 (sizeof river-node))
(= (. n start) start)
(= (. n end) end)
(= (. n parent) -1)
(= (. n river) river)
(= (. n start-size) parent-start-size)
(= (. n end-size) size)
(= (. n is-end) true)
(= (. n is-lake) true)
(= (. n bounds) (node-envelope p start end))
(= [(. p node-next) index] -1)
(var s int (add-segment p start end index))
(= (. [(. p nodes) index] first-segment) s)
(= (. [(. p nodes) index] segment-count) 1)
(add-child p last-segment s)
(= (. [(. p segments) s] parent-invalid) true)
(= (. [(. p segments) last-segment] parent-invalid) false)
(river-append-node p river index))
(fn river-node-count ((p (* const river-plate)) (river int)) int
(var count int 0)
(for (var n int (. [(. p rivers) river] first-node)) (>= n 0) (= n [(. p node-next) n])
(++ count))
(return count))
;;; RiverSegment.InitializeBounds: the segment, its parent's and
;;; children's midpoints, widened by the valley and the river.
(fn segment-bounds ((p (* river-plate)) (i int)) void
(var s (* river-segment) (& [(. p segments) i]))
(var lo vec2 (v2 (fmin (. s start x) (. s end x)) (fmin (. s start y) (. s end y))))
(var hi vec2 (v2 (fmax (. s start x) (. s end x)) (fmax (. s start y) (. s end y))))
(if (>= (. s parent) 0)
(do
(var m vec2 (. [(. p segments) (. s parent)] mid))
(= lo (v2 (fmin (. lo x) (. m x)) (fmin (. lo y) (. m y))))
(= hi (v2 (fmax (. hi x) (. m x)) (fmax (. hi y) (. m y))))))
(for (var c int (. s first-child)) (>= c 0) (= c (. [(. p segments) c] next-sibling))
(var m vec2 (. [(. p segments) c] mid))
(= lo (v2 (fmin (. lo x) (. m x)) (fmin (. lo y) (. m y))))
(= hi (v2 (fmax (. hi x) (. m x)) (fmax (. hi y) (. m y)))))
(var n (* river-node) (& [(. p nodes) (. s node)]))
(var size float (fmaxf (. n start-size) (. n end-size)))
(var pad double (+ (. p config max-valley-width) size))
(= (. s bounds) #(envelope : (- (. lo x) pad) (- (. lo y) pad) (+ (. hi x) pad) (+ (. hi y) pad))))
(fn grid-cell ((p (* const river-plate)) (v double)) int
(var cell double (/ (cast (plate-size p) double) PLATE-GRID))
(var i int (saturating-int (floor (/ v cell))))
(return (if (< i 0) 0 (if (>= i PLATE-GRID) (- PLATE-GRID 1) i))))
(fn build-grid ((p (* river-plate)) (live (* bool))) void
(var cells int (* PLATE-GRID PLATE-GRID))
(= (. p grid-start) (calloc (+ cells 1) (sizeof int)))
(for (var pass int 0) (< pass 2) (++ pass)
(var fill (* int) (calloc cells (sizeof int)))
(for (var i int 0) (< i (. p segment-count)) (++ i)
(if (! [live i])
(continue))
(var b (* envelope) (& (. [(. p segments) i] bounds)))
(for (var gx int (grid-cell p (. b min-x))) (<= gx (grid-cell p (. b max-x))) (++ gx)
(for (var gz int (grid-cell p (. b min-y))) (<= gz (grid-cell p (. b max-y))) (++ gz)
(var cell int (+ (* gz PLATE-GRID) gx))
(if (== pass 0)
(++ [(. p grid-start) (+ cell 1)])
(do
(= [(. p grid-items) (+ [(. p grid-start) cell] [fill cell])] i)
(++ [fill cell]))))))
(if (== pass 0)
(do
(for (var c int 0) (< c cells) (++ c)
(+= [(. p grid-start) (+ c 1)] [(. p grid-start) c]))
(= (. p grid-items) (malloc (* (+ [(. p grid-start) cells] 1) (sizeof int))))))
(free fill)))
;;; new RiverRegion(plateX, plateZ): the whole plate's rivers.
(pub fn river-plate/make ((config river-config) (oceans (* ocean-layer)) (size-y int)
(px int) (pz int)) (* river-plate)
(var p (* river-plate) (calloc 1 (sizeof river-plate)))
(= (. p config) config)
(= (. p px) px)
(= (. p pz) pz)
(= (. p rng) (lcg/make 0))
(.init-position (& (. p rng)) px pz)
(var n int (. config zones-in-region))
(= (. p ocean) (calloc (* n n) (sizeof bool)))
(= (. p ocean-distance) (calloc (* n n) (sizeof double)))
(for (var x int 0) (< x n) (++ x)
(for (var z int 0) (< z n) (++ z)
(= [(. p ocean) (zone-index p x z)] (zone-is-ocean p oceans size-y x z))))
(ocean-distances p)
;; Seed rivers on coastal ocean zones, x outer and z inner.
(for (var x int 0) (< x n) (++ x)
(for (var z int 0) (< z n) (++ z)
(if (! [(. p ocean) (zone-index p x z)])
(continue))
(var coastal bool false)
(for (var dx int -1) (< dx 2) (++ dx)
(for (var dz int -1) (< dz 2) (++ dz)
(var cx int (if (< (+ x dx) 0) 0 (if (> (+ x dx) (- n 1)) (- n 1) (+ x dx))))
(var cz int (if (< (+ z dz) 0) 0 (if (> (+ z dz) (- n 1)) (- n 1) (+ z dz))))
(if (! [(. p ocean) (zone-index p cx cz)])
(= coastal true))))
(if (! coastal)
(continue))
(if (! (< (.next-float (& (. p rng))) (. config river-spawn-chance)))
(continue))
(var center vec2 (zone-center p x z))
(= (. p rivers) (grow-array (. p rivers) (& (. p river-cap)) (. p river-count) (sizeof river)))
(= (. p river-last) (realloc (. p river-last) (* (cast (. p river-cap) size-t) (sizeof int))))
(var r int (. p river-count))
(= [(. p rivers) r] #(river : center -1 false))
(= [(. p river-last) r] -1)
(++ (. p river-count))
(var target int (find-highest p x z 8))
(var tc vec2 (zone-center p (% target n) (/ target n)))
(var angle double (normal-to-degrees (v-normalized (v-sub tc center))))
(if (generate-river p angle center 0 -1 r (. config downhill-error))
(= (. [(. p rivers) r] alive) true)
(-- (. p river-count)))))
(while (< (. p queue-head) (. p queue-tail))
(var q request [(. p queue) (. p queue-head)])
(++ (. p queue-head))
(generate-river p (. q angle) (. q start) (. q stage) (. q parent) (. q river) (. q error)))
;; Sizes and lakes, then drop rivers with too few nodes.
(for (var r int 0) (< r (. p river-count)) (++ r)
(if (< (river-node-count p r) (. config min-nodes))
(do (= (. [(. p rivers) r] alive) false) (continue)))
(for (var nd int (. [(. p rivers) r] first-node)) (>= nd 0) (= nd [(. p node-next) nd])
(if (. [(. p nodes) nd] is-end)
(assign-size p nd 1)))
(var ends (* int) (malloc (* (+ (river-node-count p r) 1) (sizeof int))))
(var end-count int 0)
(for (var nd int (. [(. p rivers) r] first-node)) (>= nd 0) (= nd [(. p node-next) nd])
(if (. [(. p nodes) nd] is-end)
(do (= [ends end-count] nd) (++ end-count))))
(for (var i int 0) (< i end-count) (++ i)
(if (< (.next-float (& (. p rng))) (. config lake-chance))
(do
(var en (* river-node) (& [(. p nodes) [ends i]]))
(add-lake p r [ends i] (normal-to-degrees (v-normalized (v-sub (. en end) (. en start))))))))
(free ends))
(var live (* bool) (calloc (+ (. p segment-count) 1) (sizeof bool)))
(for (var r int 0) (< r (. p river-count)) (++ r)
(if (! (. [(. p rivers) r] alive))
(continue))
(for (var nd int (. [(. p rivers) r] first-node)) (>= nd 0) (= nd [(. p node-next) nd])
(var node (* river-node) (& [(. p nodes) nd]))
(for (var i int 0) (< i (. node segment-count)) (++ i)
(segment-bounds p (+ (. node first-segment) i))
(= [live (+ (. node first-segment) i)] true))))
(build-grid p live)
(free live)
(return p))
(pub fn river-plate/free ((p (* river-plate))) void
(free (. p ocean))
(free (. p ocean-distance))
(free (. p nodes))
(free (. p node-next))
(free (. p segments))
(free (. p rivers))
(free (. p river-last))
(free (. p queue))
(free (. p grid-start))
(free (. p grid-items))
(free p))
;;; Sampling ------------------------------------------------------------
(pub record river-sample ((distance double) (bank double)))
(pub record river-sampler
((distort-x fast-noise) (distort-z fast-noise) (strength int)
(river-depth double) (base-depth double)))
(pub fn river-sampler/make ((c (* const river-config)) (size-y int)) river-sampler
(var multi double (/ (cast 256 float) size-y))
(var s river-sampler)
(= (. s distort-x) (fast-noise/make 0 (. c river-frequency) (. c river-octaves) (. c river-gain)
(. c river-lacunarity)))
(= (. s distort-z) (fast-noise/make 2 (. c river-frequency) (. c river-octaves) (. c river-gain)
(. c river-lacunarity)))
(= (. s strength) (. c river-distortion-strength))
(= (. s river-depth) (* (. c river-depth) multi))
(= (. s base-depth) (* (. c base-depth) multi))
(return s))
;;; The segments whose sampling bounds touch chunk (cx, cz), which is
;;; the set the mod samples a chunk's columns against. Returns the
;;; count, filling OUT (which needs room for every segment).
(pub fn river-plate/chunk-segments ((p (* const river-plate)) (cx int) (cz int) (out (* int))) int
(var size double (plate-size p))
(var q envelope)
(= (. q min-x) (- (* cx 32.0) (* (. p px) size)))
(= (. q min-y) (- (* cz 32.0) (* (. p pz) size)))
(= (. q max-x) (+ (. q min-x) 32))
(= (. q max-y) (+ (. q min-y) 32))
(var n int 0)
(for (var gx int (grid-cell p (. q min-x))) (<= gx (grid-cell p (. q max-x))) (++ gx)
(for (var gz int (grid-cell p (. q min-y))) (<= gz (grid-cell p (. q max-y))) (++ gz)
(var cell int (+ (* gz PLATE-GRID) gx))
(for (var k int [(. p grid-start) cell]) (< k [(. p grid-start) (+ cell 1)]) (++ k)
(var i int [(. p grid-items) k])
(if (intersects (& (. [(. p segments) i] bounds)) (& q))
(do (= [out n] i) (++ n))))))
(return n))
(fn sample-line ((s (* const river-sampler)) (sample (* river-sample)) (p vec2)
(start vec2) (end vec2) (size float)) void
(var distance double (distance-to-line p start end))
(if (<= distance size)
(do
(= (. sample distance) 0)
(var lerp double (/ (- distance size) (- 0 size)))
(= lerp (sqrt (- 1 (pow (- 1 lerp) 2))))
(var depth double (* (fmax (* (sqrt size) (. s river-depth)) (. s base-depth)) lerp))
(= (. sample bank) (fmax depth (. sample bank)))
(return)))
(-= distance size)
(if (< distance 0) (= distance 0))
(= (. sample distance) (fmin distance (. sample distance))))
(fn sample-connector ((rs (* const river-sampler)) (p (* const river-plate)) (seg int) (conn int)
(proj float) (sample (* river-sample)) (point vec2) (size float)) void
(var s (* const river-segment) (& [(. p segments) seg]))
(var c (* const river-segment) (& [(. p segments) conn]))
(var mid-proj float (projection point (. s mid) (. c mid)))
(var ls vec2)
(var le vec2)
(if (> proj 0.5)
(do
(if (. c parent-invalid) (= mid-proj 0))
(var cn (* const river-node) (& [(. p nodes) (. c node)]))
(var sn (* const river-node) (& [(. p nodes) (. s node)]))
(if (< (. cn start-size) (. sn end-size))
(= size (+ (. cn start-size) (* (- (. cn end-size) (. cn start-size)) (cast 0.5 float)))))
(= ls (v2 (+ (. s mid x) (* (- (. c start x) (. s mid x)) mid-proj))
(+ (. s mid y) (* (- (. c start y) (. s mid y)) mid-proj))))
(= le (v2 (+ (. s end x) (* (- (. c mid x) (. s end x)) mid-proj))
(+ (. s end y) (* (- (. c mid y) (. s end y)) mid-proj)))))
(do
(if (. s parent-invalid) (= mid-proj 0))
(= ls (v2 (+ (. s start x) (* (- (. c mid x) (. s start x)) mid-proj))
(+ (. s start y) (* (- (. c mid y) (. s start y)) mid-proj))))
(= le (v2 (+ (. s mid x) (* (- (. c end x) (. s mid x)) mid-proj))
(+ (. s mid y) (* (- (. c end y) (. s mid y)) mid-proj))))))
(sample-line rs sample point ls le size))
;;; RiverGenerator.SampleRiver at world block (x, z), against the
;;; segments of its chunk.
(pub fn river-sampler/sample ((rs (* const river-sampler)) (p (* const river-plate))
(segments (* const int)) (count int) (x int) (z int)) river-sample
(var size double (plate-size p))
(var lx double (- x (* (. p px) size)))
(var lz double (- z (* (. p pz) size)))
(var dx double (.get (& (. rs distort-x)) lx lz))
(var dz double (.get (& (. rs distort-z)) lx lz))
(var point vec2 (v2 (+ lx (* dx (. rs strength))) (+ lz (* dz (. rs strength)))))
(var sample river-sample #(river-sample : 5000 0))
(for (var k int 0) (< k count) (++ k)
(var seg int [segments k])
(var s (* const river-segment) (& [(. p segments) seg]))
(var n (* const river-node) (& [(. p nodes) (. s node)]))
(var river-proj float (projection point (. n start) (. n end)))
(var size float (+ (. n start-size) (* (- (. n end-size) (. n start-size)) river-proj)))
(var seg-proj float (projection point (. s start) (. s end)))
(if (> seg-proj 0.5)
(if (< (. s first-child) 0)
(sample-line rs (& sample) point (. s start) (. s end) size)
(for (var c int (. s first-child)) (>= c 0) (= c (. [(. p segments) c] next-sibling))
(sample-connector rs p seg c seg-proj (& sample) point size)))
(if (< (. s parent) 0)
(sample-line rs (& sample) point (. s start) (. s end) size)
(sample-connector rs p seg (. s parent) seg-proj (& sample) point size))))
(return sample))
;;; Whether the zone holding plate-local block (x, z) is ocean to
;;; Rivers.
(pub fn river-plate/ocean-at ((p (* const river-plate)) (x int) (z int)) bool
(var size double (plate-size p))
(return [(. p ocean) (zone-at p (- x (* (. p px) size)) (- z (* (. p pz) size)))]))
(pub fn river-plate/chunks ((c (* const river-config))) int
(return (/ (* (. c zone-size) (. c zones-in-region)) 32)))