Files
VS-map-previewer/Plan.org
alex-eg 90b5d50fa5 read the save, the seed and the worldgen assets
The engine's save classes are closed, so the protobuf field numbers
were read off the data and matched to the map sizes TerraGenConfig
gives. vsmv dump renders what the save stored, as the reference the
generator will be diffed against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:56:14 +03:00

20 KiB
Raw Blame History

vs-map-viewer: plan

Goal

A desktop app that takes a Vintage Story 1.22.7 seed and world settings, reimplements the standard world generator plus the Rivers 5.0.3 mod, and shows:

  • a zoomable top-down map of the world;
  • a rock overlay: each column colored by its rock at the surface, at a chosen depth below the surface, or at an absolute Y. Clicking a rock in the legend highlights only that rock, which is how you find a given stratum.

Decisions so far:

  • The generator is our own port, written in Sex (~/dev/sex). This app is a field test for the language. No .NET and no game DLLs, at runtime or in development.
  • When something doesn't match the save, we stop and show the diffs. Whether to bring in more tooling is decided case by case.
  • The GUI is Nuklear on SDL3, using its SDL_Renderer backend (Metal on macOS). Map tiles are SDL textures.
  • Rivers is included, using its default config. A rivers.json can be loaded to override it.
  • Ground truth is the save in this directory, ktt9s village story-new.vcdbs. It was made with Rivers 5.0.3 and the default Rivers config.
  • Frugal by design. We compute only what the viewer window shows. The world is 2,048,000 × 25,600 blocks with height 320 (confirmed from the save's gamedata), and nothing ever iterates over the whole of it.

Upstream sources

Upstream is anegostudios/vsapi, vsessentialsmod and vssurvivalmod at their master heads. Each head is the "Updated to Version 1.22.7" commit from 2026-08-17. Since 1.22, the worldgen lives in vsessentialsmod. Rivers is at github.com/glutzer/Rivers-Mod, HEAD 98f75e8, which is the 5.0.3 release. All of this code is proprietary or All Rights Reserved: we may "read it and learn from it". We write our own port and never redistribute their code verbatim.

Area Upstream
Seed string → int vsapi/Math/GameMath.cs DotNetStringHash
RNG vsapi LCGRandom
Noise vsapi SimplexNoise, NormalizedSimplexNoise, NewNormalizedSimplexFractalNoise, SimplexOctave
2D containers vsapi IntDataMap2D, NaturalShape
Region maps vsessentialsmod/Systems/WorldGen/Standard/ChunkGen/0.GenMaps/, MapLayer*, NoiseBase, LerpedWeightedIndex2DMap
Terrain height Rivers/src/WorldGenSystems/NewGenTerra.cs. This is a copy of vanilla .../1.GenTerra/GenTerra.cs plus the river code.
River layout Rivers/src/Rivers/RiverRegion.cs, RiverNode.cs, RiverGenerator.cs (SampleRiver), Api/RiversApi.cs (the river landform)
River noise Rivers/src/Noise/FastNoise.cs, Noise.cs
Rock strata .../ChunkGen/2.GenRockStrata/GenRockStrata.cs (GenRockStrataNew)
Strata for one column vssurvivalmod/Systems/Prospecting/ProPickWorkSpace.cs GetRockColumn
Dry-climate height raise .../GenBlockLayers.cs:185, patched by Rivers/src/Patches/BlockLayersPatches.cs
Forced story landforms vssurvivalmod GenStoryStructures, plus GenMaps.ForceLandformAt / ForceClimateAt

Assets come from assets/survival/worldgen/: landforms.json, geologicprovinces.json, rockstrata.json, storystructures.json, blocklayers.json and deposits.json. They are local and never committed. They are not strict JSON: keys are unquoted, and they may contain comments and trailing commas. Newtonsoft reads them leniently; cJSON does not. So the assets module needs a small JSON5-ish normalising pass before cJSON, or we patch cJSON to accept these files.

How the computation is structured

Everything is a 2D function of the column. We never build 3D chunks.

Level Size (blocks) What Cost
River plate 32768 × 32768 128×128 zone ocean flags, distance to ocean, river tree ~410k ocean-noise samples, once per plate
Map region 512 × 512 climate, ocean, upheaval, province, landform, strata thickness maps cheap 2D noise
Chunk (32 × 32) 32 × 32 the set of river segments near the chunk (exactness depends on it) a filter over the plate's segments
Column 1 × 1 river sample → valley blend → surfaceY → strata column 10–50 µs, dominated by 3D noise

The frugality rule: the view asks for tiles, and a tile asks for exactly the columns it shows. Columns pull in the regions, chunk segment sets and plates they need. Each of these is cached with an LRU. Nothing is ever computed "just in case".

The one unavoidable wide dependency is the river plate.

  • Rivers lays out the river network for a whole 32768-block plate at once. To know whether a river passes through the window, you need that plate's layout.
  • It is coarse (256-block zones) and runs once per plate.
  • Our port samples the ocean map 25 times per zone, about 410k samples per plate, where the original does about 11M. That should come in well under a second.
  • The world is 62.5 × 0.78 plates, so a window touches 1–2 plates.
  • The plate is computed lazily, in the background, and the map shows terrain without rivers until it is ready. Plates are independent of each other and deterministic.

Facts that shape the port

Vanilla

  • A rock column needs only 2D data. It depends on the region maps, the seed and surfaceY. ProPickWorkSpace.GetRockColumn does exactly this in the game.
  • Strata see the height before the dry-climate raise. Strata run at order 0.1, and GenBlockLayers (0.4) can later raise the stored WorldGenTerrainHeightMap in dry climates below sea level. For validation we compare against the raised value. Strata use the unraised one.
  • The seed hash is verified. DotNetStringHash("письки+жопки") is -90319180, which matches the seed stored in the save.
  • Story structures force landform and climate near spawn. The save's gamedata stores storystructurelocations, which gives us ground truth for the placement code.
  • Rock strata noise uses its own seeds. The distortion noises are seeded from SeaLevel+9876/9877, not from the world seed.
  • Order matters in two places:

    • rockstrata.json list order changes the result;
    • NoiseClimateRealistic draws its ZOffset from an unpositioned LCG.

Rivers

  • Layout RNG. It is LCGRandom(0), positioned at the plate coordinates. The world only enters through the ocean map: the blurred MapLayerOceans at seed+1873, with landcover and oceanscale applied.
  • The ocean map ignores forced land. Rivers samples it with requireLandAt (forced land at spawn and story locations) emptied. Our ocean layer needs a "no forced land" mode.
  • Zone ocean test. A zone is ocean if, at its centre chunk, the blurred ocean value × oceanicityFactor > oceanThreshold (30). The blur is a separable 5-tap integer box blur, truncating after each pass. The oceanicityFactor is MapSizeY/256*0.33333f, with integer division.
  • Distance to ocean. Upstream computes it with a BFS that is equivalent to the exact Euclidean distance between zone centres. We use a distance transform: same result, without the O(n²) cost.
  • RNG call order is the contract. We have to replicate it exactly:

    • zone scan, x outer and z inner;
    • FindHighestZone, a stable sort;
    • the FIFO generation queue;
    • per-river NextInt, NextDouble and NextFloat calls in upstream order. This includes AddLake rolling NextInt before its bounds check.
  • River sample per column. It is computed in plate-local coordinates and distorted by FastNoise (seeds 0 and 2). It yields riverDistance and bankFactor.

    • The candidate segments are the chunk's segment set, not the plate's. The distortion can reach segments outside a segment's envelope, so using the plate's set would give different results.
  • Valley blend. Applies when riverDistance < maxValleyWidth (150). A river landform is appended as the last landform index. Landform weights, octave amplitudes, thresholds and upheaval are lerped toward it, using valley noise (seed 0, freq 0.0008).
  • Carving. Applies when riverDistance < 0=. It removes blocks between baseline - bank and baseline + bank*topFactor. surfaceY is the highest solid block that remains, which can be a tunnel ceiling.
  • What Rivers leaves alone. Region maps and strata are not patched; strata change only through surfaceY.

    • Gravel beaches are cosmetic and only matter top-down: gravel on top, with the strata underneath. That's a later, optional layer.
    • We skip boulders.
  • FastNoise subset. We need OpenSimplex2 2D with FBm only, in its double-coordinate build. Perlin, Value, Cellular, Ridged and the other variants are dead code here.
  • Config is not in the save. It is read from ModConfig/rivers.json, which here means the defaults (RiverConfig.cs).
  • Not reproducible in the original either: an on-disk zone cache that ignores config changes, and live /riversettings edits. Neither applies to this world.
  • Ground truth for rivers is in the save. mapchunk moddata "riverDistance" is a ushort[1024], stored wherever some column has a distance ≤ 300. We can validate the layout and the per-column sample before touching terrain.

Determinism rules for the port

C# semantics that a naive C port gets wrong. Encode them once, in a cs-compat module, and use only that module:

  • Integer overflow wraps in C# (unchecked). This covers the LCG (x*6364136223846793005+1442695040888963407 on long) and the int hashes. In C, do the arithmetic in unsigned types, and also build with -fwrapv.
  • No FMA contraction. Clang on arm64 fuses a*b+c by default; .NET does not. Build with -ffp-contract=off and never with -ffast-math.
  • Keep float and double exactly as upstream has them. Both the vanilla noise layers and Rivers (riverSize, GetProjection, MathF.Pow) mix the two.
  • Truncating / and % on negatives match between C99 and C#. Use explicit floor helpers where upstream calls Math.Floor or FastFloor.
  • Casting an out-of-range float to (int) is undefined behaviour in C. Clamp it, or mirror the .NET x64 result (INT_MIN).
  • Statics. Upstream keeps mutable static state (NoiseLandforms, NoiseGeoProvince). We keep it in an explicit worldgen context struct instead, so changing settings regenerates cleanly.

Math.Pow, Sin, Cos and Atan2 may differ from macOS libm by an ulp. Accept that until validation says otherwise. In Rivers it could theoretically flip a node acceptance test.

Architecture

 settings (serverconfig.json / .vcdbs gamedata / UI) ──┐
 assets/survival/worldgen/*.json (lenient JSON → cJSON) ┤
 rivers.json (optional, else defaults) ─────────────────┤
                                                       ▼
                       worldgen context (seed, sizes, parsed assets, river config)
                                                       │
   plate cache (LRU) ── region cache (LRU) ── chunk segment-set cache (LRU)
                                                       │
     column query: river sample → valley blend → surfaceY → strata → rock at surface/depth/Y
                                                       │
     tile workers (pthreads): tiles in the view only, centre first, cancelled when the view moves
                                                       │
                Nuklear/SDL_Renderer UI: map, layers, settings, legend, probe

Modules. Each is a Sex module; the vsmv CLI and the GUI share them.

  • cs-compat: wrapping int math, LCG, DotNetStringHash, floor and lerp helpers, and the GameMath subset.
  • noise: vanilla simplex family and NaturalShape.
  • fastnoise: OpenSimplex2 2D with FBm.
  • maplayers: IntDataMap2D, NoiseBase, MapLayer* (including the ocean layer's no-forced-land mode), LerpedWeightedIndex2DMap, GenMaps region generation and story-structure forcing.
  • rivers: plate generation (zones, distance to ocean, river tree), chunk segment sets, SampleRiver, and the river landform.
  • terra: per-column surfaceY with the valley blend and carving, plus the dry-climate raise for validation.
  • strata: genBlockColumn, plus queries for "rock at depth d" and "rock at Y".
  • assets: lenient JSON loading and asset structs, plus a rock color palette. Hardcode the palette at first; take block texture averages later.
  • save: reads the .vcdbs through SQLite3, with a minimal protobuf wire reader. gamedata turned out to be plain protobuf.
  • tiles: tile pyramid, LRU caches, worker pool, cancellation.
  • ui: Nuklear + SDL3 SDL_Renderer. Tiles are SDL textures under the Nuklear panels.

Coordinates are shown like the in-game HUD, relative to the map centre ((MapSizeX+32)/2, (MapSizeZ+32)/2), with absolute coordinates available too. The viewer opens at spawn.

Phases

Each phase ends with a check against the save. A mismatch means stop, produce diff images and numbers, and decide together.

0. Skeleton

  • Repo layout, Makefile (sexc ... -- -ffp-contract=off -fwrapv), and a .gitignore for *.vcdbs*, *.zip and assets/.
  • Vendor nuklear.h. Take SDL3 from brew and sqlite3 from the system; cJSON is already here.
  • Create Sex-field-notes.org: a running log of language bugs and friction found while building this.

1. Save reader + seed + assets (done)

vsmv info, vsmv seed, vsmv assets and vsmv dump exist. The dump renders the save's stored maps as mosaics over the explored area, one per map. That turned out more useful than single-region dumps.

What the save turned out to be:

  • Encoding. Every blob is plain protobuf, with no compression. Rows are keyed by x | z << 27, in region units for mapregion and in chunk units for mapchunk.
  • gamedata:

    Field Contents
    1, 2, 3 MapSizeX/Y/Z: 2048000 × 320 × 25600
    7 seed
    11 mod data: key/value entries, including BlockIDs and storystructurelocations
    31 world config, as a binary TreeAttribute (type byte, .NET string key, value)
  • mapregion (ServerMapRegion). Every map is an IntDataMap2D with fields 1 data (packed), 2 size, 3 pad-tl, 4 pad-br.

    Field Map Size (pad)
    1 landform 40 (4)
    3 climate 20 (2)
    4 geologic province 14 (3)
    12 rock strata, one per stratum, in rockstrata.json order 36 (2)
    17 upheaval 22 (3)
    18 ocean 26 (5)

    The landform map is stored at landformMapScale 16 regardless of landformScale, which only scales the noise inside MapLayerLandforms.

    Not used: forest, shrub, flower and beach (2, 5, 6, 15), ore maps (8), mod data (9), ore distortion (13, 14), block patch maps (16), animal spawn maps (21).

  • mapchunk (ServerMapChunk). All ushort arrays are repeated, not packed.

    Field Contents
    1 mod data; Rivers' "riverDistance" is a serialized ushort[1024]
    3 rain height
    7 WorldGenTerrainHeightMap
    13 TopRockIdMap (block ids)
  • Assets. The six worldgen JSONs (and all 910 asset JSONs) parse after a relaxing pass: comments, unquoted keys and trailing commas. There are 48 landforms, 6 provinces and 16 strata.
  • 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%.

3. Minimal viewer

  • Nuklear panels, a pannable and zoomable tile map, and a layer switcher for the region maps.
  • Settings panel:

    • seed, world size, worldHeight;
    • landcover, oceanscale, landformScale, upheavelCommonness, geologicActivity;
    • worldClimate, polarEquatorDistance, globalTemperature/Precipitation, startingClimate.
  • River config section, with load from rivers.json.
  • Load settings from serverconfig.json or a .vcdbs.
  • Hover readout: coordinates, province, landform, climate.
  • Tiles exist only for the view.

4. Rivers layout

  • Port fastnoise (OpenSimplex2 2D FBm) and rivers:

    • zone ocean flags;
    • distance to ocean;
    • river tree, with the exact RNG call order;
    • chunk segment sets;
    • SampleRiver.
  • vsmv verify-rivers compares per-column riverDistance against the saved moddata in every stored map chunk.
  • Viewer: river layer (segments plus the riverDistance field), computed per plate in the background.

5. Terrain height

  • Port NewGenTerra's per-column path:

    • landform weights (lerped, radius 3) with the river landform;
    • valley blend;
    • warp distortion (seed+9876/+9878);
    • oceanicity and upheaval distY;
    • NoiseSign with the bounds early-out;
    • carving.
  • Port the dry-climate raise from GenBlockLayers, with the Rivers patch factor applied, so we can compare against stored heights. The Rivers transpiler is IL pattern matching, so whether it applies in 1.22.7 will show up in the diff.
  • vsmv verify-height compares against WorldGenTerrainHeightMap for all 11,414 stored map chunks. It reports the match percentage and writes a diff PNG.
  • Viewer: hillshaded terrain with water.

6. Rock strata + overlay

  • Port GenRockStrataNew.genBlockColumn:

    • province weights (lerped, radius 2) → per-group thickness budget;
    • distortion noises;
    • BottomUp/TopDown fill and the sedimentary thinning.
  • Queries: rock at the surface, at depth d, at absolute Y, and the full column.
  • Validation: surface rock against TopRockIdMap (if stored). Decode chunk blobs for full columns only if that isn't enough.
  • Viewer:

    • rock overlay with a mode switch (surface / depth / Y) and a slider;
    • legend with per-rock highlight;
    • click probe that shows the strata stack (rock, Y range, thickness).

7. Performance + polish

  • Level of detail:

    • zoomed out: one column per N blocks;
    • zoomed in: refined down to one per block.
  • Rough budget: a 1920×1080 view at 1 block/px is about 2M columns. That is about 60 s on one core, or under 10 s on all cores, rendered progressively.
  • Optional disk cache of tiles and plates, keyed by a hash of the settings.
  • Go-to-coordinates, PNG export of the current view.
  • Later: gravel-beach layer; ore deposits (GenDeposits.GeneratePartial is already on the ProPickWorkSpace path).

Risks

  • Bit-exactness of the noise and the Rivers trigonometry. The mitigations are the cs-compat rules and validating each phase before the next.
  • Undocumented blob layouts or compression in the vcdbs.
  • Mismatch between the Rivers source and the 5.0.3 build. The source HEAD and the DLL share a date, but we haven't verified the build. If the river diff says so, we can compare symbols against rivers_5.0.3.zip.
  • Sex gaps: threads, function pointers, unions, varargs interop. Log them in the field notes, and use small C shims when they block.
  • Version drift. Pin to VS 1.22.7 and Rivers 5.0.3.