diff --git a/Makefile b/Makefile index 1b10a73..32a1ffe 100644 --- a/Makefile +++ b/Makefile @@ -18,8 +18,10 @@ all: $(B)/vsmv $(B)/vs-map-viewer # any Sex object. SEX_SRC := $(wildcard src/*.sex) +# Statement-level #line directives can land inside a ?: and break the +# C (see Sex-field-notes.org), so they are kept to toplevel forms. $(B)/%.o: src/%.sex $(SEX_SRC) | $(B) - $(SEXC) $< -c -o $@ -- $(CFLAGS) $(SEX_CFLAGS) $(CPPFLAGS) + $(SEXC) --line-directives=toplevel $< -c -o $@ -- $(CFLAGS) $(SEX_CFLAGS) $(CPPFLAGS) $(B)/nk.o: src/nk.c src/nk.h | $(B) $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ @@ -30,7 +32,7 @@ $(B)/cJSON.o: cJSON/cJSON.c cJSON/cJSON.h | $(B) $(B)/stb.o: src/stb.c third_party/stb/stb_image_write.h | $(B) $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ -VSMV_OBJ = vsmv cs pb json save img dump cJSON stb +VSMV_OBJ = vsmv cs pb json maps save img dump lcg noise shape worldgen verify cJSON stb $(B)/vsmv: $(VSMV_OBJ:%=$(B)/%.o) $(CC) $^ -o $@ -lsqlite3 diff --git a/Plan.org b/Plan.org index 084f011..ff2d525 100644 --- a/Plan.org +++ b/Plan.org @@ -293,18 +293,55 @@ What the save turned out to be: - *Seed.* A numeric seed is assumed to be used as is. That is unverified, since the parse is in the closed engine. -** 2. Region maps** 2. Region maps -- Port =noise= and =maplayers=, then =GenMaps=, in this order: - 1. geologic province - 2. landform - 3. ocean - 4. upheaval - 5. climate - 6. strata thickness -- Then the story-structure placement and forcing. Check the placement - against =storystructurelocations=. -- =vsmv verify-regions= diffs all 118 stored regions and reports the - percentage of exact pixel matches per map type. The target is 100%. +** 2. Region maps (done) +=vsmv verify SAVE ASSETS OUT= generates every region the save stored +and diffs each map, padding included. It also writes a diff image per +map. All of them match exactly: + +| Map | Pixels matched | +|-----+----------------| +| province | 23,128 / 23,128 | +| landform | 188,800 / 188,800 | +| ocean | 79,768 / 79,768 | +| upheaval | 57,112 / 57,112 | +| climate | 47,200 / 47,200 | +| strata (16 per region) | 2,446,848 / 2,446,848 | + +All six story locations land where the save has them. Generating the +118 regions takes about 0.26 s. + +Ported, in =src/=: +- =lcg= (the game's RNG); +- =noise= (SimplexNoiseOctave 2D/3D, NormalizedSimplexNoise, + SimplexNoise); +- =shape= (NaturalShape); +- =worldgen= (the layers, GenMaps' forcing and story placement). + +Quirks that had to be reproduced, beyond those listed under +[[*Determinism rules for the port]]: +- *=LCGRandom.SetWorldSeed=* sets =currentSeed= from the /previous/ + mapGenSeed. Story placement re-seeds one RNG per structure, so each + structure's first draw depends on the previous structure's seed. +- *Unpositioned RNG.* An RNG that is never positioned always starts at + =currentSeed = 1442695040888963407=. NoiseClimateRealistic draws its + ZOffset from it. +- *NaturalShape* picks cells with =Dictionary.ElementAt(n)=. Enumeration + follows .NET's slot order, where removed slots are reused + last-in-first-out, and =shape.sex= keeps those slots. +- *GenMaps.ForceClimate* is passed the landform map's padding (4) + instead of the climate map's (2), and it matters. +- *MapLayerLandforms* samples climate at =finalX / 32= in integer + division, so its climate lerp is always at a cell corner. +- *Float vs double.* C# =float= expressions are kept in =float=. That + includes =1 / scale=-style frequencies, but not =0.5 / scale=, which + is double. +- *Evaluation order.* =a() + b() + c()= is evaluated left to right in + C# and in unspecified order in C. Draws are sequenced through + variables (NatFloat's Gauss sum). + +Not ported yet: the =patchy= world climate (=worldClimate= other than +=realistic=), and the forest, shrub, flower and beach maps, which +nothing here uses. ** 3. Minimal viewer - Nuklear panels, a pannable and zoomable tile map, and a diff --git a/Sex-field-notes.org b/Sex-field-notes.org index d195076..44e9505 100644 --- a/Sex-field-notes.org +++ b/Sex-field-notes.org @@ -3,6 +3,50 @@ Language bugs and friction met while building vs-map-viewer, against sexc at ~/dev/sex. Newest first. Unless said otherwise, sexc dfafe8b. +* A conditional expression as an operand loses its parentheses +#+begin_src scheme +(/ (* 100.0 matched) (if (> compared 0) compared 1)) +#+end_src +emits =(100.0 * matched) / (compared > 0) ? compared : 1=, which C +parses as =((100.0 * matched) / (compared > 0)) ? compared : 1=. +Clang only warns (-Wparentheses). This one computes wrong values +silently, so it is the most dangerous entry here. Bound to a variable +first, it's right. + +* An import doesn't bring the types its interface needs +Module =save= takes a =(* region-maps)= from module =maps=. Importing +=save= pastes its prototypes but not =region-maps=, so every importer +has to import =maps= itself, and before =save=: + +#+begin_example +save.sex:284:52: error: unknown type name 'region_maps' +#+end_example + +=vsmv.sex= now imports eight modules in dependency order to use three. +Imports are at least idempotent (a diamond works). + +* A pub record with a field of a private record type +=(pub record natural-shape (... (slots (* shape-cell)) ...))= with +=shape-cell= not =pub= compiles in its own module, and in the importer +fails with =unknown type name 'shape_cell'=. Either an error at the +definition or exporting the type would do. + +* =[(* T) N]= fields break in importers +A pub record field =(noises [(* simplex-sum) 32])= compiles in its own +module but not when pasted into an importer: +=Error: pointer chains are written flat, as (* * T), not nested: +((* simplex-sum) MAX_STRATA)=. The message points at the wrong thing; +=[* simplex-sum MAX_STRATA]= works, while a local +=(var names [(* const char) 6])= is fine either way. + +* =define= bodies are pasted raw +=(define K (/ (cast 255 float) (cast 60 float)))= emits +=#define K cast(255, float) / cast(60, float)=: not translated, and +not parenthesized. With =(define D (/ -1.0 6.0))=, =(* x D)= becomes +=x * -1.0 / 6.0=. That's =(x * -1.0) / 6.0=, which rounds differently +from multiplying by the folded constant. Bit-exact code needs literal +values or typed =var=s. + * =#line= splits a ternary in a call argument =(if c a b)= in expression position becomes =c ? a : b=. Inside a multi-line call, though, the statement anchor lands between the @@ -16,8 +60,8 @@ dump.sex:128:1: error: expected expression 128 | , grey(255 - d)); #+end_example -=-C= output, without the directives, is fine. Worked around with a -variable. +=-C= output, without the directives, is fine. The build now passes +=--line-directives=toplevel= to every Sex unit. * A typedef of a function pointer type crashes the compiler #+begin_src scheme diff --git a/src/dump.sex b/src/dump.sex index 04705ab..05409f2 100644 --- a/src/dump.sex +++ b/src/dump.sex @@ -3,6 +3,7 @@ ;;; pictures the generator's own output is diffed against. (include stdio.h stdlib.h string.h) +(import maps) (import save) (import img) diff --git a/src/lcg.sex b/src/lcg.sex new file mode 100644 index 0000000..0860c43 --- /dev/null +++ b/src/lcg.sex @@ -0,0 +1,68 @@ +;;; The game's linear congruential RNG, as both LCGRandom and NoiseBase +;;; have it: one 64-bit state stepped by +;;; s = s * (s * 6364136223846793005 + 1442695040888963407) + mapGenSeed +;;; C# lets the long arithmetic wrap, so it is done on u64 here. +;;; +;;; Both classes start `current' from a mapGenSeed that is still 0, so +;;; an RNG that is never positioned draws the same sequence whatever +;;; the world seed. NoiseClimateRealistic relies on exactly that. + +(pub record lcg ((map-gen-seed u64) (current u64))) + +(define LCG-A 6364136223846793005) +(define LCG-C 1442695040888963407) + +(fn step ((s u64)) u64 + (return (* s (+ (* s (cast LCG-A u64)) (cast LCG-C u64))))) + +(ops lcg + (pub fn make ((world-seed i64)) lcg + (var w u64 (cast world-seed u64)) + (var m u64 w) + (= m (* m (+ (* w (cast LCG-A u64)) (cast LCG-C u64)))) + (+= m 1) + (= m (* m (+ (* w (cast LCG-A u64)) (cast LCG-C u64)))) + (+= m 2) + (= m (* m (+ (* w (cast LCG-A u64)) (cast LCG-C u64)))) + (+= m 3) + (return #(lcg : m (cast LCG-C u64)))) + + ;; LCGRandom.SetWorldSeed on an RNG already in use: `current' is set + ;; from the old mapGenSeed before it is replaced, so re-seeding + ;; depends on what the RNG was seeded with before. + (pub fn reseed ((self (* lcg)) (world-seed i64)) void + (var current u64 (+ (* (. self map-gen-seed) (cast LCG-A u64)) (cast LCG-C u64))) + (= (* self) (lcg/make world-seed)) + (= (. self current) current)) + + (pub fn init-position ((self (* lcg)) (x int) (z int)) void + (var s u64 (. self map-gen-seed)) + (= s (+ (step s) (cast (cast x i64) u64))) + (= s (+ (step s) (cast (cast z i64) u64))) + (= s (+ (step s) (cast (cast x i64) u64))) + (= s (+ (step s) (cast (cast z i64) u64))) + (= (. self current) s)) + + (fn advance ((self (* lcg))) void + (= (. self current) (+ (step (. self current)) (. self map-gen-seed)))) + + ;; (int)((seed >> 24) % max), made non-negative. + (pub fn next-int ((self (* lcg)) (max int)) int + (var r int (cast (% (>> (cast (. self current) i64) 24) max) int)) + (if (< r 0) + (+= r max)) + (.advance self) + (return r)) + + (fn next-bits ((self (* lcg))) int + (var r int (& (cast (>> (cast (. self current) i64) 24) int) INT32_MAX)) + (.advance self) + (return r)) + + (pub fn next-float ((self (* lcg))) float + (return (/ (cast (.next-bits self) float) (cast INT32_MAX float)))) + + (pub fn next-double ((self (* lcg))) double + (var r u32 (cast (>> (cast (. self current) i64) 24) u32)) + (.advance self) + (return (/ r (cast UINT32_MAX double))))) diff --git a/src/maps.sex b/src/maps.sex new file mode 100644 index 0000000..a4adc03 --- /dev/null +++ b/src/maps.sex @@ -0,0 +1,24 @@ +;;; The map types both sides of the comparison produce: what the save +;;; stored and what the generator makes for one map region. + +(include stdlib.h) + +(pub define MAX-STRATA 32) + +;;; IntDataMap2D: a square map whose border pixels only feed lerps +;;; and blurs. The region's own pixels are the inner +;;; (size - pad-tl - pad-br) square. +(pub record int-map ((data (* i32)) (size i32) (pad-tl i32) (pad-br i32))) + +(pub record region-maps + ((landform int-map) (climate int-map) (geoprov int-map) (upheaval int-map) + (ocean int-map) (strata [int-map MAX_STRATA]) (strata-count int))) + +(pub fn region-maps/free ((m (* region-maps))) void + (free (. m landform data)) + (free (. m climate data)) + (free (. m geoprov data)) + (free (. m upheaval data)) + (free (. m ocean data)) + (for (var i int 0) (< i (. m strata-count)) (++ i) + (free (. [(. m strata) i] data)))) diff --git a/src/noise.sex b/src/noise.sex new file mode 100644 index 0000000..2a48b80 --- /dev/null +++ b/src/noise.sex @@ -0,0 +1,335 @@ +;;; Simplex noise as vsapi has it: SimplexNoiseOctave, the OpenSimplex +;;; variant with precomputed contribution lists, and +;;; NormalizedSimplexNoise, octaves of it squashed by tanh into 0..1. +;;; Every map layer and the terrain itself sample these, so this is +;;; ported operation for operation, in doubles where C# has doubles. + +(pub include stdint.h) +(include stdlib.h math.h) + +;;; The C# folds these at compile time; written as divisions here they +;;; would be unparenthesized macros and round differently in context. +(define STRETCH-2D -0.211324865405187) +(define SQUISH-2D 0.366025403784439) +(define STRETCH-3D -0.16666666666666666) +(define SQUISH-3D 0.3333333333333333) +(define NORM-2D 0.02127659574468085) +(define NORM-3D 0.009708737864077669) +(pub define MAX-VALUE-3D 0.9871465422297019) +(define VALUE-MULTIPLIER 1.2) +(pub define MAX-OCTAVES 16) + +(var gradients-2d [double 16] #(5 2 2 5 -5 2 -2 5 5 -2 2 -5 -5 -2 -2 -5)) + +(var gradients-3d [double 72] + #(-11 4 4 -4 11 4 -4 4 11 + 11 4 4 4 11 4 4 4 11 + -11 -4 4 -4 -11 4 -4 -4 11 + 11 -4 4 4 -11 4 4 -4 11 + -11 4 -4 -4 11 -4 -4 4 -11 + 11 4 -4 4 11 -4 4 4 -11 + -11 -4 -4 -4 -11 -4 -4 -4 -11 + 11 -4 -4 4 -11 -4 4 -4 -11)) + +;;; Generated from vsapi SimplexOctave.cs by a script; do not edit. +(var base2d-0 [int 9] + #(1 1 0 1 0 1 0 0 0)) +(var base2d-1 [int 9] + #(1 1 0 1 0 1 2 1 1)) +(var base3d-0 [int 16] + #(0 0 0 0 1 1 0 0 1 0 1 0 1 0 0 1)) +(var base3d-1 [int 16] + #(2 1 1 0 2 1 0 1 2 0 1 1 3 1 1 1)) +(var base3d-2 [int 24] + #(1 1 0 0 1 0 1 0 1 0 0 1 2 1 1 0 2 1 0 1 2 0 1 1)) +(var p2d [int 24] + #(0 0 1 -1 0 0 -1 1 0 2 1 1 1 2 2 0 1 2 0 2 1 0 0 0)) +(var lookup-pairs-2d [int 24] + #(0 1 1 0 4 1 17 0 20 2 21 2 22 5 23 5 26 4 39 3 42 4 43 3)) +(var p3d [int 216] + #(0 0 1 -1 0 0 1 0 -1 0 0 -1 1 0 0 0 1 -1 0 0 -1 0 1 0 0 -1 1 + 0 2 1 1 0 1 1 1 -1 0 2 1 0 1 1 1 -1 1 0 2 0 1 1 1 -1 1 1 + 1 3 2 1 0 3 1 2 0 1 3 2 0 1 3 1 0 2 1 3 0 2 1 3 0 1 2 + 1 1 1 0 0 2 2 0 0 1 1 0 1 0 2 0 2 0 1 1 0 0 1 2 0 0 2 + 2 0 0 0 0 1 1 -1 1 2 0 0 0 0 1 -1 1 1 2 0 0 0 0 1 1 1 -1 + 2 3 1 1 1 2 0 0 2 2 3 1 1 1 2 2 0 0 2 3 1 1 1 2 0 2 0 + 2 1 1 -1 1 2 0 0 2 2 1 1 -1 1 2 2 0 0 2 1 -1 1 1 2 0 0 2 + 2 1 -1 1 1 2 0 2 0 2 1 1 1 -1 2 2 0 0 2 1 1 1 -1 2 0 2 0)) +(var lookup-pairs-3d [int 144] + #(0 2 1 1 2 2 5 1 6 0 7 0 32 2 34 2 129 1 133 1 160 5 161 5 + 518 0 519 0 546 4 550 4 645 3 647 3 672 5 673 5 674 4 677 3 678 4 679 3 + 680 13 681 13 682 12 685 14 686 12 687 14 712 20 714 18 809 21 813 23 840 20 841 21 + 1198 19 1199 22 1226 18 1230 19 1325 23 1327 22 1352 15 1353 17 1354 15 1357 17 1358 16 1359 16 + 1360 11 1361 10 1362 11 1365 10 1366 9 1367 9 1392 11 1394 11 1489 10 1493 10 1520 8 1521 8 + 1878 9 1879 9 1906 7 1910 7 2005 6 2007 6 2032 8 2033 8 2034 7 2037 6 2038 7 2039 6)) + +;;; One vertex a lattice cell contributes. The C# builds linked lists +;;; of these once, statically; here they are a pool and `next' is an +;;; index into it, -1 at a list's end. +(record contribution ((dx double) (dy double) (dz double) + (xsb int) (ysb int) (zsb int) (next int))) + +(var pool [contribution 256]) +(var pool-used int 0) +(var lookup-2d [int 64]) +(var lookup-3d [int 2048]) +(var tables-ready bool false) + +(fn contribution-2d ((multiplier double) (xsb int) (ysb int)) int + (var c (* contribution) (& [pool pool-used])) + (= (. c dx) (- (- xsb) (* multiplier SQUISH-2D))) + (= (. c dy) (- (- ysb) (* multiplier SQUISH-2D))) + (= (. c dz) 0) + (= (. c xsb) xsb) + (= (. c ysb) ysb) + (= (. c zsb) 0) + (= (. c next) -1) + (++ pool-used) + (return (- pool-used 1))) + +(fn contribution-3d ((multiplier double) (xsb int) (ysb int) (zsb int)) int + (var c (* contribution) (& [pool pool-used])) + (= (. c dx) (- (- xsb) (* multiplier SQUISH-3D))) + (= (. c dy) (- (- ysb) (* multiplier SQUISH-3D))) + (= (. c dz) (- (- zsb) (* multiplier SQUISH-3D))) + (= (. c xsb) xsb) + (= (. c ysb) ysb) + (= (. c zsb) zsb) + (= (. c next) -1) + (++ pool-used) + (return (- pool-used 1))) + +;;; The static constructor of SimplexNoiseOctave, 2D and 3D parts. +(fn build-tables () void + (var heads-2d [int 6]) + (for (var i int 0) (< i 24) (+= i 4) + (var base (* int) (if (== [p2d i] 0) base2d-0 base2d-1)) + (var previous int -1) + (for (var k int 0) (< k 9) (+= k 3) + (var current int (contribution-2d [base k] [base (+ k 1)] [base (+ k 2)])) + (if (< previous 0) + (= [heads-2d (/ i 4)] current) + (= (. [pool previous] next) current)) + (= previous current)) + (= (. [pool previous] next) + (contribution-2d [p2d (+ i 1)] [p2d (+ i 2)] [p2d (+ i 3)]))) + (for (var i int 0) (< i 64) (++ i) + (= [lookup-2d i] -1)) + (for (var i int 0) (< i 24) (+= i 2) + (= [lookup-2d [lookup-pairs-2d i]] [heads-2d [lookup-pairs-2d (+ i 1)]])) + + (var heads-3d [int 24]) + (for (var i int 0) (< i 216) (+= i 9) + (var base (* int) base3d-0) + (var base-len int 16) + (if (== [p3d i] 1) (= base base3d-1) + (== [p3d i] 2) (do (= base base3d-2) (= base-len 24))) + (var previous int -1) + (for (var k int 0) (< k base-len) (+= k 4) + (var current int (contribution-3d [base k] [base (+ k 1)] [base (+ k 2)] [base (+ k 3)])) + (if (< previous 0) + (= [heads-3d (/ i 9)] current) + (= (. [pool previous] next) current)) + (= previous current)) + (var a int (contribution-3d [p3d (+ i 1)] [p3d (+ i 2)] [p3d (+ i 3)] [p3d (+ i 4)])) + (= (. [pool previous] next) a) + (= (. [pool a] next) + (contribution-3d [p3d (+ i 5)] [p3d (+ i 6)] [p3d (+ i 7)] [p3d (+ i 8)]))) + (for (var i int 0) (< i 2048) (++ i) + (= [lookup-3d i] -1)) + (for (var i int 0) (< i 144) (+= i 2) + (= [lookup-3d [lookup-pairs-3d i]] [heads-3d [lookup-pairs-3d (+ i 1)]])) + (= tables-ready true)) + +;;; Builds the shared lookup tables. Call once before any threads +;;; sample noise; constructors call it too. +(pub fn noise-init () void + (if (! tables-ready) + (build-tables))) + +(pub record simplex-octave ((perm [u8 256]) (perm-2d [u8 256]) (perm-3d [u8 256]))) + +(ops simplex-octave + (pub fn make ((seed i64)) simplex-octave + (noise-init) + (var o simplex-octave) + (var source [u8 256]) + (for (var i int 0) (< i 256) (++ i) + (= [source i] (cast i u8))) + (var s u64 (cast seed u64)) + (for (var k int 0) (< k 3) (++ k) + (= s (+ (* s 6364136223846793005) 1442695040888963407))) + (for (var i int 255) (>= i 0) (-- i) + (= s (+ (* s 6364136223846793005) 1442695040888963407)) + (var r int (cast (% (+ (cast s i64) 31) (+ i 1)) int)) + (if (< r 0) + (+= r (+ i 1))) + (= [(. o perm) i] [source r]) + (= [(. o perm-2d) i] (cast (& [(. o perm) i] 14) u8)) + (= [(. o perm-3d) i] (cast (* (% [(. o perm) i] 24) 3) u8)) + (= [source r] [source i])) + (return o)) + + (pub fn eval-2d ((self (* const simplex-octave)) (x double) (y double)) double + (var stretch double (* (+ x y) STRETCH-2D)) + (var xs double (+ x stretch)) + (var ys double (+ y stretch)) + (var xsb int (cast (floor xs) int)) + (var ysb int (cast (floor ys) int)) + (var squish double (* (+ xsb ysb) SQUISH-2D)) + (var dx0 double (- x (+ xsb squish))) + (var dy0 double (- y (+ ysb squish))) + (var xins double (- xs xsb)) + (var yins double (- ys ysb)) + (var in-sum double (+ xins yins)) + (var hash u32 (c-bit-or (cast (+ (- xins yins) 1) u32) + (<< (cast in-sum u32) 1) + (<< (cast (+ in-sum yins) u32) 2) + (<< (cast (+ in-sum xins) u32) 4))) + (var value double 0.0) + (for (var c int [lookup-2d hash]) (>= c 0) (= c (. [pool c] next)) + (var dx double (+ dx0 (. [pool c] dx))) + (var dy double (+ dy0 (. [pool c] dy))) + (var attn double (- 2.0 (* dx dx) (* dy dy))) + (if (> attn 0.0) + (do + (var px int (+ xsb (. [pool c] xsb))) + (var py int (+ ysb (. [pool c] ysb))) + (var i int [(. self perm-2d) (& (+ [(. self perm) (& px 255)] py) 255)]) + (var part double (+ (* [gradients-2d i] dx) (* [gradients-2d (+ i 1)] dy))) + (*= attn attn) + (+= value (* attn attn part))))) + (return (* value NORM-2D))) + + (pub fn eval-3d ((self (* const simplex-octave)) (x double) (y double) (z double)) double + (var stretch double (* (+ x y z) STRETCH-3D)) + (var xs double (+ x stretch)) + (var ys double (+ y stretch)) + (var zs double (+ z stretch)) + (var xsb int (cast (floor xs) int)) + (var ysb int (cast (floor ys) int)) + (var zsb int (cast (floor zs) int)) + (var squish double (* (+ xsb ysb zsb) SQUISH-3D)) + (var dx0 double (- x (+ xsb squish))) + (var dy0 double (- y (+ ysb squish))) + (var dz0 double (- z (+ zsb squish))) + (var xins double (- xs xsb)) + (var yins double (- ys ysb)) + (var zins double (- zs zsb)) + (var in-sum double (+ xins yins zins)) + (var hash int (c-bit-or (cast (+ (- yins zins) 1) int) + (<< (cast (+ (- xins yins) 1) int) 1) + (<< (cast (+ (- xins zins) 1) int) 2) + (<< (cast in-sum int) 3) + (<< (cast (+ in-sum zins) int) 5) + (<< (cast (+ in-sum yins) int) 7) + (<< (cast (+ in-sum xins) int) 9))) + (if (< hash 0) (= hash 0)) + (if (> hash 2047) (= hash 2047)) + (var value double 0.0) + (for (var c int [lookup-3d hash]) (>= c 0) (= c (. [pool c] next)) + (var dx double (+ dx0 (. [pool c] dx))) + (var dy double (+ dy0 (. [pool c] dy))) + (var dz double (+ dz0 (. [pool c] dz))) + (var attn double (- 2.0 (* dx dx) (* dy dy) (* dz dz))) + (if (> attn 0.0) + (do + (var px int (+ xsb (. [pool c] xsb))) + (var py int (+ ysb (. [pool c] ysb))) + (var pz int (+ zsb (. [pool c] zsb))) + (var i int [(. self perm-3d) + (& (+ [(. self perm) (& (+ [(. self perm) (& px 255)] py) 255)] pz) 255)]) + (var part double (+ (* [gradients-3d i] dx) (* [gradients-3d (+ i 1)] dy) + (* [gradients-3d (+ i 2)] dz))) + (*= attn attn) + (+= value (* attn attn part))))) + (return (* value NORM-3D)))) + +;;; NormalizedSimplexNoise. Octave i samples at frequencies[i] and is +;;; weighted so the sum stays in a known range before tanh. +(pub record simplex-noise + ((count int) (frequencies [double MAX_OCTAVES]) (amplitudes [double MAX_OCTAVES]) + (scaled-2d [double MAX_OCTAVES]) (scaled-3d [double MAX_OCTAVES]) + (octaves [simplex-octave MAX_OCTAVES]))) + +(ops simplex-noise + (pub fn make ((amplitudes (* const double)) (frequencies (* const double)) (count int) + (seed i64)) (* simplex-noise) + (var n (* simplex-noise) (calloc 1 (sizeof simplex-noise))) + (= (. n count) count) + (var norm-3d double 0) + (var norm-2d double 0) + (for (var i int 0) (< i count) (++ i) + (= [(. n frequencies) i] [frequencies i]) + (= [(. n amplitudes) i] [amplitudes i]) + (= [(. n octaves) i] + (simplex-octave/make (cast (+ (* (cast seed u64) 65599) (cast i u64)) i64))) + (+= norm-3d (* [amplitudes i] (pow (- 0.74 0.1) (+ i 1)))) + (+= norm-2d (* [amplitudes i] (pow (- 0.83 0.1) (+ i 1))))) + (for (var i int 0) (< i count) (++ i) + (= [(. n scaled-2d) i] (/ [amplitudes i] norm-2d)) + (= [(. n scaled-3d) i] (/ [amplitudes i] norm-3d))) + (return n)) + + ;; FromDefaultOctaves: octave i at 2^i * BASE-FREQUENCY, weighted + ;; PERSISTENCE^i. + (pub fn octaves ((count int) (base-frequency double) (persistence double) (seed i64)) + (* simplex-noise) + (var frequencies [double MAX_OCTAVES]) + (var amplitudes [double MAX_OCTAVES]) + (for (var i int 0) (< i count) (++ i) + (= [frequencies i] (* (pow 2 i) base-frequency)) + (= [amplitudes i] (pow persistence i))) + (return (simplex-noise/make amplitudes frequencies count seed))) + + (pub fn noise-2d ((self (* const simplex-noise)) (x double) (y double)) double + (var value double 0) + (for (var i int 0) (< i (. self count)) (++ i) + (var f double [(. self frequencies) i]) + (+= value (* VALUE-MULTIPLIER (.eval-2d (& [(. self octaves) i]) (* x f) (* y f)) + [(. self scaled-2d) i]))) + (return (+ (* (tanh value) 0.5) 0.5))) + + (pub fn noise-3d ((self (* const simplex-noise)) (x double) (y double) (z double)) double + (var value double 0) + (for (var i int 0) (< i (. self count)) (++ i) + (var f double [(. self frequencies) i]) + (+= value (* VALUE-MULTIPLIER (.eval-3d (& [(. self octaves) i]) (* x f) (* y f) (* z f)) + [(. self scaled-3d) i]))) + (return (+ (* (tanh value) 0.5) 0.5)))) + +;;; SimplexNoise: plain octave sums, no normalising and no tanh. The +;;; rock strata thickness maps and the strata distortion use it. +(pub record simplex-sum + ((count int) (frequencies [double MAX_OCTAVES]) (amplitudes [double MAX_OCTAVES]) + (octaves [simplex-octave MAX_OCTAVES]))) + +(ops simplex-sum + (pub fn make ((amplitudes (* const double)) (frequencies (* const double)) (count int) + (seed i64)) (* simplex-sum) + (var n (* simplex-sum) (calloc 1 (sizeof simplex-sum))) + (= (. n count) count) + (for (var i int 0) (< i count) (++ i) + (= [(. n frequencies) i] [frequencies i]) + (= [(. n amplitudes) i] [amplitudes i]) + (= [(. n octaves) i] + (simplex-octave/make (cast (+ (* (cast seed u64) 65599) (cast i u64)) i64)))) + (return n)) + + (pub fn noise-2d ((self (* const simplex-sum)) (x double) (y double)) double + (var value double 0) + (for (var i int 0) (< i (. self count)) (++ i) + (var f double [(. self frequencies) i]) + (+= value (* (.eval-2d (& [(. self octaves) i]) (* x f) (* y f)) [(. self amplitudes) i]))) + (return value)) + + ;; Each octave's value pulled toward 0 by its threshold, so only + ;; peaks above it count. + (pub fn noise-2d-thresholded ((self (* const simplex-sum)) (x double) (y double) + (thresholds (* const double))) double + (var value double 0) + (for (var i int 0) (< i (. self count)) (++ i) + (var f double [(. self frequencies) i]) + (var v double (* (.eval-2d (& [(. self octaves) i]) (* x f) (* y f)) [(. self amplitudes) i])) + (+= value (if (> v 0.0) (fmax 0.0 (- v [thresholds i])) (fmin 0.0 (+ v [thresholds i]))))) + (return value))) diff --git a/src/save.sex b/src/save.sex index d53803e..24916b0 100644 --- a/src/save.sex +++ b/src/save.sex @@ -9,23 +9,14 @@ (pub include sqlite3.h) (include stdio.h stdlib.h string.h) (import pb) +(import maps) ;;; RegionSize is the closed engine's; Rivers hardcodes the same 512. (pub define REGION-SIZE 512) (pub define CHUNK-SIZE 32) (pub define CHUNK-AREA 1024) -(pub define MAX-STRATA 32) (pub define MAX-STORIES 32) -;;; IntDataMap2D: a square map whose border pixels only feed lerps -;;; and blurs. The region's own pixels are the inner -;;; (size - pad-tl - pad-br) square. -(pub record int-map ((data (* i32)) (size i32) (pad-tl i32) (pad-br i32))) - -(pub record region-maps - ((landform int-map) (climate int-map) (geoprov int-map) (upheaval int-map) - (ocean int-map) (strata [int-map MAX_STRATA]) (strata-count int))) - (pub record chunk-maps ((terrain-height [u16 CHUNK_AREA]) (rain-height [u16 CHUNK_AREA]) (top-rock [i32 CHUNK_AREA]) (river-distance [u16 CHUNK_AREA]) @@ -290,15 +281,6 @@ (++ (. m strata-count))) (.skip (& r) wire)))) -(pub fn region-maps/free ((m (* region-maps))) void - (free (. m landform data)) - (free (. m climate data)) - (free (. m geoprov data)) - (free (. m upheaval data)) - (free (. m ocean data)) - (for (var i int 0) (< i (. m strata-count)) (++ i) - (free (. [(. m strata) i] data)))) - (pub fn save/region ((s (* const save)) (rx i32) (rz i32) (out (* region-maps))) bool (var stmt (* sqlite3-stmt) NULL) (var r pb (query-blob s "select data from mapregion where position = ?1" diff --git a/src/shape.sex b/src/shape.sex new file mode 100644 index 0000000..5e81583 --- /dev/null +++ b/src/shape.sex @@ -0,0 +1,247 @@ +;;; NaturalShape: grows a blob of cells outward from a square, at +;;; random, to shape the land forced around spawn and story locations. +;;; +;;; The growth picks its next cell with outline.ElementAt(n) on a .NET +;;; Dictionary, so the result depends on that dictionary's enumeration +;;; order. That order is slot order: new keys take the most recently +;;; freed slot first, otherwise the next unused one. The outline here +;;; keeps exactly those slots. + +(include stdlib.h string.h) +(import lcg) + +;;; An (x, z) → int hash map, open addressing with tombstones. +(pub record cell-map ((keys (* u64)) (vals (* int)) (state (* u8)) (cap int) (live int) (filled int))) + +(fn cell-key ((x int) (z int)) u64 + (return (c-bit-or (<< (cast (cast x u32) u64) 32) (cast (cast z u32) u64)))) + +(fn mix ((k u64)) u64 + (^= k (>> k 33)) + (*= k 6364136223846793005) + (^= k (>> k 33)) + (return k)) + +(ops cell-map + (pub fn make () cell-map + (var m cell-map) + (= (. m cap) 64) + (= (. m keys) (calloc (. m cap) (sizeof u64))) + (= (. m vals) (calloc (. m cap) (sizeof int))) + (= (. m state) (calloc (. m cap) 1)) + (= (. m live) 0) + (= (. m filled) 0) + (return m)) + + (pub fn release ((self (* cell-map))) void + (free (. self keys)) + (free (. self vals)) + (free (. self state))) + + ;; The slot holding KEY, or the one it would go in. + (fn find ((self (* const cell-map)) (key u64)) int + (var mask int (- (. self cap) 1)) + (var i int (cast (& (mix key) (cast mask u64)) int)) + (var tomb int -1) + (while (!= [(. self state) i] 0) + (if (&& (== [(. self state) i] 1) (== [(. self keys) i] key)) + (return i)) + (if (&& (== [(. self state) i] 2) (< tomb 0)) + (= tomb i)) + (= i (& (+ i 1) mask))) + (return (if (>= tomb 0) tomb i))) + + (pub fn get ((self (* const cell-map)) (x int) (z int)) int + (var i int (.find self (cell-key x z))) + (return (if (== [(. self state) i] 1) [(. self vals) i] -1))) + + (pub fn has ((self (* const cell-map)) (x int) (z int)) bool + (return (>= (.get self x z) 0))) + + (fn grow ((self (* cell-map))) void + (var old cell-map (* self)) + (= (. self cap) (* (. old cap) 2)) + (= (. self keys) (calloc (. self cap) (sizeof u64))) + (= (. self vals) (calloc (. self cap) (sizeof int))) + (= (. self state) (calloc (. self cap) 1)) + (= (. self live) 0) + (= (. self filled) 0) + (for (var i int 0) (< i (. old cap)) (++ i) + (if (== [(. old state) i] 1) + (do + (var j int (.find self [(. old keys) i])) + (= [(. self keys) j] [(. old keys) i]) + (= [(. self vals) j] [(. old vals) i]) + (= [(. self state) j] 1) + (++ (. self live)) + (++ (. self filled))))) + (.release (& old))) + + ;; Sets X, Z to VALUE (a non-negative int). + (pub fn put ((self (* cell-map)) (x int) (z int) (value int)) void + (if (>= (* 2 (+ (. self filled) 1)) (. self cap)) + (.grow self)) + (var key u64 (cell-key x z)) + (var i int (.find self key)) + (if (!= [(. self state) i] 1) + (do + (if (== [(. self state) i] 0) (++ (. self filled))) + (++ (. self live)))) + (= [(. self keys) i] key) + (= [(. self vals) i] value) + (= [(. self state) i] 1)) + + (pub fn remove ((self (* cell-map)) (x int) (z int)) void + (var i int (.find self (cell-key x z))) + (if (== [(. self state) i] 1) + (do + (= [(. self state) i] 2) + (-- (. self live)))))) + +;;; NaturalShape ----------------------------------------------------- + +(pub record shape-cell ((x int) (z int) (open [bool 4]) (live bool))) + +(pub record natural-shape + ((rng (* lcg)) + (slots (* shape-cell)) (slot-cap int) (slot-count int) (free (* int)) (free-count int) + (outline cell-map) (inside cell-map))) + +(var offset-x [int 4] #(0 1 0 -1)) +(var offset-z [int 4] #(-1 0 1 0)) + +(fn any-open ((open (* const bool))) bool + (return (|| [open 0] [open 1] [open 2] [open 3]))) + +(ops natural-shape + (fn open-sides ((self (* const natural-shape)) (x int) (z int) (out (* bool))) void + (for (var i int 0) (< i 4) (++ i) + (var nx int (+ x [offset-x i])) + (var nz int (+ z [offset-z i])) + (= [out i] (&& (! (.has (& (. self outline)) nx nz)) (! (.has (& (. self inside)) nx nz)))))) + + ;; Dictionary.TryAdd: the last freed slot, else a new one at the end. + (fn outline-add ((self (* natural-shape)) (x int) (z int) (open (* const bool))) void + (if (.has (& (. self outline)) x z) + (return)) + (var slot int 0) + (if (> (. self free-count) 0) + (do + (-- (. self free-count)) + (= slot [(. self free) (. self free-count)])) + (do + (if (== (. self slot-count) (. self slot-cap)) + (do + (= (. self slot-cap) (* 2 (. self slot-cap))) + (= (. self slots) (realloc (. self slots) (* (. self slot-cap) (sizeof shape-cell)))) + (= (. self free) (realloc (. self free) (* (. self slot-cap) (sizeof int)))))) + (= slot (. self slot-count)) + (++ (. self slot-count)))) + (var c (* shape-cell) (& [(. self slots) slot])) + (= (. c x) x) + (= (. c z) z) + (memcpy (. c open) open (* 4 (sizeof bool))) + (= (. c live) true) + (.put (& (. self outline)) x z slot)) + + (fn outline-remove ((self (* natural-shape)) (x int) (z int)) void + (var slot int (.get (& (. self outline)) x z)) + (if (< slot 0) + (return)) + (.remove (& (. self outline)) x z) + (= (. [(. self slots) slot] live) false) + (= [(. self free) (. self free-count)] slot) + (++ (. self free-count))) + + ;; new NaturalShape(rand) followed by InitSquare(size-x, size-z). + (pub fn square ((rng (* lcg)) (size-x int) (size-z int)) natural-shape + (var s natural-shape) + (memset (& s) 0 (sizeof s)) + (= (. s rng) rng) + (= (. s slot-cap) 64) + (= (. s slots) (malloc (* (. s slot-cap) (sizeof shape-cell)))) + (= (. s free) (malloc (* (. s slot-cap) (sizeof int)))) + (= (. s outline) (cell-map/make)) + (= (. s inside) (cell-map/make)) + (for (var x int 0) (< x size-x) (++ x) + (for (var z int 0) (< z size-z) (++ z) + (var open [bool 4] #(false false false false)) + (if (== z 0) (= [open 0] true) + (== z (- size-z 1)) (= [open 2] true)) + (if (== x 0) (= [open 3] true) + (== x (- size-x 1)) (= [open 1] true)) + (if (any-open open) + (.outline-add (& s) x z open) + (.put (& (. s inside)) x z 1)))) + (return s)) + + (pub fn grow ((self (* natural-shape)) (steps int)) void + (for (var step int 0) (< step steps) (++ step) + (var count float (cast (. (. self outline) live) float)) + (var avg float (* count (cast 0.5 float))) + (var spread float (* count (cast 0.5 float))) + ;; NatFloat GAUSSIAN; the three draws are sequenced as C# has them. + (var r1 float (.next-float (. self rng))) + (var r2 float (.next-float (. self rng))) + (var r3 float (.next-float (. self rng))) + (var rnd float (- (/ (+ (+ r1 r2) r3) (cast 3 float)) (cast 0.5 float))) + (var next int (cast (* (cast 1 float) (+ avg (* (* rnd (cast 2 float)) spread))) int)) + ;; outline.ElementAt(next) + (var slot int -1) + (for (var i int 0) (< i (. self slot-count)) (++ i) + (if (. [(. self slots) i] live) + (do + (if (== next 0) + (do (= slot i) (break))) + (-- next)))) + (if (< slot 0) + (continue)) + (var cell shape-cell [(. self slots) slot]) + (var dir int (.next-int (. self rng) 4)) + (var found bool false) + (var nx int 0) + (var nz int 0) + (for (var j int dir) (< j (+ dir 4)) (++ j) + (if (! [(. cell open) (% j 4)]) + (continue)) + (= nx (+ (. cell x) [offset-x (% j 4)])) + (= nz (+ (. cell z) [offset-z (% j 4)])) + (var open [bool 4]) + (.open-sides self nx nz open) + (if (any-open open) + (.outline-add self nx nz open) + (.put (& (. self inside)) nx nz 1)) + (= found true) + (break)) + (if (! found) + (continue)) + (for (var j int 0) (< j 4) (++ j) + (var px int (+ nx [offset-x j])) + (var pz int (+ nz [offset-z j])) + (var s int (.get (& (. self outline)) px pz)) + (if (< s 0) + (continue)) + (.open-sides self px pz (. [(. self slots) s] open)) + (if (any-open (. [(. self slots) s] open)) + (continue)) + (.outline-remove self px pz) + (.put (& (. self inside)) px pz 1)))) + + ;; Every cell of the shape, outline and inside, added to SET at + ;; (x0 + x, z0 + z). + (pub fn add-to ((self (* const natural-shape)) (set (* cell-map)) (x0 int) (z0 int)) void + (for (var i int 0) (< i (. self slot-count)) (++ i) + (var c (* const shape-cell) (& [(. self slots) i])) + (if (. c live) + (.put set (+ x0 (. c x)) (+ z0 (. c z)) 1))) + (var in (* const cell-map) (& (. self inside))) + (for (var i int 0) (< i (. in cap)) (++ i) + (if (== [(. in state) i] 1) + (.put set (+ x0 (cast (>> [(. in keys) i] 32) i32)) + (+ z0 (cast (& [(. in keys) i] 4294967295) i32)) 1)))) + + (pub fn release ((self (* natural-shape))) void + (free (. self slots)) + (free (. self free)) + (.release (& (. self outline))) + (.release (& (. self inside))))) diff --git a/src/verify.sex b/src/verify.sex new file mode 100644 index 0000000..2922f45 --- /dev/null +++ b/src/verify.sex @@ -0,0 +1,110 @@ +;;; Diffs generated region maps against what a save stored, region by +;;; region over everything the save has. A port is right when every +;;; map matches to the pixel, padding included. + +(include stdio.h stdlib.h string.h) +(import maps) +(import lcg) +(import noise) +(import json) +(import shape) +(import save) +(import worldgen) +(import img) + +(define MAP-KINDS 6) + +(var map-names [(* const char) 6] #("landform" "climate" "province" "upheaval" "ocean" "strata")) + +(record tally ((compared i64) (matched i64) (regions int) (size-mismatch int))) + +(fn map-of ((m (* region-maps)) (kind int) (stratum int)) (* int-map) + (switch kind + (case 0 (return (& (. m landform)))) + (case 1 (return (& (. m climate)))) + (case 2 (return (& (. m geoprov)))) + (case 3 (return (& (. m upheaval)))) + (case 4 (return (& (. m ocean)))) + (default (return (& [(. m strata) stratum]))))) + +;;; Compares one map; marks the region's cell in DIFF (CELL pixels a +;;; side at OX, OZ): grey where the inner pixel matches, red where not. +(fn compare ((want (* const int-map)) (got (* const int-map)) (t (* tally)) + (diff (* image)) (ox int) (oz int) (cell int)) void + (if (|| (! (. got data)) (! (. want data))) + (return)) + (++ (. t regions)) + (if (!= (. want size) (. got size)) + (do (++ (. t size-mismatch)) (return))) + (var n int (* (. want size) (. want size))) + (for (var i int 0) (< i n) (++ i) + (++ (. t compared)) + (if (== [(. want data) i] [(. got data) i]) + (++ (. t matched)))) + (var inner int (- (. want size) (. want pad-tl) (. want pad-br))) + (for (var y int 0) (< y cell) (++ y) + (for (var x int 0) (< x cell) (++ x) + (var i int (+ (* (+ (. want pad-tl) (/ (* y inner) cell)) (. want size)) + (. want pad-tl) (/ (* x inner) cell))) + (var ok bool (== [(. want data) i] [(. got data) i])) + (.set diff (+ ox x) (+ oz y) (if ok (grey 96) 16719904))))) + +(pub fn verify-stories ((s (* save)) (g (* worldgen))) int + (var failed int 0) + (for (var i int 0) (< i (. g story-count)) (++ i) + (var mine (* story) (& [(. g stories) i])) + (var theirs (* story-location) NULL) + (for (var j int 0) (< j (. s story-count)) (++ j) + (if (== (strcmp (. [(. s stories) j] code) (. mine code)) 0) + (= theirs (& [(. s stories) j])))) + (var ok bool (&& theirs (== (. theirs x) (. mine x)) (== (. theirs z) (. mine z)))) + (if (! ok) (++ failed)) + (printf "story %-18s %8d %6d %s\n" (. mine code) (. mine x) (. mine z) + (if ok "ok" "MISMATCH"))) + (return failed)) + +(pub fn verify-regions ((s (* save)) (g (* worldgen)) (dir (* const char))) int + (var e extent (save/extent s "mapregion")) + (var cell int 32) + (var w int (* (+ (- (. e x1) (. e x0)) 1) cell)) + (var h int (* (+ (- (. e z1) (. e z0)) 1) cell)) + (var tallies [tally 6]) + (memset tallies 0 (sizeof tallies)) + (var diffs [image 6]) + (for (var k int 0) (< k MAP-KINDS) (++ k) + (= [diffs k] (image/make w h))) + + (var want region-maps) + (var got region-maps) + (for (var rz int (. e z0)) (<= rz (. e z1)) (++ rz) + (for (var rx int (. e x0)) (<= rx (. e x1)) (++ rx) + (if (! (save/region s rx rz (& want))) + (continue)) + (worldgen/region g rx rz (& got)) + (var ox int (* (- rx (. e x0)) cell)) + (var oz int (* (- rz (. e z0)) cell)) + (for (var k int 0) (< k 5) (++ k) + (compare (map-of (& want) k 0) (map-of (& got) k 0) (& [tallies k]) + (& [diffs k]) ox oz cell)) + (for (var i int 0) (< i (. got strata-count)) (++ i) + (compare (map-of (& want) 5 i) (map-of (& got) 5 i) (& [tallies 5]) + (& [diffs 5]) ox oz cell)) + (region-maps/free (& want)) + (region-maps/free (& got)))) + + (var failed int 0) + (for (var k int 0) (< k MAP-KINDS) (++ k) + (var t (* tally) (& [tallies k])) + (if (== (. t regions) 0) + (do (.release (& [diffs k])) (continue))) + (var percent double (/ (* 100.0 (. t matched)) (. t compared))) + (printf "%-9s %4d maps %10lld/%-10lld px %8.4f%%%s\n" [map-names k] (. t regions) + (. t matched) (. t compared) percent + (if (. t size-mismatch) " (size mismatch)" "")) + (if (!= (. t matched) (. t compared)) + (++ failed)) + (var path [char 1024]) + (snprintf path (sizeof path) "%s/diff-%s.png" dir [map-names k]) + (.write (& [diffs k]) path) + (.release (& [diffs k]))) + (return failed)) diff --git a/src/vsmv.sex b/src/vsmv.sex index b5e4841..7e28bcd 100644 --- a/src/vsmv.sex +++ b/src/vsmv.sex @@ -2,17 +2,25 @@ ;;; against a saved world and dumps what either side produced. (include stdio.h string.h) +;; An import brings in a module's own public forms but not the types +;; they mention, so dependencies come first. (import cs) (import json) +(import maps) +(import lcg) +(import noise) +(import shape) (import save) (import dump) +(import worldgen) +(import verify) (var worldgen-assets [(* const char) 6] #("landforms" "geologicprovinces" "rockstrata" "storystructures" "blocklayers" "deposits")) (fn usage () int - (fputs "usage: vsmv info SAVE.vcdbs\n vsmv seed TEXT...\n vsmv assets ASSETS-DIR\n vsmv dump SAVE.vcdbs OUT-DIR\n" + (fputs "usage: vsmv info SAVE.vcdbs\n vsmv seed TEXT...\n vsmv assets ASSETS-DIR\n vsmv dump SAVE.vcdbs OUT-DIR\n vsmv verify SAVE.vcdbs ASSETS-DIR OUT-DIR\n" stderr) (return 2)) @@ -65,6 +73,26 @@ (cJSON-Delete j)) (return bad)) +;;; Generates every region the save stored, with the save's own world +;;; settings, and diffs the maps. +(fn verify ((save-path (* const char)) (assets-dir (* const char)) (out (* const char))) int + (var s (* save) (save/open save-path)) + (if (! s) + (return 1)) + (var settings world-settings (world-settings/defaults)) + (= (. settings seed) (. s seed)) + (= (. settings size-x) (. s size-x)) + (= (. settings size-y) (. s size-y)) + (= (. settings size-z) (. s size-z)) + (for (var i int 0) (< i (. s config-count)) (++ i) + (.set (& settings) [(. s config-keys) i] [(. s config-values) i])) + (var g (* worldgen) (worldgen/make settings assets-dir)) + (if (! g) + (return 1)) + (var failed int (+ (verify-stories s g) (verify-regions s g out))) + (save/close s) + (return failed)) + (pub fn main ((argc int) (argv [* char])) int (if (< argc 2) (return (usage))) @@ -86,4 +114,6 @@ (dump s [argv 3]) (save/close s) (return 0))) + (if (&& (== (strcmp cmd "verify") 0) (== argc 5)) + (return (verify [argv 2] [argv 3] [argv 4]))) (return (usage))) diff --git a/src/worldgen.sex b/src/worldgen.sex new file mode 100644 index 0000000..11b4633 --- /dev/null +++ b/src/worldgen.sex @@ -0,0 +1,927 @@ +;;; The region-map side of world generation: GenMaps and the map layers +;;; it builds, producing for one map region the same IntDataMap2Ds the +;;; game stores. Everything here is a function of the world settings, +;;; the worldgen assets and the region's coordinates. + +(include stdio.h stdlib.h string.h math.h) +(import maps) +(import lcg) +(import noise) +(import json) +(import shape) + +(pub define MAX-PROVINCES 32) + +;;; The world settings worldgen reads, with the game's defaults. +(pub record world-settings + ((seed i32) (size-x int) (size-y int) (size-z int) + (landcover float) (oceanscale float) (landform-scale float) + (upheaval-commonness float) (geologic-activity float) + (polar-equator-distance int) (global-temperature float) + (global-precipitation float) (realistic-climate bool) + (starting-climate [char 16]) (story-dist-scaling float))) + +(ops world-settings + (pub fn defaults () world-settings + (var s world-settings) + (memset (& s) 0 (sizeof s)) + (= (. s size-x) 1024000) + (= (. s size-y) 256) + (= (. s size-z) 1024000) + (= (. s landcover) 1) + (= (. s oceanscale) 1) + (= (. s landform-scale) 1) + (= (. s upheaval-commonness) 0.3) + (= (. s geologic-activity) 0.05) + (= (. s polar-equator-distance) 50000) + (= (. s global-temperature) 1) + (= (. s global-precipitation) 1) + (= (. s realistic-climate) true) + (= (. s story-dist-scaling) 1) + (return s)) + + ;; One world config value, as the game's config tree spells it. + ;; Unknown keys are ignored. + (pub fn set ((self (* world-settings)) (key (* const char)) (value (* const char))) void + (if (== (strcmp key "landcover") 0) (= (. self landcover) (strtof value NULL)) + (== (strcmp key "oceanscale") 0) (= (. self oceanscale) (strtof value NULL)) + (== (strcmp key "landformScale") 0) (= (. self landform-scale) (strtof value NULL)) + (== (strcmp key "upheavelCommonness") 0) + (= (. self upheaval-commonness) (strtof value NULL)) + (== (strcmp key "geologicActivity") 0) + (= (. self geologic-activity) (strtof value NULL)) + (== (strcmp key "polarEquatorDistance") 0) + (= (. self polar-equator-distance) (atoi value)) + (== (strcmp key "globalTemperature") 0) + (= (. self global-temperature) (strtof value NULL)) + (== (strcmp key "globalPrecipitation") 0) + (= (. self global-precipitation) (strtof value NULL)) + (== (strcmp key "worldClimate") 0) + (= (. self realistic-climate) (== (strcmp value "realistic") 0)) + (== (strcmp key "startingClimate") 0) + (snprintf (. self starting-climate) 16 "%s" value) + (== (strcmp key "storyStructuresDistScaling") 0) + (= (. self story-dist-scaling) (strtof value NULL))))) + +;;; Geologic provinces ---------------------------------------------- + +;;; NoiseGeoProvince plus MapLayerGeoProvince: a weighted random +;;; province per 64x64 cell of province-map pixels, sampled through a +;;; wobble so the cells don't show. +(pub record province-layer + ((rng lcg) (weights [int MAX_PROVINCES]) (count int) (weight-sum int) + (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise)))) + +(define GEOPROV-MAP-SCALE 64) + +(ops province-layer + (pub fn make ((seed i64) (provinces (* cJSON))) province-layer + (var p province-layer) + (memset (& p) 0 (sizeof p)) + (= (. p rng) (lcg/make seed)) + (var variants (* cJSON) (cJSON-GetObjectItem provinces "variants")) + (for (var v (* cJSON) (. variants child)) (&& v (< (. p count) MAX-PROVINCES)) (= v (. v next)) + (var w int (cast (cJSON-GetNumberValue (cJSON-GetObjectItem v "weight")) int)) + (= [(. p weights) (. p count)] w) + (+= (. p weight-sum) w) + (++ (. p count))) + (var wscale float (* 1.5 GEOPROV-MAP-SCALE)) + (var frequency float (/ (cast 0.4 float) wscale)) + (= (. p wobble-x) (simplex-noise/octaves 4 frequency (cast 0.9 float) (+ seed 2))) + (= (. p wobble-z) (simplex-noise/octaves 4 frequency (cast 0.9 float) (+ seed 1231296))) + (return p)) + + (fn index-at ((self (* province-layer)) (x int) (z int)) int + (.init-position (& (. self rng)) x z) + (var r int (.next-int (& (. self rng)) (. self weight-sum))) + (var i int 0) + (for (= i 0) (< i (. self count)) (++ i) + (-= r [(. self weights) i]) + (if (<= r 0) + (return i))) + (return i)) + + (pub fn gen ((self (* province-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (var wobble float (* GEOPROV-MAP-SCALE (cast 1.5 float))) + (for (var x int 0) (< x size-x) (++ x) + (for (var z int 0) (< z size-z) (++ z) + (var ox int (cast (* wobble (.noise-2d (. self wobble-x) (+ x0 x) (+ z0 z))) int)) + (var oz int (cast (* wobble (.noise-2d (. self wobble-z) (+ x0 x) (+ z0 z))) int)) + (= [out (+ (* z size-x) x)] + (.index-at self (/ (+ x0 x ox) GEOPROV-MAP-SCALE) (/ (+ z0 z oz) GEOPROV-MAP-SCALE))))))) + +;;; MapLayerBlur: a separable box blur of each byte of each pixel, +;;; averaging only the pixels inside the map, in integers. +(fn blur-pixel ((sums (* const int)) (hits int)) u32 + (return (c-bit-or (<< (cast (cast (/ [sums 0] hits) u8) u32) 24) + (<< (cast (cast (/ [sums 1] hits) u8) u32) 16) + (<< (cast (cast (/ [sums 2] hits) u8) u32) 8) + (cast (cast (/ [sums 3] hits) u8) u32)))) + +(fn blur-add ((sums (* int)) (col int) (sign int)) void + (if (== col 0) + (return)) + (+= [sums 0] (* sign (& (>> col 24) 255))) + (+= [sums 1] (* sign (& (>> col 16) 255))) + (+= [sums 2] (* sign (& (>> col 8) 255))) + (+= [sums 3] (* sign (& col 255)))) + +;;; One line of the blur: LEN pixels STRIDE apart from MAP. +(fn blur-line ((map (* i32)) (start int) (stride int) (len int) (range int) (tmp (* u32))) void + (var half int (/ range 2)) + (var sums [int 4] #(0 0 0 0)) + (var hits int 0) + (for (var i int (- half)) (< i len) (++ i) + (var old int (- i half 1)) + (if (>= old 0) + (do + (blur-add sums [map (+ start (* old stride))] -1) + (-- hits))) + (var new int (+ i half)) + (if (< new len) + (do + (blur-add sums [map (+ start (* new stride))] 1) + (++ hits))) + (if (>= i 0) + (= [tmp i] (blur-pixel sums hits)))) + (for (var i int 0) (< i len) (++ i) + (= [map (+ start (* i stride))] (cast [tmp i] i32)))) + +(fn box-blur ((map (* i32)) (w int) (h int) (range int)) void + (var tmp (* u32) (malloc (* (if (> w h) w h) (sizeof u32)))) + (for (var y int 0) (< y h) (++ y) + (blur-line map (* y w) 1 w range tmp)) + (for (var x int 0) (< x w) (++ x) + (blur-line map x w h range tmp)) + (free tmp)) + +;;; Climate ---------------------------------------------------------- + +;;; NoiseClimateRealistic: temperature follows latitude (a sawtooth +;;; along z), rain and geologic activity are random per cell. A +;;; climate is packed as temperature << 16 | rain << 8 | activity. +(pub record climate-noise + ((rng lcg) (half-range double) (z-offset double) (temp-mul float) (rain-mul float) + (geologic-activity-inv float))) + +;;; Climate.TemperatureScaleConversion, 255f / 60f. +(var temperature-scale-conversion float 4.25) + +(fn clamp-int ((v int) (lo int) (hi int)) int + (return (if (< v lo) lo (if (> v hi) hi v)))) + +(fn descale-temperature ((t float)) int + (return (clamp-int (cast (* (+ t 20) temperature-scale-conversion) int) 0 255))) + +;;; Climate.GetScaledAdjustedTemperature at sea level: the packed byte +;;; back to degrees. +(fn scaled-temperature ((unscaled int)) int + (var t float (/ (- unscaled (/ (cast 0 float) (cast 1.5 float))) temperature-scale-conversion)) + (return (clamp-int (- (cast t int) 20) -20 40))) + +(fn lerp-masked ((lt int) (rt int) (lb int) (rb int) (lx float) (ly float) (mask int)) int + (var top float (+ (cast (& lt mask) float) (* (- (cast (& rt mask) float) (cast (& lt mask) float)) lx))) + (var bottom float (+ (cast (& lb mask) float) (* (- (cast (& rb mask) float) (cast (& lb mask) float)) lx))) + (return (& (cast (+ top (* (- bottom top) ly)) int) mask))) + +(ops climate-noise + (pub fn make ((world-seed i64) (s (* const world-settings))) climate-noise + (var c climate-noise) + (= (. c rng) (lcg/make (+ world-seed 1))) + (var climate-map-scale int 32) + (var climate-map-sub-scale int 16) + ;; Integer division, as the C# does it. + (= (. c half-range) (/ (/ (. s polar-equator-distance) climate-map-scale) climate-map-sub-scale)) + (var map-size-z double (/ (/ (cast (. s size-z) double) climate-map-scale) climate-map-sub-scale)) + (var min-temp int 6) + (var max-temp int 14) + (var start (* const char) (. s starting-climate)) + (if (== (strcmp start "hot") 0) (do (= min-temp 28) (= max-temp 32)) + (== (strcmp start "warm") 0) (do (= min-temp 19) (= max-temp 23)) + (== (strcmp start "cool") 0) (do (= min-temp -5) (= max-temp 1)) + (== (strcmp start "icy") 0) (do (= min-temp -15) (= max-temp -10))) + (var lo int (descale-temperature min-temp)) + (var hi int (descale-temperature max-temp)) + ;; Drawn before any position is set: the same for every seed's + ;; state, but not for every seed's mapGenSeed. + (var rnd-temp double (+ lo (.next-int (& (. c rng)) (+ (- hi lo) 1)))) + (var z-per-deg double (/ (. c half-range) 255)) + (= (. c z-offset) (- (* rnd-temp z-per-deg) (/ map-size-z 2))) + (= (. c temp-mul) (. s global-temperature)) + (= (. c rain-mul) (. s global-precipitation)) + (= (. c geologic-activity-inv) (/ (cast 1 float) (. s geologic-activity))) + (return c)) + + (fn random-climate ((self (* climate-noise)) (pos-z double)) int + (var rng (* lcg) (& (. self rng))) + (var temp-rnd int (- (.next-int rng 51) 35)) + (var a double 255) + (var p double (. self half-range)) + (var z double (+ pos-z (. self z-offset))) + (var pre-temp int (+ (cast (* (/ a p) (- p (fabs (- (fmod (fabs z) (* 2 p)) p)))) int) + temp-rnd)) + (var temperature int (clamp-int (cast (* pre-temp (. self temp-mul)) int) 0 255)) + (var rain int (cast (* (.next-int rng 256) (. self rain-mul)) int)) + (if (> rain 255) (= rain 255)) + (var g float (/ (cast (.next-int rng 256) float) (cast 255 float))) + (var activity double (* (pow g (. self geologic-activity-inv)) 255)) + (if (< activity 0) (= activity 0)) + (return (+ (<< temperature 16) (<< rain 8) (cast activity int)))) + + ;; GetLerpedClimateAt: the four corner climates smoothstep-blended, + ;; byte by byte (GameMath.BiSerpRgbColor). + (pub fn lerped ((self (* climate-noise)) (x double) (z double)) int + (var xi int (cast x int)) + (var zi int (cast z int)) + (var rng (* lcg) (& (. self rng))) + (.init-position rng xi zi) + (var lt int (.random-climate self z)) + (.init-position rng (+ xi 1) zi) + (var rt int (.random-climate self z)) + (.init-position rng xi (+ zi 1)) + (var lb int (.random-climate self z)) + (.init-position rng (+ xi 1) (+ zi 1)) + (var rb int (.random-climate self z)) + (var fx float (cast (- x xi) float)) + (var fz float (cast (- z zi) float)) + (var lx float (* fx fx (- (cast 3 float) (* (cast 2 float) fx)))) + (var ly float (* fz fz (- (cast 3 float) (* (cast 2 float) fz)))) + (return (+ (lerp-masked lt rt lb rb lx ly 255) + (lerp-masked lt rt lb rb lx ly 65280) + (lerp-masked lt rt lb rb lx ly 16711680))))) + +;;; Landforms --------------------------------------------------------- + +(pub define MAX-LANDFORMS 128) + +;;; A landform or a mutation of one. LandFormsByIndex order: the +;;; variants as listed, then every variant's mutations in turn. +(pub record landform + ((code [char 64]) (weight double) (use-climate bool) (min-temp float) (max-temp float) + (min-rain int) (max-rain int) (chance float) (first-mutation int) (mutation-count int))) + +(fn json-number ((o (* cJSON)) (key (* const char)) (fallback double)) double + (var v (* cJSON) (cJSON-GetObjectItem o key)) + (return (if (cJSON-IsNumber v) (cJSON-GetNumberValue v) fallback))) + +(fn read-landform ((o (* cJSON)) (l (* landform))) void + (memset l 0 (sizeof landform)) + (var code (* cJSON) (cJSON-GetObjectItem o "code")) + (if (cJSON-IsString code) + (snprintf (. l code) 64 "%s" (cJSON-GetStringValue code))) + (= (. l weight) (json-number o "weight" 0)) + (= (. l use-climate) (cJSON-IsTrue (cJSON-GetObjectItem o "useClimateMap"))) + (= (. l min-temp) (cast (json-number o "minTemp" -50) float)) + (= (. l max-temp) (cast (json-number o "maxTemp" 50) float)) + (= (. l min-rain) (cast (json-number o "minRain" 0) int)) + (= (. l max-rain) (cast (json-number o "maxRain" 255) int)) + (= (. l chance) (cast (json-number o "chance" 0) float)) + (= (. l first-mutation) -1)) + +(pub record landform-table ((all [landform MAX_LANDFORMS]) (count int) (variant-count int))) + +(pub fn landform-table/load ((json (* cJSON)) (t (* landform-table))) void + (memset t 0 (sizeof landform-table)) + (var variants (* cJSON) (cJSON-GetObjectItem json "variants")) + (for (var v (* cJSON) (. variants child)) v (= v (. v next)) + (read-landform v (& [(. t all) (. t count)])) + (++ (. t count))) + (= (. t variant-count) (. t count)) + (var i int 0) + (for (var v (* cJSON) (. variants child)) v (= v (. v next)) + (var mutations (* cJSON) (cJSON-GetObjectItem v "mutations")) + (var parent (* landform) (& [(. t all) i])) + (= (. parent first-mutation) (. t count)) + (for (var m (* cJSON) (if mutations (. mutations child) NULL)) m (= m (. m next)) + (read-landform m (& [(. t all) (. t count)])) + (++ (. t count)) + (++ (. parent mutation-count))) + (++ i))) + +(pub fn landform-table/find ((t (* const landform-table)) (code (* const char))) int + (for (var i int 0) (< i (. t count)) (++ i) + (if (== (strcmp (. [(. t all) i] code) code) 0) + (return i))) + (return -1)) + +(fn climate-excludes ((l (* const landform)) (temp int) (rain int)) bool + (if (! (. l use-climate)) + (return false)) + (var clamped-rain int (clamp-int rain (. l min-rain) (. l max-rain))) + (var t float (cast temp float)) + (var clamped-temp float (if (< t (. l min-temp)) (. l min-temp) + (if (> t (. l max-temp)) (. l max-temp) t))) + (return (|| (!= (- rain clamped-rain) 0) (!= (- t clamped-temp) 0)))) + +;;; MapLayerLandforms over NoiseLandforms. +(pub record landform-layer + ((rng lcg) (table (* const landform-table)) (climate climate-noise) (scale float) + (weights [double MAX_LANDFORMS]) + (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise)))) + +(define LANDFORM-MAP-SCALE 16) + +(ops landform-layer + (pub fn make ((seed i64) (table (* const landform-table)) (climate climate-noise) + (s (* const world-settings))) landform-layer + (var l landform-layer) + (memset (& l) 0 (sizeof l)) + (= (. l rng) (lcg/make seed)) + (= (. l table) table) + (= (. l climate) climate) + (var scale float (* LANDFORM-MAP-SCALE (. s landform-scale))) + (var height-scale float (/ (cast (. s size-y) float) (cast 256 float))) + (*= scale (if (> height-scale (cast 1 float)) height-scale (cast 1 float))) + (= (. l scale) scale) + (var wscale float (* (cast 2 float) LANDFORM-MAP-SCALE)) + (= (. l wobble-x) (simplex-noise/octaves 2 (/ (cast 1 float) wscale) (cast 0.9 float) (+ seed 2))) + (= (. l wobble-z) (simplex-noise/octaves 2 (/ (cast 1 float) wscale) (cast 0.9 float) (+ seed 1231296))) + (return l)) + + (fn parent-at ((self (* landform-layer)) (x int) (z int) (temp int) (rain int)) int + (.init-position (& (. self rng)) x z) + (var t (* const landform-table) (. self table)) + (var weight-sum double 0) + (for (var i int 0) (< i (. t variant-count)) (++ i) + (var l (* const landform) (& [(. t all) i])) + (var w double (. l weight)) + (if (climate-excludes l temp rain) + (= w 0)) + (= [(. self weights) i] w) + (+= weight-sum w)) + (var r double (/ (* weight-sum (.next-int (& (. self rng)) 10000)) 10000.0)) + (for (var i int 0) (< i (. t variant-count)) (++ i) + (-= r [(. self weights) i]) + (if (<= r 0) + (return i))) + (return (- (. t variant-count) 1))) + + (fn index-at ((self (* landform-layer)) (x int) (z int) (temp int) (rain int)) int + (var xs float (/ (cast x float) (. self scale))) + (var zs float (/ (cast z float) (. self scale))) + (var parent int (.parent-at self (cast xs int) (cast zs int) temp rain)) + (var p (* const landform) (& [(. (. self table) all) parent])) + (if (> (. p mutation-count) 0) + (do + (.init-position (& (. self rng)) (/ x 2) (/ z 2)) + (var chance float (/ (cast (.next-int (& (. self rng)) 101) float) (cast 100 float))) + (for (var i int 0) (< i (. p mutation-count)) (++ i) + (var m int (+ (. p first-mutation) i)) + (var mut (* const landform) (& [(. (. self table) all) m])) + (if (climate-excludes mut temp rain) + (continue)) + (-= chance (. mut chance)) + (if (<= chance 0) + (return m))))) + (return parent)) + + (pub fn gen ((self (* landform-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (var wobble float (* LANDFORM-MAP-SCALE (cast 1.5 float))) + (for (var x int 0) (< x size-x) (++ x) + (for (var z int 0) (< z size-z) (++ z) + (var ox int (cast (* (* wobble (.noise-2d (. self wobble-x) (+ x0 x) (+ z0 z))) + (cast 1.2 float)) int)) + (var oz int (cast (* (* wobble (.noise-2d (. self wobble-z) (+ x0 x) (+ z0 z))) + (cast 1.2 float)) int)) + (var fx int (+ x0 x ox)) + (var fz int (+ z0 z oz)) + (var climate int (.lerped (& (. self climate)) (/ fx 32) (/ fz 32))) + (var rain int (& (>> climate 8) 255)) + (var temp int (scaled-temperature (& (>> climate 16) 255))) + (= [out (+ (* z size-x) x)] (.index-at self fx fz temp rain)))))) + +;;; Oceans ----------------------------------------------------------- + +;;; MapLayerOceans under MapLayerBlur(5): per cell of `scale' pixels, +;;; land (0) with probability landcover, else ocean (255); wobbled, +;;; with forced land where spawn and story locations need it, then box +;;; blurred. +(pub record ocean-layer + ((rng lcg) (scale float) (landcover float) (wobble float) + (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise)) (require-land cell-map))) + +(define OCEAN-MAP-SCALE 32) + +(ops ocean-layer + (pub fn make ((seed i64) (s (* const world-settings))) ocean-layer + (var o ocean-layer) + (memset (& o) 0 (sizeof o)) + (= (. o rng) (lcg/make seed)) + (= (. o scale) (* OCEAN-MAP-SCALE (. s oceanscale))) + (= (. o landcover) (. s landcover)) + (= (. o wobble) (/ (* OCEAN-MAP-SCALE (. o scale)) OCEAN-MAP-SCALE)) + (var frequency float (/ (cast 1 float) (. o scale))) + (= (. o wobble-x) (simplex-noise/octaves 3 frequency (cast 0.9 float) (+ seed 2))) + (= (. o wobble-z) (simplex-noise/octaves 3 frequency (cast 0.9 float) (+ seed 1231296))) + (= (. o require-land) (cell-map/make)) + (return o)) + + (fn index-at ((self (* ocean-layer)) (x int) (z int)) int + (.init-position (& (. self rng)) (cast (/ x (. self scale)) int) (cast (/ z (. self scale)) int)) + (var r double (/ (.next-int (& (. self rng)) 10000) 10000.0)) + (return (if (< r (. self landcover)) 0 255))) + + ;; FORCED-LAND false leaves out the land forced around spawn and + ;; story locations, which is how Rivers samples this map. + (pub fn gen ((self (* ocean-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (forced-land bool) (out (* i32))) void + (for (var x int 0) (< x size-x) (++ x) + (for (var z int 0) (< z size-z) (++ z) + (var nx int (+ x0 x)) + (var nz int (+ z0 z)) + (var ox int (cast (* (. self wobble) (.noise-2d (. self wobble-x) nx nz)) int)) + (var oz int (cast (* (. self wobble) (.noise-2d (. self wobble-z) nx nz)) int)) + (var v int (.index-at self (+ nx ox) (+ nz oz))) + (if (&& (== v 255) forced-land (.has (& (. self require-land)) nx nz)) + (= v 0)) + (= [out (+ (* z size-x) x)] v))) + (box-blur out size-x size-z 5))) + +;;; GenMaps.ForceRandomLandArea: a natural blob of forced land covering +;;; RADIUS blocks around (x, z), in ocean map pixels. +(fn force-land-area ((o (* ocean-layer)) (seed i64) (x int) (z int) (radius int)) void + (var n int (/ 512 OCEAN-MAP-SCALE)) + (var min-x int (/ (* (- x radius) n) 512)) + (var min-z int (/ (* (- z radius) n) 512)) + (var max-x int (/ (* (+ x radius) n) 512)) + (var max-z int (/ (* (+ z radius) n) 512)) + (var rng lcg (lcg/make seed)) + (.init-position (& rng) x z) + (var size-x int (- max-x min-x)) + (var size-z int (- max-z min-z)) + (var blob natural-shape (natural-shape/square (& rng) size-x size-z)) + (.grow (& blob) (* size-x size-z)) + (.add-to (& blob) (& (. o require-land)) min-x min-z) + (.release (& blob))) + +;;; Upheaval --------------------------------------------------------- + +;;; MapLayerPerlinUpheavel under MapLayerBlur(3): where low-frequency +;;; noise rises above 1 - upheavelCommonness, terrain is pushed up. +(pub record upheaval-layer ((noise (* simplex-noise)) (noise-offset float))) + +(ops upheaval-layer + (pub fn make ((seed i64) (s (* const world-settings))) upheaval-layer + (var scale float 64) + (var amplitudes [double 4] #(1 0.5 0.25 0.15)) + (var frequencies [double 4]) + (= [frequencies 0] (/ 0.5 scale)) + (= [frequencies 1] (/ (cast 1 float) scale)) + (= [frequencies 2] (/ (cast 2 float) scale)) + (= [frequencies 3] (/ (cast 4 float) scale)) + (var u upheaval-layer) + (= (. u noise) (simplex-noise/make amplitudes frequencies 4 (+ seed 1685))) + (= (. u noise-offset) (- (cast 1 float) (. s upheaval-commonness))) + (return u)) + + (pub fn gen ((self (* upheaval-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (var out-value double (+ -300 (cast 600 float))) + (for (var z int 0) (< z size-z) (++ z) + (for (var x int 0) (< x size-x) (++ x) + (var low double (* (- (.noise-2d (. self noise) (+ x0 x) (+ z0 z)) (. self noise-offset)) 15)) + (= low (fmin (fmax low 0) 1)) + (= [out (+ (* z size-x) x)] (cast (fmin (fmax (* low out-value) 0) 255) int)))) + (box-blur out size-x size-z 3))) + +;;; Climate map ------------------------------------------------------ + +;;; MapLayerClimate under MapLayerPerlinWobble: the climate noise +;;; sampled every 16 pixels and smoothstep-lerped between, then +;;; displaced by a wobble. +(pub record climate-layer + ((noise climate-noise) (intensity float) + (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise)))) + +(define CLIMATE-SUB-SCALE 16) + +(ops climate-noise + ;; GetClimateAt: one cell's climate, unlerped. + (pub fn at ((self (* climate-noise)) (x int) (z int)) int + (.init-position (& (. self rng)) x z) + (return (.random-climate self z)))) + +(fn lerp-cache ((x double) (z double) (cache (* const i32)) (w int)) int + (var xi int (cast x int)) + (var zi int (cast z int)) + (var fx float (cast (- x xi) float)) + (var fz float (cast (- z zi) float)) + (var lx float (* fx fx (- (cast 3 float) (* (cast 2 float) fx)))) + (var ly float (* fz fz (- (cast 3 float) (* (cast 2 float) fz)))) + (var lt int [cache (+ (* zi w) xi)]) + (var rt int [cache (+ (* zi w) xi 1)]) + (var lb int [cache (+ (* (+ zi 1) w) xi)]) + (var rb int [cache (+ (* (+ zi 1) w) xi 1)]) + (return (+ (lerp-masked lt rt lb rb lx ly 255) + (lerp-masked lt rt lb rb lx ly 65280) + (lerp-masked lt rt lb rb lx ly 16711680)))) + +(ops climate-layer + (pub fn make ((seed i64) (noise climate-noise)) climate-layer + (var c climate-layer) + (= (. c noise) noise) + (var scale float 192) + (= (. c intensity) (* scale (cast 0.15 float))) + (var frequency float (/ (cast 1 float) scale)) + (= (. c wobble-x) (simplex-noise/octaves 6 frequency (cast 0.7 float) seed)) + (= (. c wobble-z) (simplex-noise/octaves 6 frequency (cast 0.7 float) (+ seed 1231296))) + (return c)) + + (fn gen-unwobbled ((self (* climate-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (var cache-w int (+ (cast (ceil (/ (cast size-x float) CLIMATE-SUB-SCALE)) int) 1)) + (var cache-h int (+ (cast (ceil (/ (cast size-z float) CLIMATE-SUB-SCALE)) int) 1)) + (var cx int (cast (floor (/ (cast x0 float) CLIMATE-SUB-SCALE)) int)) + (var cz int (cast (floor (/ (cast z0 float) CLIMATE-SUB-SCALE)) int)) + (var cache (* i32) (malloc (* cache-w cache-h (sizeof i32)))) + (for (var x int 0) (< x cache-w) (++ x) + (for (var z int 0) (< z cache-h) (++ z) + (= [cache (+ (* z cache-w) x)] (.at (& (. self noise)) (+ cx x) (+ cz z))))) + (for (var x int 0) (< x size-x) (++ x) + (for (var z int 0) (< z size-z) (++ z) + (= [out (+ (* z size-x) x)] + (lerp-cache (/ x (cast CLIMATE-SUB-SCALE double)) (/ z (cast CLIMATE-SUB-SCALE double)) + cache cache-w)))) + (free cache)) + + (pub fn gen ((self (* climate-layer)) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (var margin int (cast (ceil (. self intensity)) int)) + (var pw int (+ size-x (* 2 margin))) + (var ph int (+ size-z (* 2 margin))) + (var in (* i32) (malloc (* pw ph (sizeof i32)))) + (.gen-unwobbled self (- x0 margin) (- z0 margin) pw ph in) + (for (var y int 0) (< y size-z) (++ y) + (for (var x int 0) (< x size-x) (++ x) + (var nx double (+ x0 x margin)) + (var nz double (+ z0 y margin)) + (var ox int (cast (* (. self intensity) (.noise-2d (. self wobble-x) nx nz)) int)) + (var oz int (cast (* (. self intensity) (.noise-2d (. self wobble-z) nx nz)) int)) + (var sx int (% (+ (% (+ x ox (/ margin 2)) pw) pw) pw)) + (var sz int (% (+ (% (+ y oz (/ margin 2)) ph) ph) ph)) + (= [out (+ (* y size-x) x)] [in (+ (* sz pw) sx)]))) + (free in))) + +;;; Rock strata thickness --------------------------------------------- + +;;; MapLayerCustomPerlin per stratum of rockstrata.json: how thick +;;; that stratum may be, in blocks, per 16 blocks of region. +(pub record strata-layer + ((count int) (noises [* simplex-sum MAX_STRATA]) (thresholds [* double MAX_STRATA]))) + +(fn json-doubles ((o (* cJSON)) (key (* const char)) (out (* double)) (max int)) int + (var arr (* cJSON) (cJSON-GetObjectItem o key)) + (var n int 0) + (for (var v (* cJSON) (if arr (. arr child) NULL)) (&& v (< n max)) (= v (. v next)) + (= [out n] (cJSON-GetNumberValue v)) + (++ n)) + (return n)) + +(ops strata-layer + (pub fn make ((world-seed i32) (rockstrata (* cJSON)) (size-y int)) strata-layer + (var l strata-layer) + (memset (& l) 0 (sizeof l)) + (var variants (* cJSON) (cJSON-GetObjectItem rockstrata "variants")) + (for (var v (* cJSON) (. variants child)) (&& v (< (. l count) MAX-STRATA)) (= v (. v next)) + (var amplitudes [double MAX_OCTAVES]) + (var frequencies [double MAX_OCTAVES]) + (var th (* double) (calloc MAX-OCTAVES (sizeof double))) + (var n int (json-doubles v "amplitudes" amplitudes MAX-OCTAVES)) + (json-doubles v "frequencies" frequencies MAX-OCTAVES) + (json-doubles v "thresholds" th MAX-OCTAVES) + (for (var j int 0) (< j n) (++ j) + (/= [frequencies j] 32) + (*= [amplitudes j] size-y) + (*= [th j] size-y)) + (var seed i64 (+ (cast (+ world-seed 23423 (. l count)) i64) 12321)) + (= [(. l noises) (. l count)] (simplex-sum/make amplitudes frequencies n seed)) + (= [(. l thresholds) (. l count)] th) + (++ (. l count))) + (return l)) + + (pub fn gen ((self (* strata-layer)) (i int) (x0 int) (z0 int) (size-x int) (size-z int) + (out (* i32))) void + (for (var z int 0) (< z size-z) (++ z) + (for (var x int 0) (< x size-x) (++ x) + (var v double (.noise-2d-thresholded [(. self noises) i] (+ x0 x) (+ z0 z) + [(. self thresholds) i])) + (= [out (+ (* z size-x) x)] (cast (fmin (fmax v 0) 255) int)))))) + +;;; Story structures ------------------------------------------------- + +(pub define MAX-STORY-LOCATIONS 16) + +;;; A story location as GenStoryStructures places it, with what it +;;; forces on the region maps around it. +(pub record story + ((code [char 64]) (x int) (z int) (dir-x int) (landform-radius int) + (landform int) (forces-climate bool) (climate int))) + +(fn json-int ((o (* cJSON)) (key (* const char)) (fallback int)) int + (return (cast (json-number o key fallback) int))) + +(fn find-story ((stories (* story)) (count int) (code (* const char))) (* story) + (for (var i int 0) (< i count) (++ i) + (if (== (strcmp (. [stories i] code) code) 0) + (return (& [stories i])))) + (return NULL)) + +;;; GenStoryStructures.TryAddStoryLocation for every structure in +;;; storystructures.json, in order, from one LCGRandom re-seeded with +;;; seed + 1095 + i for each. Positions are relative to spawn (the map +;;; centre) or to the structure depended on, whose x direction is kept. +(fn place-stories ((json (* cJSON)) (s (* const world-settings)) + (landforms (* const landform-table)) (out (* story))) int + (var count int 0) + (var i int 0) + (var structures (* cJSON) (cJSON-GetObjectItem json "structures")) + (var rng lcg (lcg/make (+ (cast (. s seed) i64) 1095))) + (for (var c (* cJSON) (. structures child)) (&& c (< count MAX-STORY-LOCATIONS)) (= c (. c next)) + (.reseed (& rng) (+ (cast (. s seed) i64) 1095 i)) + (++ i) + (var scale double (. s story-dist-scaling)) + (var min-x int (cast (* (json-int c "minSpawnDistX" 0) scale) int)) + (var max-x int (cast (* (json-int c "maxSpawnDistX" 0) scale) int)) + (var min-z int (cast (* (json-int c "minSpawnDistZ" 0) scale) int)) + (var max-z int (cast (* (json-int c "maxSpawnDistZ" 0) scale) int)) + (var depends (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem c "dependsOnStructure"))) + (var base-x int 0) + (var base-z int 0) + (var dir-x int 0) + (if (&& depends (== (strcmp depends "spawn") 0)) + (do + (= base-x (/ (. s size-x) 2)) + (= base-z (/ (. s size-z) 2)) + (= dir-x (if (> (.next-float (& rng)) 0.5) -1 1))) + depends + (do + (var parent (* story) (find-story out count depends)) + (if (! parent) + (continue)) + (= base-x (. parent x)) + (= base-z (. parent z)) + (= dir-x (. parent dir-x))) + (continue)) + (var dir-z int (if (> (.next-float (& rng)) 0.5) -1 1)) + (var dist-x int (+ min-x (.next-int (& rng) (- (+ max-x 1) min-x)))) + (var dist-z int (+ min-z (.next-int (& rng) (- (+ max-z 1) min-z)))) + + (var st (* story) (& [out count])) + (memset st 0 (sizeof story)) + (snprintf (. st code) 64 "%s" (cJSON-GetStringValue (cJSON-GetObjectItem c "code"))) + (= (. st x) (+ base-x (* dist-x dir-x))) + (= (. st z) (+ base-z (* dist-z dir-z))) + (= (. st dir-x) dir-x) + (= (. st landform-radius) (json-int c "landformRadius" 0)) + (var landform (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem c "requireLandform"))) + (= (. st landform) (if landform (landform-table/find landforms landform) -1)) + (var force-temp (* cJSON) (cJSON-GetObjectItem c "forceTemperature")) + (var force-rain (* cJSON) (cJSON-GetObjectItem c "forceRain")) + (if (|| force-temp force-rain) + (do + (= (. st forces-climate) true) + (= (. st climate) + (+ (<< (descale-temperature (cast (json-number c "forceTemperature" 0) float)) 16) + (<< (json-int c "forceRain" 0) 8))))) + (++ count)) + (return count)) + +;;; GenMaps.forceLandform: stamps a story's landform in a disc of +;;; landform-radius around it, wobbled so the edge looks natural. +(fn force-landform ((m (* int-map)) (rx int) (rz int) (st (* const story)) + (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))) void + (var region-size int 512) + (var pad int (. m pad-tl)) + (var size int (- (. m size) (* 2 pad))) + (var wobble-blocks float 80) + (var wobble-px float (* (/ wobble-blocks region-size) size)) + (var pad-rel float (+ (/ (cast pad float) size) (/ wobble-blocks region-size))) + (var lo float (- pad-rel)) + (var hi float (+ 1 pad-rel)) + (var r int (. st landform-radius)) + (var start-x float (- (/ (cast (- (. st x) r) float) region-size) rx)) + (var end-x float (- (/ (cast (+ (. st x) r) float) region-size) rx)) + (var start-z float (- (/ (cast (- (. st z) r) float) region-size) rz)) + (var end-z float (- (/ (cast (+ (. st z) r) float) region-size) rz)) + (if (! (&& (>= end-x lo) (<= start-x hi) (>= end-z lo) (<= start-z hi))) + (return)) + (= start-x (- (* (fminf (fmaxf start-x lo) hi) size) pad)) + (= end-x (+ (* (fminf (fmaxf end-x lo) hi) size) pad)) + (= start-z (- (* (fminf (fmaxf start-z lo) hi) size) pad)) + (= end-z (+ (* (fminf (fmaxf end-z lo) hi) size) pad)) + (var radius-sq double (pow (* (/ (cast r double) region-size) size) 2)) + (var off-x double (* (- (/ (cast (. st x) double) region-size) rx) size)) + (var off-z double (* (- (/ (cast (. st z) double) region-size) rz) size)) + (for (var x int (cast start-x int)) (< x end-x) (++ x) + (for (var z int (cast start-z int)) (< z end-z) (++ z) + (var rsq double (+ (pow (- x off-x) 2) (pow (- z off-z) 2))) + (if (>= rsq radius-sq) + (continue)) + (var nx double (+ x (* rx size))) + (var nz double (+ z (* rz size))) + (var fx int (+ x (cast (* wobble-px (.noise-2d wobble-x nx nz)) int) pad)) + (var fz int (+ z (cast (* wobble-px (.noise-2d wobble-z nx nz)) int) pad)) + (if (&& (>= fx 0) (< fx (. m size)) (>= fz 0) (< fz (. m size))) + (= [(. m data) (+ (* fz (. m size)) fx)] (. st landform)))))) + +;;; GenMaps.forceNoUpheavel: flattens upheaval within 100 blocks +;;; beyond a story's landform radius, fading out with distance. +(fn force-no-upheaval ((m (* int-map)) (rx int) (rz int) (st (* const story))) void + (var region-size int 512) + (var pad int (. m pad-tl)) + (var size int (- (. m size) (* 2 pad))) + (var pad-rel float (+ (/ (cast pad float) size) (/ (cast 80 float) region-size))) + (var lo float (- pad-rel)) + (var hi float (+ 1 pad-rel)) + (var r int (+ (. st landform-radius) 100)) + (var start-x float (- (/ (cast (- (. st x) r) float) region-size) rx)) + (var end-x float (- (/ (cast (+ (. st x) r) float) region-size) rx)) + (var start-z float (- (/ (cast (- (. st z) r) float) region-size) rz)) + (var end-z float (- (/ (cast (+ (. st z) r) float) region-size) rz)) + (if (! (&& (>= end-x lo) (<= start-x hi) (>= end-z lo) (<= start-z hi))) + (return)) + (var radius-sq double (pow (* (/ (cast r double) region-size) size) 2)) + (var off-x double (* (- (/ (cast (. st x) double) region-size) rx) size)) + (var off-z double (* (- (/ (cast (. st z) double) region-size) rz) size)) + (= start-x (- (* (fminf (fmaxf start-x lo) hi) size) pad)) + (= end-x (+ (* (fminf (fmaxf end-x lo) hi) size) pad)) + (= start-z (- (* (fminf (fmaxf start-z lo) hi) size) pad)) + (= end-z (+ (* (fminf (fmaxf end-z lo) hi) size) pad)) + (for (var x int (cast start-x int)) (< x end-x) (++ x) + (for (var z int (cast start-z int)) (< z end-z) (++ z) + (var rsq double (+ (pow (- x off-x) 2) (pow (- z off-z) 2))) + (if (>= rsq radius-sq) + (continue)) + (var attn double (* (pow (- 1 (/ rsq radius-sq)) 3) 512)) + (var fx int (+ x pad)) + (var fz int (+ z pad)) + (if (&& (>= fx 0) (< fx (. m size)) (>= fz 0) (< fz (. m size))) + (do + (var i int (+ (* fz (. m size)) fx)) + (= [(. m data) i] (cast (fmax 0 (- [(. m data) i] attn)) int))))))) + +;;; GenMaps.ForceClimate: blends a story's climate in over its +;;; landform radius plus 300 blocks. PAD is the landform map's padding, +;;; not the climate map's: GenMaps passes the variable it last set. +(fn force-climate ((m (* int-map)) (rx int) (rz int) (pad int) (st (* const story))) void + (var region-size int 512) + (var size int (- (. m size) (. m pad-tl) (. m pad-br))) + (var pad-rel float (+ (/ (cast pad float) size) (/ (cast 80 float) region-size))) + (var lo float (- pad-rel)) + (var hi float (+ 1 pad-rel)) + (var transition float 300) + (var r float (+ (. st landform-radius) transition)) + (var start-x float (- (/ (- (. st x) r) region-size) rx)) + (var end-x float (- (/ (+ (. st x) r) region-size) rx)) + (var start-z float (- (/ (- (. st z) r) region-size) rz)) + (var end-z float (- (/ (+ (. st z) r) region-size) rz)) + (if (! (&& (>= end-x lo) (<= start-x hi) (>= end-z lo) (<= start-z hi))) + (return)) + (var radius-sq double (pow (* (/ (cast r double) region-size) size) 2)) + (var trans-sq double (pow (* (/ (cast transition double) region-size) size) 2)) + (var fade-start double (- (sqrt radius-sq) (sqrt trans-sq))) + (var off-x double (* (- (/ (cast (. st x) double) region-size) rx) size)) + (var off-z double (* (- (/ (cast (. st z) double) region-size) rz) size)) + (= start-x (- (* (fminf (fmaxf start-x lo) hi) size) pad)) + (= end-x (+ (* (fminf (fmaxf end-x lo) hi) size) pad)) + (= start-z (- (* (fminf (fmaxf start-z lo) hi) size) pad)) + (= end-z (+ (* (fminf (fmaxf end-z lo) hi) size) pad)) + (var force-rain int (& (>> (. st climate) 8) 255)) + (var force-temp int (& (>> (. st climate) 16) 255)) + (for (var x int (cast start-x int)) (< x end-x) (++ x) + (for (var z int (cast start-z int)) (< z end-z) (++ z) + (var rsq double (+ (pow (- x off-x) 2) (pow (- z off-z) 2))) + (if (>= rsq radius-sq) + (continue)) + (var fx int (+ x pad)) + (var fz int (+ z pad)) + (if (! (&& (>= fx 0) (< fx (. m size)) (>= fz 0) (< fz (. m size)))) + (continue)) + (var i int (+ (* fz (. m size)) fx)) + (var climate int [(. m data) i]) + (var activity int (& climate 255)) + (var rain int (& (>> climate 8) 255)) + (var temp int (& (>> climate 16) 255)) + (var fade double (fmax 0 (- (sqrt rsq) fade-start))) + (var t double (fmin 1 (/ fade fade-start))) + (var new-temp int (cast (+ force-temp (* (- temp force-temp) t)) int)) + (var new-rain int (cast (+ force-rain (* (- rain force-rain) t)) int)) + (= [(. m data) i] (+ (<< new-temp 16) (<< new-rain 8) activity))))) + +;;; The generator -------------------------------------------------- + +(pub record worldgen + ((settings world-settings) (provinces province-layer) (landform-table landform-table) + (landforms landform-layer) (oceans ocean-layer) (upheaval upheaval-layer) + (climate climate-layer) (strata strata-layer) + (stories [story MAX_STORY_LOCATIONS]) (story-count int) + (story-wobble-x (* simplex-noise)) (story-wobble-z (* simplex-noise)))) + +(pub fn worldgen/make ((settings world-settings) (assets-dir (* const char))) (* worldgen) + (var path [char 1024]) + (snprintf path (sizeof path) "%s/survival/worldgen/geologicprovinces.json" assets-dir) + (var provinces (* cJSON) (json-load path)) + (if (! provinces) + (return NULL)) + (snprintf path (sizeof path) "%s/survival/worldgen/landforms.json" assets-dir) + (var landforms (* cJSON) (json-load path)) + (if (! landforms) + (return NULL)) + (var g (* worldgen) (calloc 1 (sizeof worldgen))) + (= (. g settings) settings) + (var seed i64 (. settings seed)) + (= (. g provinces) (province-layer/make (+ seed 3 5) provinces)) + (landform-table/load landforms (& (. g landform-table))) + (var climate climate-noise (climate-noise/make seed (& (. g settings)))) + (= (. g landforms) (landform-layer/make (+ seed 4 12) (& (. g landform-table)) climate + (& (. g settings)))) + (snprintf path (sizeof path) "%s/survival/worldgen/storystructures.json" assets-dir) + (var stories (* cJSON) (json-load path)) + (if stories + (= (. g story-count) (place-stories stories (& (. g settings)) (& (. g landform-table)) + (. g stories)))) + (var wscale float (* (cast 2 float) LANDFORM-MAP-SCALE)) + (= (. g story-wobble-x) (simplex-noise/octaves 2 (/ (cast 1 float) wscale) (cast 0.9 float) (+ seed 2))) + (= (. g story-wobble-z) (simplex-noise/octaves 2 (/ (cast 1 float) wscale) (cast 0.9 float) + (+ seed 1231296))) + (= (. g upheaval) (upheaval-layer/make (+ seed 873) (& (. g settings)))) + (= (. g climate) (climate-layer/make (+ seed 3) climate)) + (snprintf path (sizeof path) "%s/survival/worldgen/rockstrata.json" assets-dir) + (var rockstrata (* cJSON) (json-load path)) + (if (! rockstrata) + (return NULL)) + (= (. g strata) (strata-layer/make (. settings seed) rockstrata (. settings size-y))) + (cJSON-Delete rockstrata) + ;; Forced land: spawn first, then every story that forces a landform. + (= (. g oceans) (ocean-layer/make (+ seed 1873) (& (. g settings)))) + (force-land-area (& (. g oceans)) seed (/ (+ (. settings size-x) 32) 2) + (/ (+ (. settings size-z) 32) 2) (* 4 32)) + (for (var i int 0) (< i (. g story-count)) (++ i) + (var st (* story) (& [(. g stories) i])) + (if (>= (. st landform) 0) + (force-land-area (& (. g oceans)) seed (. st x) (. st z) (+ (. st landform-radius) 32)))) + (cJSON-Delete stories) + (cJSON-Delete provinces) + (cJSON-Delete landforms) + (return g)) + +(define REGION-SIZE 512) + +(fn alloc-map ((m (* int-map)) (inner int) (pad int)) void + (= (. m size) (+ inner (* 2 pad))) + (= (. m pad-tl) pad) + (= (. m pad-br) pad) + (= (. m data) (malloc (* (. m size) (. m size) (sizeof i32))))) + +;;; GenMaps.OnMapRegionGen, for the maps generated so far. +(pub fn worldgen/region ((g (* worldgen)) (rx int) (rz int) (out (* region-maps))) void + (memset out 0 (sizeof region-maps)) + (var n int (/ REGION-SIZE GEOPROV-MAP-SCALE)) + (var pad int 3) + (alloc-map (& (. out geoprov)) n pad) + (.gen (& (. g provinces)) (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) + (. out geoprov data)) + + (= n (/ REGION-SIZE LANDFORM-MAP-SCALE)) + (= pad 4) + (alloc-map (& (. out landform)) n pad) + (.gen (& (. g landforms)) (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) + (. out landform data)) + (= n (/ REGION-SIZE OCEAN-MAP-SCALE)) + (= pad 5) + (alloc-map (& (. out ocean)) n pad) + (.gen (& (. g oceans)) (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) true + (. out ocean data)) + + (= n (/ REGION-SIZE 32)) + (= pad 2) + (alloc-map (& (. out climate)) n pad) + (.gen (& (. g climate)) (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) + (. out climate data)) + + (= pad 3) + (alloc-map (& (. out upheaval)) n pad) + (.gen (& (. g upheaval)) (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) + (. out upheaval data)) + + (= n (/ REGION-SIZE 16)) + (= pad 2) + (= (. out strata-count) (. g strata count)) + (for (var i int 0) (< i (. g strata count)) (++ i) + (alloc-map (& [(. out strata) i]) n pad) + (.gen (& (. g strata)) i (- (* rx n) pad) (- (* rz n) pad) (+ n (* 2 pad)) (+ n (* 2 pad)) + (. [(. out strata) i] data))) + + ;; GenMaps' forcing, in its order: per story landform then upheaval, + ;; then climate for every story that forces one. + (for (var i int 0) (< i (. g story-count)) (++ i) + (var st (* story) (& [(. g stories) i])) + (if (>= (. st landform) 0) + (do + (force-landform (& (. out landform)) rx rz st (. g story-wobble-x) (. g story-wobble-z)) + (force-no-upheaval (& (. out upheaval)) rx rz st)))) + (for (var i int 0) (< i (. g story-count)) (++ i) + (if (. [(. g stories) i] forces-climate) + (force-climate (& (. out climate)) rx rz (. out landform pad-tl) (& [(. g stories) i])))))