Complete M6.3 read-only environment views
This commit is contained in:
+7
-1
@@ -34,7 +34,7 @@ target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in
|
||||
target_compile_features(evo_simulation PUBLIC cxx_std_23)
|
||||
evo_owned_target(evo_simulation)
|
||||
|
||||
set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp src/world/fields.cpp)
|
||||
set(evo_world_sources src/world/coordinates.cpp src/world/generation.cpp src/world/chunks.cpp src/world/edits.cpp src/world/codec.cpp src/world/local_files.cpp src/world/environment_units.cpp src/world/fields.cpp src/world/environment.cpp)
|
||||
add_library(evo_world STATIC ${evo_world_sources})
|
||||
add_library(evo::world ALIAS evo_world)
|
||||
target_include_directories(evo_world PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
@@ -72,6 +72,12 @@ evo_owned_target(evo-sim)
|
||||
|
||||
include(CTest)
|
||||
if(BUILD_TESTING)
|
||||
add_executable(evo-environment-views-tests tests/environment_views_tests.cpp)
|
||||
target_link_libraries(evo-environment-views-tests PRIVATE evo::world)
|
||||
evo_owned_target(evo-environment-views-tests)
|
||||
add_test(NAME environment-views-contracts COMMAND evo-environment-views-tests)
|
||||
set_tests_properties(environment-views-contracts PROPERTIES TIMEOUT 60)
|
||||
|
||||
add_executable(evo-world-fields-tests tests/world_fields_tests.cpp)
|
||||
target_link_libraries(evo-world-fields-tests PRIVATE evo::world)
|
||||
evo_owned_target(evo-world-fields-tests)
|
||||
|
||||
@@ -29,6 +29,7 @@ network service. Dev verification manifests are separate from the simulation.
|
||||
- [Energy/matter model and implemented ledger boundary](docs/biology/ENERGY_MODEL.md)
|
||||
- [Environmental units and habitat coupling](docs/world/ENVIRONMENTAL_UNITS.md)
|
||||
- [Optional finite environmental fields and snapshot format](docs/world/ENVIRONMENTAL_FIELDS.md)
|
||||
- [Read-only environment footprints and freshness](docs/world/ENVIRONMENT_VIEWS.md)
|
||||
- [Genome model and implemented v1 record](docs/biology/GENOME_MODEL.md)
|
||||
|
||||
Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are
|
||||
|
||||
@@ -315,6 +315,11 @@ material capacity defaults, bounded sparse pages, same-field local relocation an
|
||||
canonical field snapshot v1 under ADR-0051. Rate-driven sources and combined
|
||||
terrain/biology persistence are not provided by this independent codec. Next: M6.3.
|
||||
|
||||
M6.3 implements [read-only environment views](world/ENVIRONMENT_VIEWS.md) under
|
||||
ADR-0052: bounded canonical voxel footprints, exact typed derived values, explicit
|
||||
absence and tick/field/chunk freshness checks. No implicit terrain load or inventory
|
||||
authorization occurs. Next: M6.4 atomic coordinated transfers.
|
||||
|
||||
## M7 - Persistent region server
|
||||
|
||||
**Goal:** a disposable authoritative headless process can recover a bounded region
|
||||
|
||||
+13
-2
@@ -7,7 +7,7 @@ persistent simulation server. The founding vision remains unchanged.
|
||||
## Completed implementation
|
||||
|
||||
- Vision, architectural pillars, risks, open-question register, architecture
|
||||
diagrams, biological contracts, engineering constitution and 51 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 52 ADRs.
|
||||
Proposed/deferred choices remain distinct from accepted proof decisions.
|
||||
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
|
||||
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
|
||||
@@ -61,7 +61,7 @@ for the bounded proof; the general production ECS remains a later measured choic
|
||||
|
||||
| Priority | Work | Completion evidence |
|
||||
|---|---|---|
|
||||
| 1 | M6.3 read-only environment views | Footprint queries with explicit units, availability, tick and revision validity |
|
||||
| 1 | M6.4 coordinated environmental transfers | Atomic organism/environment debits and credits, fresh-view checks and retry identity |
|
||||
| Research | Improve aggregate fidelity and measure Linux/target-host costs | M4.6 found no qualifying width; see the aggregate budget report |
|
||||
| 2 | Revisit the ADR-0031/0032 reproduction cost model | Reproduction is affordable only at the genome schema's floor; decide whether that is intended before M4 builds cohorts on it |
|
||||
| Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes |
|
||||
@@ -630,3 +630,14 @@ restore does not regenerate supplies. [Contract and memory evidence](world/ENVIR
|
||||
and the byte schema document trust, budget and compatibility limits. M5 terrain
|
||||
formats remain unchanged; combined terrain/biology durability and rate sources are
|
||||
not implemented. Next: M6.3 read-only derived environment views.
|
||||
|
||||
## M6.3 read-only environment views (2026-09-27)
|
||||
|
||||
Added [bounded footprint queries](world/ENVIRONMENT_VIEWS.md) under ADR-0052.
|
||||
Views copy typed quantities, exact concentration/moisture and terrain samples with
|
||||
habitat resolution, logical tick, field watermark and sampled chunk revisions.
|
||||
Missing fields are distinct from zero; absent habitats/chunks fail without loading.
|
||||
Freshness validation rejects wrong stores, changed tick/field state and stale chunk
|
||||
tokens, including eviction/reload. No persistent format or simulation rule changed.
|
||||
Views grant no inventory reservation; coherent tick/store pairing remains a host
|
||||
responsibility. Next: M6.4 coordinated environmental transfers.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# ADR-0052: Read-only environment footprint views
|
||||
|
||||
## Status
|
||||
Accepted for M6.3 single-owner local queries. No transfer authorization or new format.
|
||||
|
||||
## Context
|
||||
Scalar field reads do not identify habitat volume, missing data, sampling tick or
|
||||
terrain freshness. M6.4 needs a bounded, immutable planning input without implicit
|
||||
loading or supply creation. Field and terrain stores are not yet a durable bundle.
|
||||
|
||||
## Decision
|
||||
Add `query_environment(fields, terrain, tick, footprint, mask)` in evo::world.
|
||||
The footprint contains 1..256 unique voxel addresses; order is canonicalized before
|
||||
querying. Each address selects its complete mapped habitat, not a geometric overlap
|
||||
integral. Unknown sites/chunks fail the entire query. Requested absent fields stay
|
||||
explicitly absent, distinct from present zero. No mutation or loading occurs.
|
||||
|
||||
Return an owned read-only EnvironmentView with world/frame from FieldStore, caller
|
||||
tick, requested mask, field command watermark, and samples ordered by voxel. Each
|
||||
sample contains mapping/volume, field substrate, copied terrain cell and its chunk
|
||||
revision, typed mass/energy values, exact bulk mass concentration and water saturation
|
||||
with explicit undefined/missing status. Resolution is the 1m terrain pitch plus the
|
||||
actual micrometre habitat box; no physical accuracy claim follows from exact ratios.
|
||||
|
||||
Views retain non-owning store identities and private ChunkView tokens. Both stores
|
||||
must outlive validation. `validate_environment` checks the same objects, same tick,
|
||||
unchanged global field watermark and all sampled chunk tokens. Unrelated field
|
||||
transfers conservatively invalidate the view; unrelated terrain chunks do not.
|
||||
Eviction/reload and restored clones cannot revive old views. Failed commands do not
|
||||
invalidate them. There is no serializable capability, network trust or permission
|
||||
to consume from a copied result. Validation and commit must eventually share the
|
||||
single-owner phase; a check followed by concurrent writes is invalid usage.
|
||||
|
||||
The host supplies a coherent tick/store pairing. ChunkStore has no bound WorldIdentity,
|
||||
so this gate cannot authenticate that terrain and fields belong to the same world.
|
||||
Substrate and terrain material are reported separately, never silently reconciled.
|
||||
M6.4/6.8 must define coupled ownership and persistence before biological commits.
|
||||
|
||||
## Alternatives Considered
|
||||
Returning zero for missing data manufactures environmental knowledge. Partial-volume
|
||||
interpolation needs explicit density/overlap rules and can imply false precision.
|
||||
Per-site field revisions reduce invalidation but require persisted state changes;
|
||||
the existing nonwrapping watermark safely supplies a conservative version now.
|
||||
Implicit chunk loads would turn reads into state/resource changes.
|
||||
|
||||
## Benefits
|
||||
Deterministic bounded queries, dimensional results and testable stale-data rejection.
|
||||
Existing field and terrain snapshots/goldens remain unchanged.
|
||||
|
||||
## Costs
|
||||
Each response copies up to 256 samples and tokens; buffers are outside store budgets.
|
||||
Global field invalidation may cause extra replanning. No concurrent readers/writers.
|
||||
|
||||
## Risks
|
||||
A dishonest host tick or mismatched stores cannot be detected fully here. A current
|
||||
view is not a reservation. Restored stores must reacquire views. Fine-grained geometry,
|
||||
cross-region queries and aggregation need later contracts.
|
||||
|
||||
## Consequences
|
||||
Test signed chunk seams, canonical order, absence versus zero, zero water capacity,
|
||||
invalid footprints, stale field/chunk/tick/owner, eviction/reload and unchanged
|
||||
snapshot bytes after reads. No deployment, scheduler or biological action added.
|
||||
@@ -58,3 +58,4 @@ design. No unadopted candidate is a link dependency of the proof.
|
||||
- [ADR-0049: Bounded world proof](0049-bounded-world-proof.md) - accepted for M5.8 restart regression and cost evidence.
|
||||
- [ADR-0050: Environmental units and coupling](0050-environmental-units-and-coupling.md) - accepted for M6's bounded habitat/accounting contract; no field storage or terrain conversion yet.
|
||||
- [ADR-0051: Optional environmental fields](0051-optional-environmental-fields.md) - accepted for M6.2 finite sparse pages, local transfers and field snapshot v1.
|
||||
- [ADR-0052: Environment views](0052-read-only-environment-views.md) - accepted for M6.3 bounded read-only footprint queries and freshness validation.
|
||||
|
||||
@@ -173,3 +173,13 @@ sparse scalar pages. Its versioned codec retains all field state and local trans
|
||||
watermark, without relying on procedural resource regeneration. M5 LocalWorldFiles
|
||||
still publishes only terrain state: integrated terrain/fields/biology recovery must
|
||||
use a later version bundle. No cross-store biological transfer is authorized here.
|
||||
|
||||
## M6.3 environment reads
|
||||
|
||||
[ADR-0052](../adr/0052-read-only-environment-views.md) adds
|
||||
[environment views](../world/ENVIRONMENT_VIEWS.md) across a bounded voxel footprint.
|
||||
Samples carry exact typed field quantities, habitat volume, terrain chunk revision
|
||||
and an explicit host tick. Queries never load chunks or mutate inventories. A
|
||||
separate validator rejects stale ticks, field watermarks, foreign store instances
|
||||
and stale sampled chunk tokens. Coherent store pairing and single-owner scheduling
|
||||
remain host obligations; M6.4 must validate and commit in one ownership phase.
|
||||
|
||||
@@ -1738,3 +1738,37 @@ or new sanitizer claims. Local Docker CLI exists, but docker version could not c
|
||||
because the dockerDesktopLinuxEngine named pipe is absent. Consequently the corrected
|
||||
Linux TSan container invocation requires confirmation in Gitea CI; it was not run
|
||||
locally. No application deployment or World0 changes.
|
||||
|
||||
## M6.3 read-only environment views - 2026-09-27
|
||||
|
||||
Added ADR-0052 and a bounded canonical footprint query with typed mass/energy,
|
||||
exact concentration/moisture, habitat resolution, explicit caller tick, field
|
||||
watermark and sampled chunk revisions. FieldStore gained read-only identity and
|
||||
capacity accessors. Views own copied samples and retain private non-owning store/
|
||||
chunk tokens for freshness checks. Existing formats, versions and goldens are unchanged.
|
||||
|
||||
Executed on Windows x64 / MSVC 19.44:
|
||||
|
||||
- `tools/windows-check.ps1 -Preset release -Action check`: 51/51 passed on final code.
|
||||
- `tools/windows-check.ps1 -Preset analysis -Action check`: clang-tidy 19 and
|
||||
51/51 passed. Removed an ineffective move of a trivially copyable sample after
|
||||
the initial analysis diagnostic.
|
||||
- `tools/windows-check.ps1 -Preset asan -Action check`: 51/51 passed on final code.
|
||||
- `tools/windows-check.ps1 -Preset release -Action format`: passed.
|
||||
- `git diff --check`: passed.
|
||||
|
||||
Tests cover negative/positive chunk seams, input permutation, missing site/chunk,
|
||||
absent versus zero/unrequested fields, all moisture statuses, invalid masks and
|
||||
footprints, exact quantities/ratios, maximum 256-site footprint with all ten fields,
|
||||
and unchanged terrain/field snapshots after queries. Freshness checks cover changed
|
||||
tick, restored foreign stores, successful versus rejected field transfers, global
|
||||
field invalidation, unrelated terrain activity, sampled dirty marking, excavation
|
||||
and eviction/reload. The query never loads missing chunks or authorizes consumption.
|
||||
|
||||
Linux/UBSan/TSan and cluster execution were not run locally; existing CI includes
|
||||
the new CTest without additional scratch mounts (this test writes no files).
|
||||
Host tick/store pairing and single-owner execution are explicit preconditions.
|
||||
ChunkStore does not yet bind a world identity, so coherent field/terrain pairing
|
||||
cannot be independently authenticated by this view. Combined ownership, reservation,
|
||||
atomic inventory transfer and retry outcomes remain M6.4. No deployment or World0
|
||||
operation occurred.
|
||||
|
||||
@@ -46,7 +46,9 @@ Restore additionally uses at most 327680 bytes of dense field staging, a second
|
||||
outside the resident budget. All counts are bounded before those allocations.
|
||||
|
||||
`read(site, channel)` returns the owned scalar in that channel's units; it grants
|
||||
no consumption permission. M6.3 will add derived footprint/tick/revision views.
|
||||
no consumption permission. M6.3 adds [derived footprint/tick/revision views](ENVIRONMENT_VIEWS.md).
|
||||
Read-only `identity()` and checked `water_capacity(site)` accessors support those
|
||||
queries without exposing writable metadata or changing field snapshot v1.
|
||||
`transfer(action, channel, from, to, amount)` moves a positive quantity between
|
||||
distinct sites within one present field. It checks source, overflow, water capacity,
|
||||
fresh nonzero command and replacement budget before publishing. Rejection preserves
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# M6.3 read-only environment views
|
||||
|
||||
[ADR-0052](../adr/0052-read-only-environment-views.md) defines the implemented local
|
||||
query in `include/evo/world/environment.hpp`. FieldStore gains read-only identity
|
||||
and per-site capacity accessors; neither changes field snapshot v1.
|
||||
|
||||
```cpp
|
||||
auto view = query_environment(fields, terrain, tick, voxel_footprint, requested_mask);
|
||||
// Plan from view->samples(), then under the same single-owner phase:
|
||||
auto current = validate_environment(*view, fields, terrain, tick);
|
||||
// A successful check is NOT an inventory reservation or transfer.
|
||||
```
|
||||
|
||||
## Selection and response
|
||||
|
||||
The footprint is 1..256 unique voxel addresses in the existing local coordinate
|
||||
contract. Input permutations produce the same sorted samples. Invalid/duplicate
|
||||
addresses, empty/oversized footprints and zero/unknown mask bits reject. Every voxel
|
||||
must have a FieldSite and an already loaded terrain chunk; otherwise the complete
|
||||
query fails with `missing_site` or `missing_chunk`. Reads never regenerate or load.
|
||||
The selected region is the site's full HabitatBox. There is no partial-box sampling,
|
||||
weighted overlap, smoothing or summing concentrations across different volumes.
|
||||
|
||||
Requested fields are bits 0..9 in Field enum order. Each sample has ten optional
|
||||
slots: unrequested slots are empty, requested missing slots are empty, present zero
|
||||
slots hold a typed zero. The view's mask distinguishes unrequested from missing.
|
||||
Mass channels return Femtograms and reduced fg/um^3 bulk concentration; energy
|
||||
channels return Picojoules. Ratios refer to the habitat's effective volume, not
|
||||
solvent volume. Moisture status is explicitly not_requested, missing_water,
|
||||
zero_capacity or available; only available carries WaterSaturation. No values are
|
||||
inferred from material IDs.
|
||||
|
||||
Each sample records voxel, chunk address/revision, FieldSite (including substrate),
|
||||
copied terrain CellSample, effective area/volume and water capacity. The view records
|
||||
world/frame from fields, logical tick, field watermark and request mask. Resolution
|
||||
is explicit: terrain pitch 1000mm, habitat coordinates/extents in um. Rational
|
||||
derivations have zero rounding error relative to stored integer inventories; physical
|
||||
resolution and unmodeled sub-habitat variation remain limitations, not zero error.
|
||||
Field substrate and terrain material can differ: both are reported without converting
|
||||
inventory or changing capacities. M6.4 must decide valid binding before consuming.
|
||||
|
||||
## Freshness, ownership and failure
|
||||
|
||||
Samples are privately owned and exposed as const spans. Copies are informational.
|
||||
Validation requires original stores alive at their original addresses, equal caller
|
||||
tick, the same field watermark and current tokens for every sampled terrain chunk.
|
||||
Any successful field transfer invalidates every prior view, even an unrelated one.
|
||||
Edits or first dirty marking in a sampled chunk invalidate; so does clean eviction
|
||||
and reload. Unrelated terrain activity does not invalidate the sampled chunks.
|
||||
Rejected commands leave views current. A restored identical store is a different
|
||||
owner; obtain a fresh view. Do not use a moved-from view except for reassignment
|
||||
or destruction; validators reject empty moved-from results defensively.
|
||||
|
||||
No library clock advances here. The host passes the committed logical tick and
|
||||
guarantees single-owner access with no mutation during query or between final
|
||||
validation and future commit. Views must not outlive either store when validated.
|
||||
The terrain API currently has no bound world/frame identity; pairing it correctly
|
||||
with fields is a trusted host responsibility, not something this query verifies.
|
||||
No pointer/token is persisted or sent as a client authority token.
|
||||
|
||||
Query failures return typed errors and publish no partial view. Allocation exceptions
|
||||
propagate to the host. A query owns at most 256 samples, tokens and sorted addresses;
|
||||
those buffers and allocator metadata are outside store resident budgets. Work is
|
||||
bounded by footprint size, field count and ChunkStore's bounded lookup. No new spatial
|
||||
index or concurrency is justified at this gate.
|
||||
|
||||
Existing geometry/field formats, versions and goldens are unchanged. Later combined
|
||||
snapshots must restore the stores first and reacquire views. Next: M6.4 coordinated
|
||||
environmental transfers, including inventory ownership and retry semantics.
|
||||
@@ -0,0 +1,101 @@
|
||||
#pragma once
|
||||
#include "evo/world/fields.hpp"
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace evo::world {
|
||||
inline constexpr std::size_t max_environment_footprint = 256;
|
||||
inline constexpr std::uint32_t all_environment_fields = (1U << field_count) - 1;
|
||||
struct EnvironmentMass {
|
||||
accounting::Femtograms amount;
|
||||
MassConcentration concentration;
|
||||
auto operator<=>(const EnvironmentMass&) const = default;
|
||||
};
|
||||
using EnvironmentQuantity = std::variant<EnvironmentMass, accounting::Picojoules>;
|
||||
enum class MoistureStatus : std::uint8_t { not_requested, missing_water, zero_capacity, available };
|
||||
struct EnvironmentSample {
|
||||
VoxelAddress voxel;
|
||||
ChunkAddress chunk;
|
||||
std::uint64_t chunk_revision;
|
||||
FieldSite habitat;
|
||||
CellSample terrain;
|
||||
HabitatMeasure measure;
|
||||
accounting::Femtograms water_capacity;
|
||||
std::array<std::optional<EnvironmentQuantity>, field_count> fields{};
|
||||
MoistureStatus moisture_status{MoistureStatus::not_requested};
|
||||
std::optional<WaterSaturation> moisture;
|
||||
};
|
||||
enum class EnvironmentError : std::uint8_t {
|
||||
invalid_request,
|
||||
invalid_voxel,
|
||||
missing_site,
|
||||
missing_chunk,
|
||||
source_error,
|
||||
wrong_owner,
|
||||
stale_tick,
|
||||
stale_fields,
|
||||
stale_terrain,
|
||||
invalid_view
|
||||
};
|
||||
class EnvironmentView;
|
||||
[[nodiscard]] std::expected<EnvironmentView, EnvironmentError>
|
||||
query_environment(const FieldStore& fields, const ChunkStore& terrain, std::uint64_t tick,
|
||||
std::span<const VoxelAddress> footprint, std::uint32_t requested_mask);
|
||||
[[nodiscard]] std::expected<void, EnvironmentError>
|
||||
validate_environment(const EnvironmentView& view, const FieldStore& fields,
|
||||
const ChunkStore& terrain, std::uint64_t current_tick) noexcept;
|
||||
|
||||
// Owned immutable samples, non-owning store identities. Stores must outlive validation.
|
||||
// Moved-from views may only be reassigned or destroyed. No concurrent store mutation.
|
||||
class EnvironmentView {
|
||||
public:
|
||||
EnvironmentView(const EnvironmentView&) = default;
|
||||
EnvironmentView& operator=(const EnvironmentView&) = default;
|
||||
EnvironmentView(EnvironmentView&&) noexcept = default;
|
||||
EnvironmentView& operator=(EnvironmentView&&) noexcept = default;
|
||||
[[nodiscard]] std::span<const EnvironmentSample> samples() const noexcept {
|
||||
return samples_;
|
||||
}
|
||||
[[nodiscard]] WorldIdentity identity() const noexcept {
|
||||
return identity_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t tick() const noexcept {
|
||||
return tick_;
|
||||
}
|
||||
[[nodiscard]] std::uint64_t field_revision() const noexcept {
|
||||
return field_revision_;
|
||||
}
|
||||
[[nodiscard]] std::uint32_t requested_mask() const noexcept {
|
||||
return mask_;
|
||||
}
|
||||
[[nodiscard]] SignedMillimetres terrain_pitch() const noexcept {
|
||||
return {cell_pitch_mm};
|
||||
}
|
||||
|
||||
private:
|
||||
friend std::expected<EnvironmentView, EnvironmentError>
|
||||
query_environment(const FieldStore&, const ChunkStore&, std::uint64_t,
|
||||
std::span<const VoxelAddress>, std::uint32_t);
|
||||
friend std::expected<void, EnvironmentError> validate_environment(const EnvironmentView&,
|
||||
const FieldStore&,
|
||||
const ChunkStore&,
|
||||
std::uint64_t) noexcept;
|
||||
EnvironmentView(const FieldStore& fields, const ChunkStore& terrain, std::uint64_t tick,
|
||||
std::uint32_t mask)
|
||||
: fields_{&fields}, terrain_{&terrain}, identity_{fields.identity()}, tick_{tick},
|
||||
field_revision_{fields.last_command()}, mask_{mask} {}
|
||||
const FieldStore* fields_;
|
||||
const ChunkStore* terrain_;
|
||||
WorldIdentity identity_;
|
||||
std::uint64_t tick_, field_revision_;
|
||||
std::uint32_t mask_;
|
||||
std::vector<EnvironmentSample> samples_;
|
||||
std::vector<ChunkView> terrain_tokens_;
|
||||
};
|
||||
} // namespace evo::world
|
||||
@@ -79,6 +79,15 @@ class FieldStore {
|
||||
[[nodiscard]] std::uint64_t last_command() const noexcept {
|
||||
return command_;
|
||||
}
|
||||
[[nodiscard]] WorldIdentity identity() const noexcept {
|
||||
return identity_;
|
||||
}
|
||||
[[nodiscard]] std::expected<accounting::Femtograms, FieldError>
|
||||
water_capacity(std::size_t site) const noexcept {
|
||||
if (site >= count_)
|
||||
return std::unexpected{FieldError::site};
|
||||
return defaults_.water_capacity[sites_[site].substrate.value];
|
||||
}
|
||||
[[nodiscard]] std::span<const FieldSite> sites() const noexcept {
|
||||
return {sites_.get(), count_};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
#include "evo/world/environment.hpp"
|
||||
#include <algorithm>
|
||||
|
||||
namespace evo::world {
|
||||
std::expected<EnvironmentView, EnvironmentError>
|
||||
query_environment(const FieldStore& fields, const ChunkStore& terrain, std::uint64_t tick,
|
||||
std::span<const VoxelAddress> footprint, std::uint32_t requested_mask) {
|
||||
if (footprint.empty() || footprint.size() > max_environment_footprint || requested_mask == 0 ||
|
||||
(requested_mask & ~all_environment_fields) != 0)
|
||||
return std::unexpected{EnvironmentError::invalid_request};
|
||||
for (const auto address : footprint)
|
||||
if (!split(address, base_chunk_edge))
|
||||
return std::unexpected{EnvironmentError::invalid_voxel};
|
||||
std::vector<VoxelAddress> ordered{footprint.begin(), footprint.end()};
|
||||
std::sort(ordered.begin(), ordered.end());
|
||||
if (std::adjacent_find(ordered.begin(), ordered.end()) != ordered.end())
|
||||
return std::unexpected{EnvironmentError::invalid_request};
|
||||
EnvironmentView result{fields, terrain, tick, requested_mask};
|
||||
result.samples_.reserve(ordered.size());
|
||||
result.terrain_tokens_.reserve(ordered.size());
|
||||
const auto sites = fields.sites();
|
||||
for (const auto voxel : ordered) {
|
||||
const auto site = std::lower_bound(
|
||||
sites.begin(), sites.end(), voxel,
|
||||
[](const FieldSite& s, VoxelAddress address) { return s.voxel < address; });
|
||||
if (site == sites.end() || site->voxel != voxel)
|
||||
return std::unexpected{EnvironmentError::missing_site};
|
||||
const auto location = split(voxel, base_chunk_edge);
|
||||
const auto token = terrain.view(location->chunk);
|
||||
if (!token)
|
||||
return std::unexpected{EnvironmentError::missing_chunk};
|
||||
const auto cell = terrain.read(*token, location->local);
|
||||
const auto size = measure_habitat(site->box);
|
||||
const auto site_index = static_cast<std::size_t>(site - sites.begin());
|
||||
const auto capacity = fields.water_capacity(site_index);
|
||||
if (!cell || !size || !capacity)
|
||||
return std::unexpected{EnvironmentError::source_error};
|
||||
EnvironmentSample sample{voxel,
|
||||
location->chunk,
|
||||
token->revision(),
|
||||
*site,
|
||||
*cell,
|
||||
*size,
|
||||
*capacity,
|
||||
{},
|
||||
MoistureStatus::not_requested,
|
||||
{}};
|
||||
for (std::size_t k = 0; k < field_count; ++k) {
|
||||
if ((requested_mask & (1U << k)) == 0)
|
||||
continue;
|
||||
const auto value = fields.read(site_index, static_cast<Field>(k));
|
||||
if (!value) {
|
||||
if (value.error() != FieldError::missing)
|
||||
return std::unexpected{EnvironmentError::source_error};
|
||||
if (k == 0)
|
||||
sample.moisture_status = MoistureStatus::missing_water;
|
||||
continue;
|
||||
}
|
||||
if (k >= static_cast<std::size_t>(Field::organic_energy)) {
|
||||
sample.fields[k] = accounting::Picojoules{*value};
|
||||
} else {
|
||||
const auto concentration = mass_concentration({*value}, size->volume);
|
||||
if (!concentration)
|
||||
return std::unexpected{EnvironmentError::source_error};
|
||||
sample.fields[k] = EnvironmentMass{{*value}, *concentration};
|
||||
}
|
||||
if (k == 0) {
|
||||
if (capacity->value == 0) {
|
||||
sample.moisture_status = MoistureStatus::zero_capacity;
|
||||
} else {
|
||||
const auto saturation = water_saturation({*value}, *capacity);
|
||||
if (!saturation)
|
||||
return std::unexpected{EnvironmentError::source_error};
|
||||
sample.moisture_status = MoistureStatus::available;
|
||||
sample.moisture = *saturation;
|
||||
}
|
||||
}
|
||||
}
|
||||
result.samples_.push_back(sample);
|
||||
result.terrain_tokens_.push_back(*token);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::expected<void, EnvironmentError> validate_environment(const EnvironmentView& view,
|
||||
const FieldStore& fields,
|
||||
const ChunkStore& terrain,
|
||||
std::uint64_t current_tick) noexcept {
|
||||
if (view.samples_.empty() || view.samples_.size() != view.terrain_tokens_.size())
|
||||
return std::unexpected{EnvironmentError::invalid_view};
|
||||
if (view.fields_ != &fields || view.terrain_ != &terrain)
|
||||
return std::unexpected{EnvironmentError::wrong_owner};
|
||||
if (view.tick_ != current_tick)
|
||||
return std::unexpected{EnvironmentError::stale_tick};
|
||||
if (view.field_revision_ != fields.last_command())
|
||||
return std::unexpected{EnvironmentError::stale_fields};
|
||||
for (const auto token : view.terrain_tokens_)
|
||||
if (!terrain.read(token, {}))
|
||||
return std::unexpected{EnvironmentError::stale_terrain};
|
||||
return {};
|
||||
}
|
||||
} // namespace evo::world
|
||||
@@ -0,0 +1,241 @@
|
||||
#include "evo/world/environment.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <limits>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace evo::world;
|
||||
constexpr WorldIdentity identity{7, 9};
|
||||
constexpr std::size_t budget = 2'000'000;
|
||||
constexpr std::uint32_t mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7);
|
||||
void check(bool ok, std::source_location at = std::source_location::current()) {
|
||||
if (!ok)
|
||||
throw std::runtime_error("environment view 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;
|
||||
}
|
||||
struct Fixture {
|
||||
std::unique_ptr<FieldStore> fields;
|
||||
std::unique_ptr<ChunkStore> terrain;
|
||||
std::vector<VoxelAddress> footprint;
|
||||
};
|
||||
Fixture fixture() {
|
||||
Fixture f;
|
||||
std::vector<FieldSite> sites;
|
||||
for (const auto x : {-17, -16, -1, 0, 15, 16}) {
|
||||
f.footprint.push_back({x, 0, -16000});
|
||||
sites.push_back({f.footprint.back(), {{0}, {0}, {0}, {10}, {20}, {3}}, {1}});
|
||||
}
|
||||
sites[1].substrate = {2};
|
||||
const std::array<std::uint64_t, 6> water{6, 0, 12, 18, 24, 30};
|
||||
const std::uint64_t zero = 0, energy = 72;
|
||||
const FieldOpening opening[]{{Field::water, water},
|
||||
{Field::phosphorus, {&zero, 1}},
|
||||
{Field::organic_energy, {&energy, 1}}};
|
||||
const FieldDefaults defaults{{evo::accounting::Femtograms{0}, evo::accounting::Femtograms{100},
|
||||
evo::accounting::Femtograms{0}}};
|
||||
auto fields = FieldStore::create(identity, 1, defaults, sites, opening, budget);
|
||||
CHECK(fields);
|
||||
f.fields = std::move(*fields);
|
||||
auto terrain = ChunkStore::create({}, 32, budget, {{VolumeUnits{100}, VolumeUnits{100}}});
|
||||
CHECK(terrain);
|
||||
f.terrain = std::move(*terrain);
|
||||
return f;
|
||||
}
|
||||
void load(Fixture& f) {
|
||||
for (auto address : f.footprint)
|
||||
CHECK(f.terrain->load(split(address, base_chunk_edge)->chunk));
|
||||
}
|
||||
void values_and_order() {
|
||||
auto f = fixture();
|
||||
const auto empty = f.terrain->snapshot(identity);
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 5, f.footprint, mask),
|
||||
EnvironmentError::missing_chunk));
|
||||
CHECK(f.terrain->snapshot(identity) == empty); // missing queries never load
|
||||
load(f);
|
||||
const auto terrain_before = f.terrain->snapshot(identity);
|
||||
const auto fields_before = f.fields->snapshot();
|
||||
auto q = query_environment(*f.fields, *f.terrain, 5, f.footprint, mask);
|
||||
CHECK(q && validate_environment(*q, *f.fields, *f.terrain, 5));
|
||||
CHECK(q->identity() == identity && q->tick() == 5 && q->field_revision() == 0);
|
||||
CHECK(q->requested_mask() == mask && q->terrain_pitch().value == 1000);
|
||||
CHECK(q->samples().size() == 6);
|
||||
const std::array<std::int64_t, 6> expected_chunks{-2, -1, -1, 0, 0, 1};
|
||||
for (std::size_t i = 0; i < 6; ++i) {
|
||||
const auto& s = q->samples()[i];
|
||||
CHECK(s.voxel == f.footprint[i] && s.chunk.x == expected_chunks[i]);
|
||||
CHECK(s.measure == HabitatMeasure{{200}, {600}});
|
||||
CHECK(s.terrain.material() == MaterialId{1} && s.terrain.fill() == fill_scale);
|
||||
CHECK(!s.fields[1] && !s.fields[3]); // missing requested N; unrequested organic C
|
||||
CHECK(std::get<EnvironmentMass>(*s.fields[2]) == EnvironmentMass{{0}, {0, 1}});
|
||||
CHECK(std::get<evo::accounting::Picojoules>(*s.fields[7]).value == 72);
|
||||
CHECK(s.chunk_revision == f.terrain->view(s.chunk)->revision());
|
||||
}
|
||||
CHECK(std::get<EnvironmentMass>(*q->samples()[0].fields[0]) == EnvironmentMass{{6}, {1, 100}});
|
||||
CHECK(q->samples()[0].moisture_status == MoistureStatus::available);
|
||||
CHECK(q->samples()[0].moisture == WaterSaturation{3, 50});
|
||||
CHECK(q->samples()[1].habitat.substrate == MaterialId{2}); // no silent substrate reconciliation
|
||||
CHECK(q->samples()[1].moisture_status == MoistureStatus::zero_capacity &&
|
||||
!q->samples()[1].moisture);
|
||||
auto reversed = f.footprint;
|
||||
std::reverse(reversed.begin(), reversed.end());
|
||||
auto reverse = query_environment(*f.fields, *f.terrain, 5, reversed, mask);
|
||||
CHECK(reverse);
|
||||
for (std::size_t i = 0; i < 6; ++i) {
|
||||
CHECK(reverse->samples()[i].voxel == q->samples()[i].voxel);
|
||||
CHECK(reverse->samples()[i].fields == q->samples()[i].fields);
|
||||
CHECK(reverse->samples()[i].moisture == q->samples()[i].moisture);
|
||||
}
|
||||
auto no_water = query_environment(*f.fields, *f.terrain, 5, f.footprint, 1U << 2);
|
||||
CHECK(no_water && no_water->samples()[0].moisture_status == MoistureStatus::not_requested);
|
||||
CHECK(f.terrain->snapshot(identity) == terrain_before && f.fields->snapshot() == fields_before);
|
||||
CHECK(refused(f.fields->water_capacity(6), FieldError::site));
|
||||
}
|
||||
void freshness() {
|
||||
auto f = fixture();
|
||||
load(f);
|
||||
auto q = query_environment(*f.fields, *f.terrain, 7, f.footprint, mask);
|
||||
CHECK(q);
|
||||
CHECK(
|
||||
refused(validate_environment(*q, *f.fields, *f.terrain, 8), EnvironmentError::stale_tick));
|
||||
auto clone = FieldStore::restore(f.fields->snapshot(), identity, budget);
|
||||
CHECK(clone);
|
||||
CHECK(refused(validate_environment(*q, **clone, *f.terrain, 7), EnvironmentError::wrong_owner));
|
||||
auto terrain_clone = ChunkStore::restore(*f.terrain->snapshot(identity), identity, budget);
|
||||
CHECK(terrain_clone);
|
||||
CHECK(refused(validate_environment(*q, *f.fields, **terrain_clone, 7),
|
||||
EnvironmentError::wrong_owner));
|
||||
CHECK(!f.fields->transfer(1, Field::water, 1, 2, 1));
|
||||
CHECK(validate_environment(*q, *f.fields, *f.terrain, 7));
|
||||
auto unrelated =
|
||||
query_environment(*f.fields, *f.terrain, 7, std::span{f.footprint}.last(1), mask);
|
||||
CHECK(unrelated);
|
||||
CHECK(f.fields->transfer(1, Field::water, 0, 2, 6));
|
||||
CHECK(refused(validate_environment(*q, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_fields));
|
||||
CHECK(refused(validate_environment(*unrelated, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_fields));
|
||||
q = query_environment(*f.fields, *f.terrain, 7, f.footprint, mask);
|
||||
CHECK(q);
|
||||
const auto other = f.terrain->load({10, 0, -1000});
|
||||
CHECK(other && f.terrain->mark_dirty(*other));
|
||||
CHECK(validate_environment(*q, *f.fields, *f.terrain, 7));
|
||||
const auto first = f.terrain->view({-2, 0, -1000});
|
||||
CHECK(first && f.terrain->mark_dirty(*first));
|
||||
CHECK(refused(validate_environment(*q, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_terrain));
|
||||
q = query_environment(*f.fields, *f.terrain, 7, f.footprint, mask);
|
||||
CHECK(q);
|
||||
const auto last = f.terrain->view({1, 0, -1000});
|
||||
CHECK(last && f.terrain->evict(*last));
|
||||
CHECK(refused(validate_environment(*q, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_terrain));
|
||||
CHECK(f.terrain->load({1, 0, -1000}));
|
||||
CHECK(refused(validate_environment(*q, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_terrain));
|
||||
q = query_environment(*f.fields, *f.terrain, 7, f.footprint, mask);
|
||||
CHECK(q);
|
||||
const auto revision = f.terrain->view({0, 0, -1000})->revision();
|
||||
const CellCut cut{{0, 0, -1000}, {0, 0, 0}, revision, 1};
|
||||
ExcavationRequest edit{1, 1, {&cut, 1}, 0};
|
||||
edit.digest = *excavation_digest(edit);
|
||||
CHECK(f.terrain->excavate(edit));
|
||||
CHECK(refused(validate_environment(*q, *f.fields, *f.terrain, 7),
|
||||
EnvironmentError::stale_terrain));
|
||||
auto updated = query_environment(*f.fields, *f.terrain, 7, f.footprint, mask);
|
||||
CHECK(updated);
|
||||
CHECK(updated->samples()[3].terrain.fill() == fill_scale - 1);
|
||||
CHECK(updated->samples()[3].fields == q->samples()[3].fields);
|
||||
}
|
||||
void invalid_and_absent() {
|
||||
auto f = fixture();
|
||||
load(f);
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, {}, mask),
|
||||
EnvironmentError::invalid_request));
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, f.footprint, 0),
|
||||
EnvironmentError::invalid_request));
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, f.footprint, 1U << 10),
|
||||
EnvironmentError::invalid_request));
|
||||
const VoxelAddress missing{1, 0, -16000},
|
||||
invalid{std::numeric_limits<std::int64_t>::min(), 0, 0};
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, {&missing, 1}, mask),
|
||||
EnvironmentError::missing_site));
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, {&invalid, 1}, mask),
|
||||
EnvironmentError::invalid_voxel));
|
||||
auto duplicate = f.footprint;
|
||||
duplicate.push_back(duplicate[0]);
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, duplicate, mask),
|
||||
EnvironmentError::invalid_request));
|
||||
std::vector<VoxelAddress> excess(max_environment_footprint + 1);
|
||||
CHECK(refused(query_environment(*f.fields, *f.terrain, 0, excess, mask),
|
||||
EnvironmentError::invalid_request));
|
||||
auto no_fields = FieldStore::create(identity, 2, {}, f.fields->sites(), {}, budget);
|
||||
CHECK(no_fields);
|
||||
auto absent =
|
||||
query_environment(**no_fields, *f.terrain, 0, f.footprint, all_environment_fields);
|
||||
CHECK(absent);
|
||||
for (const auto& s : absent->samples()) {
|
||||
CHECK(s.moisture_status == MoistureStatus::missing_water && !s.moisture);
|
||||
for (const auto& value : s.fields)
|
||||
CHECK(!value);
|
||||
}
|
||||
}
|
||||
void maximum_footprint() {
|
||||
std::vector<FieldSite> sites;
|
||||
std::vector<VoxelAddress> footprint;
|
||||
for (std::int64_t x = -128; x < 128; ++x) {
|
||||
footprint.push_back({x, 0, -16000});
|
||||
sites.push_back({footprint.back(), {{0}, {0}, {0}, {1}, {1}, {1}}, {1}});
|
||||
}
|
||||
const std::uint64_t amount = 4;
|
||||
std::array<FieldOpening, field_count> openings;
|
||||
for (std::size_t k = 0; k < field_count; ++k)
|
||||
openings[k] = {static_cast<Field>(k), {&amount, 1}};
|
||||
const FieldDefaults defaults{{evo::accounting::Femtograms{0}, evo::accounting::Femtograms{100},
|
||||
evo::accounting::Femtograms{0}}};
|
||||
auto fields = FieldStore::create(identity, 3, defaults, sites, openings, budget);
|
||||
auto terrain = ChunkStore::create({}, 32, budget);
|
||||
CHECK(fields && terrain);
|
||||
for (auto voxel : footprint)
|
||||
CHECK((*terrain)->load(split(voxel, base_chunk_edge)->chunk));
|
||||
std::reverse(footprint.begin(), footprint.end());
|
||||
const auto fields_before = (*fields)->snapshot();
|
||||
const auto terrain_before = (*terrain)->snapshot(identity);
|
||||
auto result = query_environment(**fields, **terrain, 0, footprint, all_environment_fields);
|
||||
CHECK(result && result->samples().size() == max_environment_footprint);
|
||||
CHECK(validate_environment(*result, **fields, **terrain, 0));
|
||||
for (std::size_t i = 0; i < sites.size(); ++i) {
|
||||
const auto& s = result->samples()[i];
|
||||
CHECK(s.voxel == sites[i].voxel);
|
||||
for (std::size_t k = 0; k < field_count; ++k) {
|
||||
CHECK(s.fields[k]);
|
||||
if (k < 7)
|
||||
CHECK(std::get<EnvironmentMass>(*s.fields[k]) == EnvironmentMass{{4}, {4, 1}});
|
||||
else
|
||||
CHECK(std::get<evo::accounting::Picojoules>(*s.fields[k]).value == 4);
|
||||
}
|
||||
CHECK(s.moisture == WaterSaturation{1, 25});
|
||||
}
|
||||
CHECK((*fields)->snapshot() == fields_before &&
|
||||
(*terrain)->snapshot(identity) == terrain_before);
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
values_and_order();
|
||||
freshness();
|
||||
invalid_and_absent();
|
||||
maximum_footprint();
|
||||
return 0;
|
||||
} catch (const std::exception& e) {
|
||||
std::fprintf(stderr, "%s\n", e.what());
|
||||
return 1;
|
||||
} catch (...) {
|
||||
return 1;
|
||||
}
|
||||
Reference in New Issue
Block a user