Complete M6.1 environmental units and coupling contract
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)
|
||||
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)
|
||||
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-units-tests tests/environment_units_tests.cpp)
|
||||
target_link_libraries(evo-environment-units-tests PRIVATE evo::world evo::accounting)
|
||||
evo_owned_target(evo-environment-units-tests)
|
||||
add_test(NAME environment-units-contracts COMMAND evo-environment-units-tests)
|
||||
set_tests_properties(environment-units-contracts PROPERTIES TIMEOUT 60)
|
||||
|
||||
add_executable(evo-world-codec-fuzz-smoke tests/fuzz/world_codec_fuzz.cpp tests/fuzz/world_codec_smoke.cpp)
|
||||
target_link_libraries(evo-world-codec-fuzz-smoke PRIVATE evo::world)
|
||||
evo_owned_target(evo-world-codec-fuzz-smoke)
|
||||
|
||||
@@ -27,6 +27,7 @@ network service. Dev verification manifests are separate from the simulation.
|
||||
- [Sequential command scheduling and recovery](docs/architecture/SCHEDULER_CONTRACT.md)
|
||||
- [Local periodic spatial queries](docs/architecture/SPATIAL_CONTRACT.md)
|
||||
- [Energy/matter model and implemented ledger boundary](docs/biology/ENERGY_MODEL.md)
|
||||
- [Environmental units and habitat coupling](docs/world/ENVIRONMENTAL_UNITS.md)
|
||||
- [Genome model and implemented v1 record](docs/biology/GENOME_MODEL.md)
|
||||
|
||||
Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are
|
||||
|
||||
@@ -305,6 +305,11 @@ later client, but no rendering is required. Ecological results and failure regim
|
||||
are reported separately from arithmetic. Unsupported distributed transfers remain
|
||||
rejected rather than simulated with untracked remote credits.
|
||||
|
||||
M6.1 ratifies [environmental units and coupling](world/ENVIRONMENTAL_UNITS.md)
|
||||
under ADR-0050. Pure checked habitat/ratio/energy-integration helpers and dimensional
|
||||
tests are implemented. No environmental stock, field codec, source scheduler or
|
||||
terrain-to-biological-mass converter is implemented by this gate. Next: M6.2.
|
||||
|
||||
## M7 - Persistent region server
|
||||
|
||||
**Goal:** a disposable authoritative headless process can recover a bounded region
|
||||
|
||||
+15
-3
@@ -1,13 +1,13 @@
|
||||
# Project status and next steps
|
||||
|
||||
Updated 2026-09-26. The repository contains an engineering foundation and a
|
||||
Updated 2026-09-27. The repository contains an engineering foundation and a
|
||||
deterministic headless proof. It does not yet contain cellular gameplay or a
|
||||
persistent simulation server. The founding vision remains unchanged.
|
||||
|
||||
## Completed implementation
|
||||
|
||||
- Vision, architectural pillars, risks, open-question register, architecture
|
||||
diagrams, biological contracts, engineering constitution and 49 ADRs.
|
||||
diagrams, biological contracts, engineering constitution and 50 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.1 environmental units and coupling contract | Define habitat mapping, resource units and volume-to-matter accounting before biological coupling |
|
||||
| 1 | M6.2 optional environmental fields | Finite versioned inventories, sparse field pages and round-trip persistence without regenerated supply |
|
||||
| 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 |
|
||||
@@ -606,3 +606,15 @@ clean regeneration checks pass. [Measured costs and reproduction](engineering/WO
|
||||
record five Windows Release runs and explicit accounting/durability limits.
|
||||
No world format or simulation version changed. Next: M6.1 environmental units and
|
||||
coupling contract; Linux golden execution remains a CI confirmation.
|
||||
|
||||
## M6.1 environmental units and habitat coupling (2026-09-27)
|
||||
|
||||
ADR-0050 and [the units contract](world/ENVIRONMENTAL_UNITS.md) define bounded
|
||||
inventories, compartment identity, derived concentration/moisture, explicit habitat
|
||||
depth and residual ownership. Pure checked helpers measure one-voxel habitat boxes,
|
||||
form rational views and integrate energy-rate proposals without creating supply.
|
||||
Dimensional examples, invalid conversions, overflow, split intervals, closed/open
|
||||
accounting and refusal rollback are tested. Windows Release, clang-tidy and ASan
|
||||
suites pass; see VALIDATION.md for exact checks. Existing formats/goldens are unchanged.
|
||||
No fields or biological coupling are implemented yet. Next: M6.2 optional finite
|
||||
environmental fields with versioned persistence and explicit opening inventories.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# ADR-0050: Bounded environmental units and ecological coupling
|
||||
|
||||
## Status
|
||||
Accepted for M6's local experiment. Habitat size, depth, material coefficients and
|
||||
source strengths are fixture inputs, not locked biological or planetary rules.
|
||||
|
||||
## Context
|
||||
M5 conserves terrain volume. M2 accounts in picojoules and femtograms of C/N/P/other.
|
||||
Neither concentration nor a material identifier is an owned supply. A 2D habitat
|
||||
needs explicit depth before it can exchange quantities with 3D environmental stores.
|
||||
The ledger's roughly 18.45 kg per-channel bound cannot cover planetary rock masses.
|
||||
|
||||
## Decision
|
||||
Adopt [ENVIRONMENTAL_UNITS.md](../world/ENVIRONMENTAL_UNITS.md). Retain M2 quanta for
|
||||
the bounded environmental experiment, with disjoint water, dissolved N/P, organic
|
||||
and mineral compartments. Tags partition inventories; they never add a second mass.
|
||||
Water belongs to `other` in this simplified basis and cannot be relabeled as edible
|
||||
other matter. No water chemistry or automatic extraction from rock is authorized.
|
||||
|
||||
Use integer micrometre extents and explicit effective depth, giving cubic-micrometre
|
||||
habitat volume. Initial mapping is one axis-aligned box inside one local 1m voxel;
|
||||
larger/cross-cell mappings require a later extension with explicit disjoint shares.
|
||||
Read concentration and saturation as exact rational views, never spendable balances.
|
||||
Carry fractional source-rate residuals under the source/interval owner; integrated
|
||||
energy is a requested transfer from a finite source, never permission to mint energy.
|
||||
|
||||
Implement only pure checked geometry/ratio/energy-integration helpers in evo::world
|
||||
and dimensional tests now. No field pages, organism adapter, rate scheduler, density
|
||||
conversion or new snapshot format. M6.2 owns field persistence; M6.4 owns atomic
|
||||
transfers. M5 geometry/debris remain separate until an explicit versioned density,
|
||||
composition and conversion transaction can debit one representation and credit the
|
||||
other together. Reject unsupported conversions rather than invent coefficients.
|
||||
|
||||
## Alternatives Considered
|
||||
Area-only coupling manufactures volume; arbitrary density-to-balance writes duplicate
|
||||
supply. Floating balances need tolerance/error accounting. A general units library
|
||||
remains an evaluation under ADR-0009; a few opaque quantities with explicit functions
|
||||
need no new dependency. Kilogram-scale coarse ledgers are appropriate later, but
|
||||
silently changing M2 units would invalidate existing biology and snapshots.
|
||||
|
||||
## Benefits
|
||||
Explicit dimensions, exact conservation, bounded arithmetic and no implicit resource
|
||||
creation. The small API can be tested independently of field storage and biology.
|
||||
|
||||
## Costs
|
||||
The proof cannot model a full voxel of dense rock in one ledger. Sub-micrometre
|
||||
geometry, arbitrary rotations, cross-cell habitats and reactions remain unsupported.
|
||||
Source integration conservatively rejects overflowing numerator intermediates even
|
||||
when division could have reduced the result; callers must use bounded intervals.
|
||||
|
||||
## Risks
|
||||
Conserved C/N/P/other does not establish chemical feasibility. Reusing `other` without
|
||||
compartment validation could make water edible. Overlapping habitat reservations or
|
||||
discarding fractional state could create supply despite dimensionally correct code.
|
||||
|
||||
## Consequences
|
||||
Public contracts distinguish computations from authorization. M6.2-6.4 must persist
|
||||
units/version, mapping, compartments, source residuals and ownership atomically, and
|
||||
reject mismatched versions or incomplete fields. No existing golden, generator,
|
||||
simulation law or world format changes in M6.1.
|
||||
@@ -56,3 +56,4 @@ design. No unadopted candidate is a link dependency of the proof.
|
||||
|
||||
- [ADR-0048: Local publication](0048-local-publication.md) - accepted for M5.7 single-writer snapshot/journal publication and recovery.
|
||||
- [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.
|
||||
|
||||
@@ -153,3 +153,13 @@ file publication and compaction; no production persistence dependency was added.
|
||||
M5.8 validates the local stack through separate prepare/compact/verify processes; see
|
||||
[bounded world proof and measurements](../engineering/WORLD_PROOF.md). This adds no
|
||||
production ownership or biological resource conversion contract.
|
||||
|
||||
## M6.1 environmental coupling boundary
|
||||
|
||||
[ADR-0050](../adr/0050-environmental-units-and-coupling.md) scopes a one-voxel,
|
||||
axis-aligned habitat with explicit micrometre depth. The
|
||||
[units contract](../world/ENVIRONMENTAL_UNITS.md) defines finite extensive stocks,
|
||||
derived concentrations/moisture, dimensional examples, closed/open accounting,
|
||||
rate residual ownership and rejection of unsupported terrain mass conversions.
|
||||
The implemented helpers are pure computations. Inventory pages, reservations,
|
||||
ownership enforcement, transfer commits and persistence follow in M6.2-6.4.
|
||||
|
||||
@@ -284,3 +284,16 @@ material between terrain fill and a finite debris inventory. VolumeUnits uses
|
||||
1/65535 m^3 at the experimental 1m pitch, not femtograms. No conversion into the
|
||||
biological ledger is allowed until M6 specifies density/composition and reconciles
|
||||
both representations. Debris is the destination of removed terrain, not new matter.
|
||||
|
||||
## M6.1 environmental units contract
|
||||
|
||||
[ADR-0050](../adr/0050-environmental-units-and-coupling.md) and
|
||||
[ENVIRONMENTAL_UNITS.md](../world/ENVIRONMENTAL_UNITS.md) ratify the bounded M6 basis:
|
||||
pJ, fg of disjoint C/N/P/other, explicit water/organic/mineral compartments, exact
|
||||
derived concentrations/moisture, and a 2D habitat's explicit effective depth.
|
||||
Checked geometry and energy integration helpers own no stock. Finite source
|
||||
budgets, residual ownership, interval identity and atomic debit/credit remain
|
||||
obligations of M6.2-6.7. Water is conserved `other` in a distinct compartment;
|
||||
this does not authorize converting it into edible material or modeling reactions.
|
||||
Bulk terrain-to-mass conversion remains unsupported pending density/composition
|
||||
and an atomic representation transfer. No existing ledger or biological rules change.
|
||||
|
||||
@@ -1649,3 +1649,37 @@ turn did not execute Linux, UBSan, physical power-cut, target-server or cluster
|
||||
checks. ASan is not UBSan. Process restarts are graceful; M5.7 fault injection
|
||||
remains separate coverage. No production durability or planet capacity claim.
|
||||
No Argo or World0 operation occurred. Next: M6.1 units and environmental coupling.
|
||||
|
||||
## M6.1 environmental units and coupling - 2026-09-27
|
||||
|
||||
Added ADR-0050, ENVIRONMENTAL_UNITS.md, checked local habitat geometry, exact mass
|
||||
concentration/water saturation and rational pJ/tick integration helpers. No field
|
||||
storage, density converter, source scheduler, gameplay or snapshot format changed.
|
||||
Terrain volume still cannot be credited as biological mass.
|
||||
|
||||
Executed on Windows x64 / MSVC 19.44:
|
||||
|
||||
- `tools/windows-check.ps1 -Preset release -Action check`: 49/49 passed.
|
||||
- `tools/windows-check.ps1 -Preset analysis -Action check`: clang-tidy 19 and
|
||||
49/49 passed.
|
||||
- `tools/windows-check.ps1 -Preset asan -Action check`: 49/49 passed.
|
||||
- After strengthening independent balance sums, open-boundary and rollback tests,
|
||||
reconfigured each preset, rebuilt `evo-environment-units-tests`, and ran
|
||||
`ctest --test-dir build/<preset> -R '^environment-units-contracts$' --output-on-failure`:
|
||||
passed in Release, analysis and ASan. Final code-only adjustment was an explicit
|
||||
cstddef include; CTest registration was grouped with other world tests.
|
||||
- `tools/windows-check.ps1 -Preset release -Action format`: passed.
|
||||
- `git diff --check`: passed.
|
||||
|
||||
Coverage includes each invalid box axis, zero/maximum inputs, exact dimensional
|
||||
examples, concentration/type separation, dry/saturated/excess water, multiplication
|
||||
and addition overflow, invalid denominators/residuals, and 78,660 repeated-addition
|
||||
oracle comparisons of split versus combined intervals. The closed/open accounting
|
||||
example uses a finite boundary reservoir, independently sums balances and verifies
|
||||
rejected overdraft leaves all balances unchanged. Documentation's large terrain
|
||||
mass example was checked using exact BigInteger division (1e21 / 65535).
|
||||
|
||||
Linux/UBSan and target-cluster checks were not executed locally; existing CI includes
|
||||
the new CTest. There is no new concurrency requiring TSan work. Helpers do not enforce
|
||||
owner identity, interval deduplication or residual persistence; those remain explicit
|
||||
M6.2-6.7 obligations. No deployment or World0 operation occurred. Next: M6.2.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# M6.1 environmental units and coupling contract
|
||||
|
||||
Authority: [ADR-0050](../adr/0050-environmental-units-and-coupling.md),
|
||||
[energy model](../biology/ENERGY_MODEL.md), ADR-0024 and ADR-0046. This is a bounded
|
||||
local experiment. Physical coefficients require separately versioned fixtures.
|
||||
|
||||
## Inventory basis and ranges
|
||||
|
||||
| Quantity | Representation / range | Ownership and meaning |
|
||||
|---|---|---|
|
||||
| Energy | u64 picojoules, 1 pJ = 1e-12 J | Finite incident source, usable reserve, chemical potential, heat, export compartments; each joule counted once |
|
||||
| Matter | u64 femtograms, 1 fg = 1e-18 kg | Disjoint C, N, P, other; total mass is their sum, not another account |
|
||||
| Water | fg of water in a dedicated compartment | Entire simplified water mass is `other`; not a fifth additive element |
|
||||
| Dissolved nutrients | fg of elemental N and P in named compartments | Not kilograms of unspecified salts; counterions, when introduced, require explicit other mass |
|
||||
| Organic matter | C/N/P/other bundle plus separately owned chemical energy | Biomass is a derived sum; no second spendable biomass field |
|
||||
| Mineral matter | C/N/P/other bundle only after explicit conversion | Rock/regolith ID is not nutrient availability or mass |
|
||||
| Habitat geometry | integer micrometres, extents 1..1,000,000 each | Effective volume = width * height * depth, 1..1e18 um^3 (1e-18..1 m^3) |
|
||||
| Concentration | exact fg / um^3 rational | Read-only derived value; zero mass valid, zero volume invalid |
|
||||
| Moisture | exact water mass / water capacity rational, 0..1 | Capacity is a fixture property, not supply; excess needs another compartment, not clamping |
|
||||
| Temperature | kelvin, future validated field | Intensive; does not mint energy; thermal capacity/heat model deferred |
|
||||
|
||||
The u64 ceiling is 18,446,744,073,709,551,615. ADR-0024 requires the global sum of
|
||||
each channel in a ledger to fit, including finite sources, sinks, organisms, corpses
|
||||
and escrow. This is about 18.45 MJ and 18.45 kg per mass channel, not a whole-world
|
||||
range. Computing a total across channels also requires checked sums. No saturation
|
||||
or silent wrap is permitted. Unavailable fields are errors/absence, never zero or
|
||||
infinite supply. Public aggregate wrappers do not validate construction; helpers do.
|
||||
|
||||
Water/organic/mineral tags partition existing elemental balances. A transfer must
|
||||
validate both the elemental bundle and compartment identity. Water cannot be spent
|
||||
as organic `other`, nor can dissolved N be obtained merely by retagging rock. M6
|
||||
does not model splitting water or chemical reactions. Water uptake/return is an
|
||||
explicit transfer of the same water; it stays in conservation totals while inside
|
||||
an organism. Destruction, conversion and phase change require their own contracts.
|
||||
|
||||
## Mapping 2D habitat to 3D ownership
|
||||
|
||||
For M6, a habitat descriptor identifies world/frame, voxel, local origin in integer
|
||||
micrometres, width/height/effective depth, mapping version and owner. Axes align with
|
||||
local X/Y/Z, +Z up. Every origin is in [0,1,000,000); every half-open box must fit in
|
||||
its 1m voxel. `measure_habitat` validates the local box; voxel/world identity and
|
||||
reservation overlap belong to the future field owner. The returned area is width *
|
||||
height; volume is area * effective depth. No camera size or organism count changes
|
||||
that volume. This is ecological sampling geometry, not shared collision physics.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
V[Finite environment owner] -->|reserve disjoint inventory share| H[2D habitat with explicit depth]
|
||||
H -->|balanced transfer| O[Organism inventories]
|
||||
O -->|death and bounded decay| V
|
||||
V -. concentration and moisture views .-> H
|
||||
```
|
||||
|
||||
Multiple habitats may read the same environment, but must either contend for the
|
||||
same owner or own nonoverlapping reserved inventory shares. A copied view cannot
|
||||
authorize a debit. Refinement partitions existing inventory; coarsening sums it.
|
||||
Changing depth or area is a mapping transaction, not `concentration * new volume`
|
||||
credited as new supply. Reject cross-voxel mappings in this version. M6.4 must commit
|
||||
source debit, destination credit, mapping/revisions and retry outcome together.
|
||||
|
||||
Example: width=1000 um, height=2000 um, depth=10 um gives area=2,000,000 um^2 and
|
||||
volume=20,000,000 um^3 = 2e-11 m^3. A fixture density of 1000 kg/m^3 would give
|
||||
20,000,000 fg of water. This is an illustrative density, not an adopted universal
|
||||
coefficient or opening-balance factory. 200 fg N in that volume is 1/100000 fg/um^3
|
||||
= 0.01 kg/m^3. A water mass of 5,000,000 fg against capacity 20,000,000 fg yields
|
||||
moisture 1/4. Dry with positive capacity is zero; zero capacity is undefined and
|
||||
rejected even when dry. Supersaturation must use explicit free water, not clipping.
|
||||
This concentration uses the full effective habitat volume (a bulk concentration),
|
||||
not solvent volume or molarity. A future dissolved-phase query must name its own
|
||||
positive solvent volume explicitly; drying cannot silently switch denominators.
|
||||
|
||||
## Energy, intervals and residuals
|
||||
|
||||
Incident power has dimensions J/(m^2 s). Integrate over explicit projected capture
|
||||
area and the world's fixed interval; shadow/efficiency cannot increase the input.
|
||||
Overlapping surfaces cannot each claim the same photons. M6.5 must derive an
|
||||
area-budgeted rational pJ/tick rate; it is not a second independent energy source.
|
||||
For example 1 W/m^2 * 2e-6 m^2 * 0.05 s = 100000 pJ per interval.
|
||||
|
||||
`integrate_energy(rate, ticks, residual)` computes `(rate.numerator * ticks + r) / d`
|
||||
and its remainder, where rate is rational pJ/tick and `0 <= r < d`, `d > 0`.
|
||||
Inputs and numerator intermediate must fit u64. Zero rate/ticks is valid. Reject
|
||||
overflow before multiplication/addition, including cases whose final quotient could
|
||||
fit. Output is a proposal, not credited energy. A changed denominator invalidates
|
||||
the old residual unless explicitly converted with exact accounting. The future
|
||||
source owner persists denominator, numerator, residual, last integrated tick and
|
||||
version; a caller cannot reset residual on restart, duplicate an interval or reuse
|
||||
it under another source. If the transfer cannot be funded, commit neither the
|
||||
proposed new residual nor the interval watermark; no repeated retries accrue supply.
|
||||
|
||||
At 5/3 pJ/tick, six ticks yield 10 pJ exactly; six single ticks yield the same result
|
||||
with carried remainders. Fractional remainder r/d is sub-quantum unissued entitlement
|
||||
against the same finite source, not extra energy added to source+destination totals.
|
||||
Splitting/refining a source must partition that entitlement exactly. M6.1's helper
|
||||
does not own or persist it; M6.2/6.7 must not omit it from their state contracts.
|
||||
|
||||
For a closed system, sum E and each element over all owners at end equals start.
|
||||
With boundaries: `E_end = E_start + imports - exports`; similarly for each element.
|
||||
Heat is an owned sink or an explicit export, never both. Capture transfers finite
|
||||
incident energy to usable energy + heat/unabsorbed outputs. Chemosynthesis consumes
|
||||
owned chemical potential, never free energy inferred from material presence.
|
||||
Example: source=100 pJ, reserve=0, heat=0; capture transfers 30 to reserve and 20 to
|
||||
heat, leaving source=50. All three sum to 100. An imported 7 raises the open-system
|
||||
total to 107 only with a recorded boundary import (not exposed by the current ledger).
|
||||
|
||||
## Terrain conversion boundary
|
||||
|
||||
M5 volume unit = 1/65535 m^3. With an explicitly supplied density rho kg/m^3,
|
||||
mass in fg is `volume_units * rho * 1e18 / 65535`. Density and elemental composition
|
||||
must be versioned rational values with exact carried residuals per material owner.
|
||||
Converting each cut independently and discarding its remainder is forbidden.
|
||||
For rho=1000, one volume unit corresponds to 15259021896696421 fg plus 49765/65535 fg;
|
||||
65535 units together give 1e21 fg, beyond a single M2 channel. This overflow is a
|
||||
scope boundary, not permission to clamp or change units. M6 has no converter yet.
|
||||
|
||||
Terrain/debris volume and converted mass are alternate representations of the same
|
||||
matter: an eventual conversion must remove/escrow the converted volume and atomically
|
||||
credit its mass/composition, including residuals. It cannot leave the debris spendable.
|
||||
Initial environmental field inventories are explicit, finite, separately attributed
|
||||
openings (e.g. pore water); they cannot also be counted in a converted solid density.
|
||||
Generator material IDs alone provide neither opening supply nor regeneration rights.
|
||||
|
||||
## Implemented versus deferred
|
||||
|
||||
`include/evo/world/environment_units.hpp` exposes pure local box measurement, exact
|
||||
concentration/moisture views and checked energy-rate integration. Tests check units,
|
||||
limits, split intervals and independently balanced examples under NDEBUG. These
|
||||
functions grant no access to stocks, create no field pages and change no snapshots.
|
||||
|
||||
M6.2 introduces optional fields, explicit initial inventories and versioned persistence;
|
||||
M6.3 read views; M6.4 coordinated ownership/transfer validation; M6.5-6.8 integrated
|
||||
processes, source budgets and replay. Density/composition conversion, chemical
|
||||
reactions, global atmosphere/hydrology and cross-region transfer remain unsupported.
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/accounting/ledger.hpp"
|
||||
|
||||
#include <compare>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
|
||||
namespace evo::world {
|
||||
inline constexpr std::uint32_t environmental_units_version = 1;
|
||||
inline constexpr std::uint64_t habitat_axis_limit_um = 1'000'000;
|
||||
inline constexpr std::uint64_t habitat_volume_limit_um3 = 1'000'000'000'000'000'000;
|
||||
|
||||
struct Micrometres {
|
||||
std::uint64_t value{};
|
||||
auto operator<=>(const Micrometres&) const = default;
|
||||
};
|
||||
struct SquareMicrometres {
|
||||
std::uint64_t value{};
|
||||
auto operator<=>(const SquareMicrometres&) const = default;
|
||||
};
|
||||
struct CubicMicrometres {
|
||||
std::uint64_t value{};
|
||||
auto operator<=>(const CubicMicrometres&) const = default;
|
||||
};
|
||||
// Half-open, axis-aligned box inside one 1m voxel. No world identity or reservation.
|
||||
struct HabitatBox {
|
||||
Micrometres x, y, z;
|
||||
Micrometres width, height, depth;
|
||||
};
|
||||
struct HabitatMeasure {
|
||||
SquareMicrometres area;
|
||||
CubicMicrometres volume;
|
||||
auto operator<=>(const HabitatMeasure&) const = default;
|
||||
};
|
||||
// Read-only ratios, not inventories. Helpers return reduced forms (zero is 0/1).
|
||||
struct MassConcentration {
|
||||
std::uint64_t femtograms{}, cubic_micrometres{1};
|
||||
auto operator<=>(const MassConcentration&) const = default;
|
||||
};
|
||||
struct WaterSaturation {
|
||||
std::uint64_t numerator{}, denominator{1};
|
||||
auto operator<=>(const WaterSaturation&) const = default;
|
||||
};
|
||||
struct EnergyRate {
|
||||
std::uint64_t picojoules_numerator{}, ticks_denominator{1};
|
||||
};
|
||||
struct EnergyIntegral {
|
||||
accounting::Picojoules amount;
|
||||
// Numerator of a fractional pJ, with the input rate's unchanged denominator.
|
||||
std::uint64_t remainder{};
|
||||
auto operator<=>(const EnergyIntegral&) const = default;
|
||||
};
|
||||
enum class EnvironmentUnitError : std::uint8_t {
|
||||
invalid_extent,
|
||||
outside_voxel,
|
||||
invalid_volume,
|
||||
zero_capacity,
|
||||
excess_water,
|
||||
invalid_rate,
|
||||
invalid_remainder,
|
||||
overflow
|
||||
};
|
||||
|
||||
// Public aggregates are unvalidated input. All helpers are pure and checked.
|
||||
[[nodiscard]] std::expected<HabitatMeasure, EnvironmentUnitError>
|
||||
measure_habitat(HabitatBox box) noexcept;
|
||||
[[nodiscard]] std::expected<MassConcentration, EnvironmentUnitError>
|
||||
mass_concentration(accounting::Femtograms mass, CubicMicrometres volume) noexcept;
|
||||
[[nodiscard]] std::expected<WaterSaturation, EnvironmentUnitError>
|
||||
water_saturation(accounting::Femtograms water, accounting::Femtograms capacity) noexcept;
|
||||
// Requires numerator*ticks+remainder to fit u64 even if its quotient could fit.
|
||||
// Returns a proposal: does not fund energy, own a residual or advance an interval.
|
||||
[[nodiscard]] std::expected<EnergyIntegral, EnvironmentUnitError>
|
||||
integrate_energy(EnergyRate rate, std::uint64_t ticks, std::uint64_t remainder) noexcept;
|
||||
} // namespace evo::world
|
||||
@@ -0,0 +1,53 @@
|
||||
#include "evo/world/environment_units.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
|
||||
namespace evo::world {
|
||||
std::expected<HabitatMeasure, EnvironmentUnitError> measure_habitat(HabitatBox box) noexcept {
|
||||
const std::array lengths{box.width.value, box.height.value, box.depth.value};
|
||||
const std::array origins{box.x.value, box.y.value, box.z.value};
|
||||
for (std::size_t i = 0; i < lengths.size(); ++i) {
|
||||
if (lengths[i] == 0 || lengths[i] > habitat_axis_limit_um)
|
||||
return std::unexpected{EnvironmentUnitError::invalid_extent};
|
||||
if (origins[i] > habitat_axis_limit_um - lengths[i])
|
||||
return std::unexpected{EnvironmentUnitError::outside_voxel};
|
||||
}
|
||||
// Validated factors <= 1e6: products <= 1e12 and 1e18 fit u64.
|
||||
const auto area = box.width.value * box.height.value;
|
||||
return HabitatMeasure{{area}, {area * box.depth.value}};
|
||||
}
|
||||
|
||||
std::expected<MassConcentration, EnvironmentUnitError>
|
||||
mass_concentration(accounting::Femtograms mass, CubicMicrometres volume) noexcept {
|
||||
if (volume.value == 0 || volume.value > habitat_volume_limit_um3)
|
||||
return std::unexpected{EnvironmentUnitError::invalid_volume};
|
||||
const auto divisor = std::gcd(mass.value, volume.value);
|
||||
return MassConcentration{mass.value / divisor, volume.value / divisor};
|
||||
}
|
||||
|
||||
std::expected<WaterSaturation, EnvironmentUnitError>
|
||||
water_saturation(accounting::Femtograms water, accounting::Femtograms capacity) noexcept {
|
||||
if (capacity.value == 0)
|
||||
return std::unexpected{EnvironmentUnitError::zero_capacity};
|
||||
if (water.value > capacity.value)
|
||||
return std::unexpected{EnvironmentUnitError::excess_water};
|
||||
const auto divisor = std::gcd(water.value, capacity.value);
|
||||
return WaterSaturation{water.value / divisor, capacity.value / divisor};
|
||||
}
|
||||
|
||||
std::expected<EnergyIntegral, EnvironmentUnitError>
|
||||
integrate_energy(EnergyRate rate, std::uint64_t ticks, std::uint64_t remainder) noexcept {
|
||||
if (rate.ticks_denominator == 0)
|
||||
return std::unexpected{EnvironmentUnitError::invalid_rate};
|
||||
if (remainder >= rate.ticks_denominator)
|
||||
return std::unexpected{EnvironmentUnitError::invalid_remainder};
|
||||
const auto available = std::numeric_limits<std::uint64_t>::max() - remainder;
|
||||
if (ticks != 0 && rate.picojoules_numerator > available / ticks)
|
||||
return std::unexpected{EnvironmentUnitError::overflow};
|
||||
const auto numerator = rate.picojoules_numerator * ticks + remainder;
|
||||
return EnergyIntegral{{numerator / rate.ticks_denominator}, numerator % rate.ticks_denominator};
|
||||
}
|
||||
} // namespace evo::world
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "evo/world/environment_units.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <limits>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
namespace {
|
||||
using namespace evo::world;
|
||||
using evo::accounting::Femtograms;
|
||||
using evo::accounting::Picojoules;
|
||||
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
||||
static_assert(!std::is_convertible_v<CubicMicrometres, Femtograms>);
|
||||
static_assert(!std::is_convertible_v<MassConcentration, Femtograms>);
|
||||
static_assert(!std::is_convertible_v<WaterSaturation, Femtograms>);
|
||||
static_assert(!std::is_convertible_v<Femtograms, Picojoules>);
|
||||
void check(bool ok, std::source_location at = std::source_location::current()) {
|
||||
if (!ok)
|
||||
throw std::runtime_error("environment units line " + std::to_string(at.line()));
|
||||
}
|
||||
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
|
||||
template <typename T>
|
||||
bool refused(const std::expected<T, EnvironmentUnitError>& value, EnvironmentUnitError error) {
|
||||
return !value && value.error() == error;
|
||||
}
|
||||
void geometry_and_ratios() {
|
||||
CHECK(measure_habitat({{0}, {0}, {0}, {1000}, {2000}, {10}}) ==
|
||||
HabitatMeasure{{2'000'000}, {20'000'000}});
|
||||
CHECK(measure_habitat({{0}, {0}, {0}, {1'000'000}, {1'000'000}, {1'000'000}}) ==
|
||||
HabitatMeasure{{1'000'000'000'000}, {habitat_volume_limit_um3}});
|
||||
CHECK(measure_habitat({{999999}, {999999}, {999999}, {1}, {1}, {1}}) ==
|
||||
HabitatMeasure{{1}, {1}});
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
for (const auto invalid : {std::uint64_t{0}, std::uint64_t{1'000'001}, maximum}) {
|
||||
HabitatBox box{{0}, {0}, {0}, {1}, {1}, {1}};
|
||||
auto* extent = axis == 0 ? &box.width : (axis == 1 ? &box.height : &box.depth);
|
||||
extent->value = invalid;
|
||||
CHECK(refused(measure_habitat(box), EnvironmentUnitError::invalid_extent));
|
||||
}
|
||||
for (const auto invalid : {std::uint64_t{1'000'000}, maximum}) {
|
||||
HabitatBox box{{0}, {0}, {0}, {1}, {1}, {1}};
|
||||
auto* origin = axis == 0 ? &box.x : (axis == 1 ? &box.y : &box.z);
|
||||
origin->value = invalid;
|
||||
CHECK(refused(measure_habitat(box), EnvironmentUnitError::outside_voxel));
|
||||
}
|
||||
}
|
||||
CHECK(refused(measure_habitat({{999999}, {0}, {0}, {2}, {1}, {1}}),
|
||||
EnvironmentUnitError::outside_voxel));
|
||||
CHECK(mass_concentration({200}, {20'000'000}) == MassConcentration{1, 100000});
|
||||
CHECK(mass_concentration({0}, {1}) == MassConcentration{0, 1});
|
||||
CHECK(mass_concentration({maximum}, {1}) == MassConcentration{maximum, 1});
|
||||
CHECK(refused(mass_concentration({1}, {0}), EnvironmentUnitError::invalid_volume));
|
||||
CHECK(refused(mass_concentration({1}, {maximum}), EnvironmentUnitError::invalid_volume));
|
||||
CHECK(water_saturation({5'000'000}, {20'000'000}) == WaterSaturation{1, 4});
|
||||
CHECK(water_saturation({0}, {maximum}) == WaterSaturation{0, 1});
|
||||
CHECK(water_saturation({maximum}, {maximum}) == WaterSaturation{1, 1});
|
||||
CHECK(refused(water_saturation({0}, {0}), EnvironmentUnitError::zero_capacity));
|
||||
CHECK(refused(water_saturation({maximum}, {maximum - 1}), EnvironmentUnitError::excess_water));
|
||||
}
|
||||
void interval_accounting() {
|
||||
CHECK(integrate_energy({5, 3}, 6, 0) == EnergyIntegral{{10}, 0});
|
||||
CHECK(integrate_energy({0, 3}, maximum, 2) == EnergyIntegral{{0}, 2});
|
||||
CHECK(integrate_energy({maximum, 3}, 0, 2) == EnergyIntegral{{0}, 2});
|
||||
CHECK(integrate_energy({maximum, 1}, 1, 0) == EnergyIntegral{{maximum}, 0});
|
||||
CHECK(refused(integrate_energy({1, 0}, 0, 0), EnvironmentUnitError::invalid_rate));
|
||||
CHECK(refused(integrate_energy({1, 3}, 0, 3), EnvironmentUnitError::invalid_remainder));
|
||||
CHECK(refused(integrate_energy({maximum, 2}, 2, 0), EnvironmentUnitError::overflow));
|
||||
CHECK(refused(integrate_energy({maximum, 2}, 1, 1), EnvironmentUnitError::overflow));
|
||||
CHECK(integrate_energy({maximum - 1, 2}, 1, 1) == EnergyIntegral{{maximum / 2}, 1});
|
||||
// Independent repeated-addition oracle: count whole units at each denominator crossing.
|
||||
for (std::uint64_t numerator = 0; numerator <= 17; ++numerator) {
|
||||
for (std::uint64_t denominator = 1; denominator <= 19; ++denominator) {
|
||||
for (std::uint64_t initial = 0; initial < denominator; ++initial) {
|
||||
std::uint64_t whole{}, residual = initial, split_whole{}, split_residual = initial;
|
||||
for (std::uint64_t tick = 1; tick <= 23; ++tick) {
|
||||
residual += numerator;
|
||||
while (residual >= denominator) {
|
||||
residual -= denominator;
|
||||
++whole;
|
||||
}
|
||||
const auto part = integrate_energy({numerator, denominator}, 1, split_residual);
|
||||
CHECK(part);
|
||||
split_whole += part->amount.value;
|
||||
split_residual = part->remainder;
|
||||
CHECK(integrate_energy({numerator, denominator}, tick, initial) ==
|
||||
EnergyIntegral{{whole}, residual});
|
||||
CHECK(split_whole == whole && split_residual == residual);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void closed_box_example() {
|
||||
using namespace evo::accounting;
|
||||
const Inventory opening[]{{{100}, {{{0}, {200}, {0}, {20'000'000}}}}, {}, {}, {{7}, {}}};
|
||||
auto ledger = Ledger::create(opening);
|
||||
CHECK(ledger);
|
||||
const auto totals = ledger->conserved_totals();
|
||||
const Transfer capture[]{{{1}, {2}, {{30}, {}}}, {{1}, {3}, {{20}, {}}}};
|
||||
CHECK(ledger->transfer(1, capture));
|
||||
const Transfer uptake[]{{{1}, {2}, {{0}, {{{0}, {50}, {0}, {5'000'000}}}}}};
|
||||
CHECK(ledger->transfer(2, uptake));
|
||||
CHECK(ledger->conserved_totals() == totals);
|
||||
CHECK(ledger->balances()[0].energy.value == 50);
|
||||
CHECK(mass_concentration(ledger->balances()[0].matter[1], {20'000'000}) ==
|
||||
MassConcentration{3, 400000});
|
||||
// Refusal preserves every inventory: a computed proposal cannot mint missing energy.
|
||||
const Transfer overdraft[]{{{1}, {2}, {{51}, {}}}};
|
||||
const std::array before{ledger->balances()[0], ledger->balances()[1], ledger->balances()[2],
|
||||
ledger->balances()[3]};
|
||||
CHECK(!ledger->transfer(3, overdraft));
|
||||
CHECK(ledger->conserved_totals() == totals && ledger->balances()[0].energy.value == 50);
|
||||
for (std::size_t i = 0; i < before.size(); ++i)
|
||||
CHECK(ledger->balances()[i] == before[i]);
|
||||
// Reservoir 4 is outside the selected habitat boundary, but inside the ledger.
|
||||
// This models a recorded import without adding a mint operation to the ledger.
|
||||
const Transfer boundary_import[]{{{4}, {1}, {{7}, {}}}};
|
||||
CHECK(ledger->transfer(3, boundary_import));
|
||||
Inventory independent_sum{};
|
||||
for (const auto& inventory : ledger->balances().first(3)) {
|
||||
independent_sum.energy.value += inventory.energy.value;
|
||||
for (std::size_t channel = 0; channel < independent_sum.matter.size(); ++channel)
|
||||
independent_sum.matter[channel].value += inventory.matter[channel].value;
|
||||
}
|
||||
CHECK(independent_sum == Inventory{{107}, {{{0}, {200}, {0}, {20'000'000}}}});
|
||||
CHECK(ledger->balances()[3] == Inventory{});
|
||||
}
|
||||
} // namespace
|
||||
int main() try {
|
||||
geometry_and_ratios();
|
||||
interval_accounting();
|
||||
closed_box_example();
|
||||
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