Implement M9.4 revision-tagged microscopic environment rendering

Add SDL-free owned EnvironmentPresentation copied from M6.3 views (no
store pointers or validation tokens), a single-slot EnvironmentLayer that
rejects foreign/regressed updates and reports none/current/stale against
observed authority watermarks, and a bounded camera projection with
explicit missing, not-requested, present-zero, undefined-moisture and
stale encodings (at most 2313 clipped rectangles, reused buffer).

The engineering app renders a local in-memory fixture authority with
configurable refresh cadence and layer selection. ADR-0080 records the
decision; validation evidence and limits are in VALIDATION.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-01 17:45:53 -04:00
co-authored by Claude Opus 5.5
parent bb0412cd0f
commit feca07f791
20 changed files with 1393 additions and 62 deletions
+441
View File
@@ -0,0 +1,441 @@
#include "evo/render/environment.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <exception>
#include <limits>
#include <source_location>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo;
using client::EnvironmentCell;
using client::FieldPresence;
using client::Freshness;
using client::ViewError;
using render::EnvironmentDisplay;
using world::Field;
constexpr world::WorldIdentity identity{7, 9};
constexpr std::size_t budget = 4'000'000;
constexpr std::int64_t slice = -16000;
constexpr std::uint32_t mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7);
// 500 x 250 x 10 um^3 box at (250, 500) mm inside its voxel.
constexpr world::HabitatBox box{{250000}, {500000}, {0}, {500000}, {250000}, {10}};
constexpr std::uint64_t volume = 500000ULL * 250000ULL * 10ULL;
constexpr std::uint64_t water_amount = volume / 8; // log2 density -3.
constexpr std::uint64_t rock_capacity = 1'000'000'000'000ULL;
void check(bool ok, std::source_location at = std::source_location::current()) {
if (!ok)
throw std::runtime_error("client environment line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
template <typename T, typename E> bool refused(const std::expected<T, E>& r, E e) {
return !r && r.error() == e;
}
bool same(render::Color a, render::Color b) {
return a.red == b.red && a.green == b.green && a.blue == b.blue && a.alpha == b.alpha;
}
bool near(double a, double b, double tolerance = 1e-3) {
return std::abs(a - b) <= tolerance * std::max(1.0, std::abs(b));
}
bool rect_is(const render::Rectangle& r, double x, double y, double w, double h) {
return near(r.x, x) && near(r.y, y) && near(r.width, w) && near(r.height, h);
}
struct Stores {
std::unique_ptr<world::FieldStore> fields;
std::unique_ptr<world::ChunkStore> terrain;
std::vector<world::VoxelAddress> footprint;
};
// Sites x in [first, first+count), y = 0. Odd offsets use zero-capacity substrate 2.
Stores stores(std::int64_t first, std::int64_t count, bool full_voxel = false) {
Stores s;
std::vector<world::FieldSite> sites;
for (std::int64_t x = first; x < first + count; ++x) {
s.footprint.push_back({x, 0, slice});
const world::HabitatBox habitat =
full_voxel ? world::HabitatBox{{0}, {0}, {0}, {1000000}, {1000000}, {1}} : box;
sites.push_back({s.footprint.back(),
habitat,
{(x - first) % 2 == 0 ? std::uint16_t{1} : std::uint16_t{2}}});
}
// Zero-capacity substrate holds no water.
std::vector<std::uint64_t> water;
water.reserve(static_cast<std::size_t>(count));
for (std::int64_t i = 0; i < count; ++i)
water.push_back(i % 2 != 0 ? 0 : full_voxel ? 1000 : water_amount);
const std::uint64_t zero = 0, energy = 72;
const world::FieldOpening opening[]{{Field::water, water},
{Field::phosphorus, {&zero, 1}},
{Field::organic_energy, {&energy, 1}}};
const world::FieldDefaults defaults{{accounting::Femtograms{0},
accounting::Femtograms{rock_capacity},
accounting::Femtograms{0}}};
auto fields = world::FieldStore::create(identity, 1, defaults, sites, opening, budget);
CHECK(fields);
s.fields = std::move(*fields);
auto terrain = world::ChunkStore::create({}, 32, budget,
{{world::VolumeUnits{100}, world::VolumeUnits{100}}});
CHECK(terrain);
s.terrain = std::move(*terrain);
for (auto address : s.footprint)
CHECK(s.terrain->load(world::split(address, world::base_chunk_edge)->chunk));
return s;
}
client::EnvironmentPresentation present(const Stores& s, std::uint64_t tick,
std::size_t cells = 0) {
const std::span<const world::VoxelAddress> footprint{s.footprint.data(),
cells == 0 ? s.footprint.size() : cells};
auto view = world::query_environment(*s.fields, *s.terrain, tick, footprint, mask);
CHECK(view);
auto result = client::present_environment(*view, slice);
CHECK(result);
return std::move(*result);
}
client::Camera camera(client::Viewport viewport, client::WorldPoint centre, double scale) {
auto result = client::Camera::create(viewport, centre, scale);
CHECK(result);
return *result;
}
std::vector<render::Rectangle> build(const client::EnvironmentPresentation* p, Freshness f,
const client::Camera& c, EnvironmentDisplay d) {
std::vector<render::Rectangle> out;
CHECK(render::build_environment(out, p, f, c, d));
CHECK(out.size() <= render::max_environment_rectangles);
return out;
}
EnvironmentDisplay field(Field f) {
return {EnvironmentDisplay::Mode::field, f};
}
void known_fields() {
const auto s = stores(0, 2);
const auto p = present(s, 5);
CHECK(p.revision() == client::EnvironmentRevision{identity, 5, 0});
CHECK(p.cells().size() == 2 && p.cells()[0].volume.value == volume);
CHECK(p.cells()[0].presence[0] == FieldPresence::present &&
p.cells()[0].quantity[0] == water_amount);
CHECK(p.cells()[0].presence[1] == FieldPresence::missing && p.cells()[0].quantity[1] == 0);
CHECK(p.cells()[0].presence[3] == FieldPresence::not_requested);
// Voxel (0,0) fills a 1000x1000 viewport at 1 unit/mm; voxel (1,0) is culled.
const auto c = camera({1000, 1000, 2000, 2000}, {500, 500}, 1);
const auto water = build(&p, Freshness::current, c, field(Field::water));
CHECK(water.size() == 1 + 1 + 4 + 1 + render::environment_legend_steps);
CHECK(rect_is(water[0], 0, 0, 1000, 1000) && same(water[0].color, {96, 96, 104, 255}));
CHECK(rect_is(water[1], 250, 250, 500, 250));
CHECK(same(water[1].color, render::ramp(27.0 / 42.0))); // log2 density -3 on [-30, 12].
CHECK(rect_is(water[2], 0, 0, 1000, 1) && same(water[2].color, render::palette::voxel_outline));
CHECK(same(water[6].color, render::palette::status_current));
CHECK(rect_is(water[6], 928, 8, 64, 8));
const auto missing = build(&p, Freshness::current, c, field(Field::nitrogen));
CHECK(rect_is(missing[1], 250, 250, 250, 125) &&
same(missing[1].color, render::palette::missing_a));
CHECK(same(missing[2].color, render::palette::missing_b) &&
same(missing[3].color, render::palette::missing_b) &&
same(missing[4].color, render::palette::missing_a));
const auto unrequested = build(&p, Freshness::current, c, field(Field::organic_carbon));
for (std::size_t i = 1; i <= 4; ++i)
CHECK(same(unrequested[i].color, render::palette::not_requested));
CHECK(rect_is(unrequested[1], 250, 250, 500, 1)); // Hollow outline, not a fill.
const auto zero = build(&p, Freshness::current, c, field(Field::phosphorus));
CHECK(rect_is(zero[1], 250, 250, 500, 250) &&
same(zero[1].color, render::palette::present_zero));
const auto energy = build(&p, Freshness::current, c, field(Field::organic_energy));
CHECK(same(energy[1].color, render::ramp(0.0))); // 72 pJ / 1.25e12 um^3 clamps low.
const auto moisture = build(&p, Freshness::current, c, {EnvironmentDisplay::Mode::moisture});
CHECK(same(moisture[1].color, render::ramp(static_cast<double>(water_amount) /
static_cast<double>(rock_capacity))));
// Substrate 2 has zero water capacity: undefined, never zero or missing.
const auto right = camera({1000, 1000, 1000, 1000}, {1500, 500}, 1);
const auto undefined =
build(&p, Freshness::current, right, {EnvironmentDisplay::Mode::moisture});
CHECK(same(undefined[1].color, render::palette::undefined));
// Shrunk habitats (< 4 units) collapse encodings to one explicit rectangle.
const auto far = camera({1000, 1000, 1000, 1000}, {500, 500}, 0.005);
const auto small = build(&p, Freshness::current, far, field(Field::nitrogen));
CHECK(small.size() == 2 + 2 + 1 + render::environment_legend_steps);
CHECK(same(small[1].color, render::palette::missing_a));
CHECK(std::abs(render::ramp(0.5).green - 145) <= 1 && same(render::ramp(-1), render::ramp(0)) &&
same(render::ramp(2), render::ramp(1)) &&
same(render::ramp(std::numeric_limits<double>::quiet_NaN()), render::ramp(0)));
}
void seams() {
// Chunk seams at x = -16, 0 and 16 (edge 16), crossing negative coordinates.
const auto s = stores(-18, 36, true);
const auto p = present(s, 3);
CHECK(p.cells().size() == 36);
for (const double scale : {0.005, 0.0123, 0.0371})
for (const double centre_x : {0.0, 0.37, -731.25})
for (const client::Viewport view : {client::Viewport{1600, 400, 1600, 400},
client::Viewport{1600, 400, 2400, 1000}}) {
const auto c = camera(view, {centre_x, 500}, scale);
const auto out = build(&p, Freshness::current, c, field(Field::water));
const std::size_t group = 1000 * scale >= 8 ? 6 : 2;
CHECK(out.size() == 36 * group + 1 + render::environment_legend_steps);
for (std::size_t i = 0; i < 36; ++i) {
const auto& r = out[i * group];
const auto x = static_cast<double>(p.cells()[i].voxel.x) * 1000;
const auto left = c.world_to_screen({x, 0});
const auto right = c.world_to_screen({x + 1000, 0});
CHECK(left && right && near(r.x, left->x) && near(r.x + r.width, right->x));
CHECK(rect_is(out[i * group + 1], r.x, r.y, r.width, r.height));
if (i > 0) {
const auto& previous = out[(i - 1) * group];
CHECK(std::abs(previous.x + previous.width - r.x) <= 1e-3F);
CHECK(previous.y == r.y && previous.height == r.height);
}
}
}
// Upper world bound: a voxel's top edge lies on the exclusive camera limit.
const auto top = world::voxel_limit - 1;
EnvironmentCell cell;
cell.voxel = {top, top, 0};
cell.habitat = {{0}, {0}, {0}, {1000000}, {1000000}, {1}};
cell.volume = {1000000000000};
cell.terrain_material = {1};
cell.terrain_fill = world::fill_scale;
cell.presence[0] = FieldPresence::missing;
cell.moisture_status = world::MoistureStatus::missing_water;
const auto edge = client::EnvironmentPresentation::create({identity, 1, 0}, 1, 0, {&cell, 1});
CHECK(edge);
const double mm = static_cast<double>(top) * 1000;
const auto c = camera({100, 100, 100, 100}, {mm + 500, mm + 500}, 0.1);
const auto out = build(&*edge, Freshness::current, c, field(Field::water));
CHECK(rect_is(out[0], 0, 0, 100, 100) && out.size() == 1 + 4 + 4 + 9);
}
void freshness() {
auto s = stores(0, 4);
const auto fields_before = s.fields->snapshot();
const auto terrain_before = s.terrain->snapshot(identity);
client::EnvironmentLayer layer;
CHECK(layer.freshness() == Freshness::none && layer.current() == nullptr);
CHECK(layer.accept(present(s, 5)));
CHECK(layer.freshness() == Freshness::current && layer.current()->revision().tick == 5);
// Presenting and drawing never mutate authority state.
const auto c = camera({1000, 1000, 1000, 1000}, {500, 500}, 1);
(void)build(layer.current(), layer.freshness(), c, field(Field::water));
CHECK(s.fields->snapshot() == fields_before && s.terrain->snapshot(identity) == terrain_before);
auto view = world::query_environment(*s.fields, *s.terrain, 5, s.footprint, mask);
CHECK(view && s.fields->transfer(1, Field::water, 0, 2, 1));
CHECK(refused(world::validate_environment(*view, *s.fields, *s.terrain, 5),
world::EnvironmentError::stale_fields));
layer.mark_stale(); // Host evidence: local validation failed.
CHECK(layer.freshness() == Freshness::stale);
const auto stale = build(layer.current(), layer.freshness(), c, field(Field::water));
CHECK(same(stale[0].color, render::dim({96, 96, 104, 255})));
CHECK(same(stale[2].color, render::palette::stale_outline));
CHECK(same(stale[6].color, render::palette::status_stale));
auto newer = present(s, 6);
CHECK(newer.revision() == client::EnvironmentRevision{identity, 6, 1});
CHECK(newer.cells()[0].quantity[0] == water_amount - 1);
CHECK(layer.accept(newer) && layer.freshness() == Freshness::current);
// Out-of-order delivery of the older presentation is rejected without mutation.
CHECK(refused(layer.accept(present(s, 5)), ViewError::regressed));
CHECK(layer.current()->revision().tick == 6 && layer.freshness() == Freshness::current);
// Equal revision with a different footprint is accepted (camera moved).
CHECK(layer.accept(present(s, 6, 2)) && layer.current()->cells().size() == 2);
// Chunk revision regression for a shared voxel rejects.
auto cells = std::vector<EnvironmentCell>(layer.current()->cells().begin(),
layer.current()->cells().end());
const auto revision = layer.current()->revision();
cells[0].chunk_revision -= 1;
auto regressed = client::EnvironmentPresentation::create(revision, mask, slice, cells);
CHECK(regressed && refused(layer.accept(*regressed), ViewError::regressed));
// Foreign world/frame rejects; so do regressed watermarks.
auto foreign = client::EnvironmentPresentation::create({{7, 10}, 9, 9}, mask, slice,
layer.current()->cells());
CHECK(foreign && refused(layer.accept(*foreign), ViewError::foreign_world));
CHECK(refused(layer.observe({{8, 9}, 9, 9}), ViewError::foreign_world));
CHECK(refused(layer.observe({identity, 5, 1}), ViewError::regressed));
CHECK(layer.freshness() == Freshness::current);
CHECK(layer.observe({identity, 6, 1}) && layer.freshness() == Freshness::current);
CHECK(layer.observe({identity, 7, 1}) && layer.freshness() == Freshness::stale);
// A presentation that is newer than displayed but older than observed stays stale.
CHECK(layer.observe({identity, 9, 3}));
cells[0].chunk_revision += 1;
const auto between =
client::EnvironmentPresentation::create({identity, 8, 2}, mask, slice, cells);
CHECK(between && layer.accept(*between) && layer.freshness() == Freshness::stale);
// Watermark observed before the first presentation is retained.
client::EnvironmentLayer early;
CHECK(early.observe({identity, 9, 3}) && early.freshness() == Freshness::none);
CHECK(early.accept(*between) && early.freshness() == Freshness::stale);
early.reset();
CHECK(early.freshness() == Freshness::none && early.accept(present(s, 5)) &&
early.freshness() == Freshness::current);
early.reset();
early.mark_stale();
CHECK(early.freshness() == Freshness::none);
// The presentation is an owned copy: it outlives the stores it came from.
const auto copy = *layer.current();
s = {};
const auto after = build(&copy, Freshness::stale, c, field(Field::water));
CHECK(after.size() > 1 + render::environment_legend_steps);
}
void missing_and_invalid() {
const auto c = camera({640, 480, 640, 480}, {0, 0}, 1);
const auto none = build(nullptr, Freshness::current, c, field(Field::water));
CHECK(none.size() == 1 + render::environment_legend_steps);
CHECK(same(none[0].color, render::palette::status_none));
std::vector<render::Rectangle> out;
// Out-of-range enumerators model untrusted decoded values; rejecting them is the point.
// NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
const EnvironmentDisplay bad_field{EnvironmentDisplay::Mode::field, Field{10}};
// NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
const EnvironmentDisplay bad_mode{EnvironmentDisplay::Mode{2}, Field::water};
CHECK(refused(render::build_environment(out, nullptr, Freshness::none, c, bad_field),
render::EnvironmentRenderError::invalid_display));
CHECK(refused(render::build_environment(out, nullptr, Freshness::none, c, bad_mode),
render::EnvironmentRenderError::invalid_display));
const auto s = stores(0, 2);
const auto p = present(s, 5);
const auto hidden = build(&p, Freshness::none, c, field(Field::water));
CHECK(hidden.size() == none.size() && same(hidden[0].color, render::palette::status_none));
auto view = world::query_environment(*s.fields, *s.terrain, 5, s.footprint, mask);
CHECK(view && refused(client::present_environment(*view, slice + 1), ViewError::empty_slice));
const std::vector<EnvironmentCell> valid(p.cells().begin(), p.cells().end());
const auto revision = p.revision();
const auto create = [&](std::vector<EnvironmentCell> cells, std::uint32_t m = mask,
std::int64_t z = slice) {
return client::EnvironmentPresentation::create(revision, m, z, cells);
};
CHECK(create(valid));
CHECK(refused(create({}), ViewError::empty_slice));
CHECK(refused(create(valid, 0), ViewError::invalid_view));
CHECK(refused(create(valid, 1U << 10), ViewError::invalid_view));
CHECK(refused(create(valid, mask, world::voxel_limit), ViewError::invalid_view));
CHECK(refused(create({valid[1], valid[0]}), ViewError::invalid_view));
CHECK(refused(create({valid[0], valid[0]}), ViewError::invalid_view));
const auto broken = [&](auto mutate) {
auto cells = valid;
mutate(cells[0]);
return refused(create(cells), ViewError::invalid_view);
};
CHECK(broken([](EnvironmentCell& x) { x.voxel.z += 1; }));
CHECK(broken([](EnvironmentCell& x) { x.voxel.x = -world::voxel_limit - 1; }));
CHECK(broken([](EnvironmentCell& x) { x.habitat.x.value = 600000; }));
CHECK(broken([](EnvironmentCell& x) { x.habitat.width.value = 0; }));
CHECK(broken([](EnvironmentCell& x) { x.volume.value += 1; }));
CHECK(broken([](EnvironmentCell& x) { x.presence[3] = FieldPresence::missing; }));
CHECK(broken([](EnvironmentCell& x) { x.presence[1] = FieldPresence::not_requested; }));
CHECK(broken([](EnvironmentCell& x) { x.quantity[1] = 1; }));
CHECK(broken([](EnvironmentCell& x) { x.quantity[3] = 1; }));
CHECK(broken(
[](EnvironmentCell& x) { x.moisture_status = world::MoistureStatus::not_requested; }));
CHECK(broken([](EnvironmentCell& x) { x.moisture = {3, 2}; }));
CHECK(broken([](EnvironmentCell& x) { x.moisture = {0, 0}; }));
CHECK(broken(
[](EnvironmentCell& x) { x.moisture_status = world::MoistureStatus::missing_water; }));
std::vector<EnvironmentCell> many;
for (std::int64_t i = 0; i <= static_cast<std::int64_t>(client::max_environment_cells); ++i) {
auto cell = valid[0];
cell.voxel.x = i;
many.push_back(cell);
}
CHECK(refused(create(many), ViewError::too_many_cells));
many.pop_back();
CHECK(create(many));
}
void bounds_and_profile() {
// 256 voxels (16 x 16), every field requested; all quantities present.
std::vector<EnvironmentCell> cells;
for (std::int64_t x = -8; x < 8; ++x)
for (std::int64_t y = -8; y < 8; ++y) {
EnvironmentCell cell;
cell.voxel = {x, y, 0};
cell.habitat = box;
cell.volume = {volume};
cell.terrain_material = {static_cast<std::uint16_t>((x + y + 16) % 4)};
cell.terrain_fill = static_cast<std::uint16_t>((x + 8) * 4000);
for (std::size_t k = 0; k < world::field_count; ++k) {
const bool missing = (x + y + static_cast<std::int64_t>(k)) % 5 == 0;
cell.presence[k] = missing ? FieldPresence::missing : FieldPresence::present;
cell.quantity[k] = missing ? 0 : static_cast<std::uint64_t>((x + 9) * (y + 9)) << k;
}
cell.moisture_status = cell.presence[0] == FieldPresence::present
? world::MoistureStatus::available
: world::MoistureStatus::missing_water;
cell.moisture = {static_cast<std::uint64_t>(y + 8), 16};
cells.push_back(cell);
}
const auto p = client::EnvironmentPresentation::create({identity, 1, 1},
world::all_environment_fields, 0, cells);
CHECK(p && p->cells().size() == client::max_environment_cells);
std::vector<render::Rectangle> out;
CHECK(render::build_environment(out, &*p, Freshness::stale,
camera({1280, 1280, 1280, 1280}, {0, 0}, 0.07),
field(Field::water)));
const auto capacity = out.capacity();
CHECK(capacity >= render::max_environment_rectangles);
std::size_t largest = 0;
for (const double scale : {1e-4, 0.002, 0.07, 1.0, 50.0})
for (const client::WorldPoint centre :
{client::WorldPoint{0, 0}, {3333.5, -2500}, client::WorldPoint{900000, 900000}})
for (const auto freshness : {Freshness::current, Freshness::stale})
for (std::size_t mode = 0; mode <= world::field_count; ++mode) {
const auto display =
mode == world::field_count
? EnvironmentDisplay{EnvironmentDisplay::Mode::moisture}
: field(static_cast<Field>(mode));
const client::Viewport view{1280, 720, 2560, 1440};
CHECK(render::build_environment(out, &*p, freshness,
camera(view, centre, scale), display));
CHECK(out.size() <= render::max_environment_rectangles &&
out.capacity() == capacity);
largest = std::max(largest, out.size());
for (const auto& r : out)
CHECK(std::isfinite(r.x) && std::isfinite(r.y) && r.width > 0 &&
r.height > 0 && r.x >= 0 && r.y >= 0 && r.x + r.width <= 1280.01F &&
r.y + r.height <= 720.01F);
// The engineering host adds three UI rectangles to every frame.
std::vector<render::Rectangle> frame(out);
frame.resize(out.size() + 3, {0, 0, 1, 1, {}});
CHECK(render::Frame::create(frame));
}
CHECK(largest > std::size_t{256} * 2);
// Profile: dense visible scene, all cells with outlines and detail encodings.
const auto c = camera({1280, 1280, 1280, 1280}, {0, 0}, 0.075);
constexpr int rounds = 2000;
const auto start = std::chrono::steady_clock::now();
std::size_t total = 0;
for (int i = 0; i < rounds; ++i) {
CHECK(render::build_environment(out, &*p, Freshness::stale, c, field(Field::nitrogen)));
total += out.size();
}
const auto elapsed =
std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - start).count();
CHECK(out.capacity() == capacity);
std::printf("environment_profile cells=%zu rectangles=%zu max_rectangles=%zu "
"presentation_cell_bytes=%zu output_capacity_bytes=%zu build_us=%.2f\n",
p->cells().size(), total / rounds, render::max_environment_rectangles,
p->cells().size() * sizeof(EnvironmentCell), capacity * sizeof(render::Rectangle),
elapsed / rounds);
}
} // namespace
int main() try {
known_fields();
seams();
freshness();
missing_and_invalid();
bounds_and_profile();
std::puts("client environment tests passed");
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
return 1;
}