diff --git a/CMakeLists.txt b/CMakeLists.txt index b6c202c..d1d589b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,7 +27,7 @@ set(EVO_SANITIZER "none" CACHE STRING "none, address (ASan/UBSan), or thread") set_property(CACHE EVO_SANITIZER PROPERTY STRINGS none address thread) include(cmake/ProjectOptions.cmake) -set(evo_simulation_sources src/simulation/world.cpp src/simulation/snapshot.cpp src/simulation/scheduler.cpp) +set(evo_simulation_sources src/simulation/world.cpp src/simulation/snapshot.cpp src/simulation/scheduler.cpp src/simulation/spatial.cpp) add_library(evo_simulation STATIC ${evo_simulation_sources}) add_library(evo::simulation ALIAS evo_simulation) target_include_directories(evo_simulation PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") @@ -60,6 +60,10 @@ add_executable(evo-benchmark tests/benchmarks/simulation_benchmark.cpp) target_link_libraries(evo-benchmark PRIVATE evo::simulation) evo_owned_target(evo-benchmark) +add_executable(evo-spatial-benchmark tests/benchmarks/spatial_benchmark.cpp) +target_link_libraries(evo-spatial-benchmark PRIVATE evo::simulation) +evo_owned_target(evo-spatial-benchmark) + if(EVO_BUILD_FUZZER) if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR MSVC OR EVO_SANITIZER STREQUAL "thread") message(FATAL_ERROR "Fuzzing requires Linux Clang and is incompatible with TSan") diff --git a/README.md b/README.md index cfad287..cfc3434 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ network service. Dev verification manifests are separate from the simulation. - [Current delivery status and next steps](docs/STATUS.md) - [Opt-in ECS evaluation and measurements](docs/engineering/ECS_EVALUATION.md) - [Sequential command scheduling and recovery](docs/architecture/SCHEDULER_CONTRACT.md) +- [Local periodic spatial queries](docs/architecture/SPATIAL_CONTRACT.md) Read [AGENTS.md](AGENTS.md) before changing code. Architecture and contracts are authoritative over implementation. No external runtime library is needed for @@ -64,6 +65,7 @@ cmake --preset release cmake --build --preset release ctest --preset release ./build/release/evo-benchmark +./build/release/evo-spatial-benchmark ``` ASan uses UBSan too on supported Linux compilers. TSan has a separate `tsan` diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 49505d3..0eea9e5 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -35,7 +35,9 @@ The first increment implements 1.1–1.4 as a proof. M1.5 now has an isolated comparison and scoped recommendation; see engineering/ECS_EVALUATION.md for measured versus still-unmeasured coverage. M1.6 implements the sequential command boundary in ADR-0022; no parallel job execution is claimed. M1.7 spatial queries -are next. A generic ECS or job framework is not required to complete this proof. +now have an exact linear-scan baseline, periodic-image oracle tests and a measured +workload (ADR-0023). A generic ECS or job framework is not required to complete +this proof. Production indexing awaits actual interaction workloads. ## M2 — Minimal energy ecosystem diff --git a/docs/STATUS.md b/docs/STATUS.md index 5dbc2ba..2f519dd 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -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 22 ADRs. + diagrams, biological contracts, engineering constitution and 23 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,9 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic | Priority | Work | Completion evidence | |---|---|---| -| 1 | M1.7 local spatial contract | Neighborhood queries checked against brute force, wrap/boundary/unit tests and measured workload | -| 2 | M2.1 energy/matter ledger | Agreed units/ranges, atomic transfers, nonnegative balances and conservation tests before organisms | -| 3 | M2.2–2.6 first headless energy cycle | Explicit source → producer → consumer → death → decomposition → nutrients; seeded million-tick ledger evidence | +| 1 | M2.1 energy/matter ledger | Agreed units/ranges, atomic transfers, nonnegative balances and conservation tests before organisms | +| 2 | M2.2–2.6 first headless energy cycle | Explicit source → producer → consumer → death → decomposition → nutrients; seeded million-tick ledger evidence | | 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 | M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md): @@ -77,6 +76,13 @@ Nonempty batches copy world state; this favors a clear transaction boundary for the proof, not a measured realtime performance claim. No thread pool or gameplay input protocol is introduced. +M1.7 implements read-only periodic neighborhood queries with stable IDs and +inclusive integer-distance boundaries. A nine-image oracle checks 2,304 seeded +queries across initial, scheduled and restored worlds. Boundary and full-capacity +tests supplement the oracle. The benchmark records uniform/clustered worlds up +to 100,000 entities. This is a linear correctness baseline, not a production +spatial index. See the spatial contract and validation report for scope/evidence. + Before biology, resolve the relevant heredity and energetic contracts rather than treating proof particles as organisms. Exact game tick rate, NPC mutation, logout treatment, species/extinction rules and multicellular transition remain diff --git a/docs/adr/0023-local-neighborhood-queries.md b/docs/adr/0023-local-neighborhood-queries.md new file mode 100644 index 0000000..b58a878 --- /dev/null +++ b/docs/adr/0023-local-neighborhood-queries.md @@ -0,0 +1,58 @@ +# ADR-0023: Local periodic neighborhood queries + +## Status + +Adopted for the bounded M1.7 proof; production spatial indexing deferred. + +## Context + +Interactions need a tested definition of proximity before an acceleration +structure. The current synthetic domain is a 1,024 mm square torus, not a planet +projection or organism scale. The existing world bounds entity count at 100,000. + +## Decision + +Expose a read-only `query_neighbors(world, center, radius)` function. Positions +must be inside the domain. Radius uses the existing unsigned millimetre wrapper; +all its values are valid. Use shortest periodic displacement independently per +axis and an inclusive Euclidean circle. Return unique entity IDs in ascending +order, including entities exactly at the center. No implicit self exclusion. + +Start with a linear scan of current component rows, no cached index or copied +world. Compute squared distance and radius in unsigned 64-bit arithmetic; even +the maximum u32 radius squared fits. No square roots or floating point are used. +The caller owns simulation access and must not mutate concurrently. Results own +their IDs and represent only the state at the call; they are not live handles. + +## Alternatives Considered + +Uniform grids are plausible for local uniform density but add rebuild/update +cost and periodic-cell deduplication. Trees may suit nonuniform density but add +maintenance and traversal complexity. A persistent index would need an explicit +invalidation contract for direct lifecycle operations, ticks and restore. + +## Benefits + +Small exact baseline, stable order, no stale cache, no changes to authoritative +state or snapshots. An independent nine-image oracle validates periodic geometry. + +## Costs + +O(N) distance checks per query, O(K) result space for K matches. All-entity queries +per tick remain O(N squared). The result vector allocates; this is not a realtime +performance promise. Benchmark sparse, clustered, narrow and world-wide queries. + +## Risks + +Accidentally treating returned IDs as guaranteed still alive, confusing this +synthetic torus with future region boundaries, or shipping quadratic interaction +loops without measurement. Allocation failures propagate at the host boundary. + +## Consequences + +Keep index details out of the API. Compare total index maintenance plus query +cost when interaction workloads exist. Neither sensory perception, network +interest management, collision geometry nor spherical coordinates are selected. +No rules/snapshot version bump: queries cannot affect state or PRNG streams. +Tests cover seams, corners, inclusive edges, antipodes, zero/maximum radii, +invalid centers, lifecycle and restore, with an independent periodic-image oracle. diff --git a/docs/adr/README.md b/docs/adr/README.md index 10305ff..74d5ec9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -15,6 +15,7 @@ infrastructure and voxels. 0020 scopes Gitea delivery and the stateless dev Job. Each record has the eight required sections. 0021 authorizes the opt-in ECS comparison only, not a production dependency. 0022 adopts the bounded sequential lifecycle-command scheduler for the proof. +0023 defines local periodic neighborhood queries and a measured linear baseline. Every dependency adoption records exact version/commit and integrity hash, transitive license obligations, maintenance/security review, owner and removal diff --git a/docs/architecture/SIMULATION_ARCHITECTURE.md b/docs/architecture/SIMULATION_ARCHITECTURE.md index 2015e89..6fe5363 100644 --- a/docs/architecture/SIMULATION_ARCHITECTURE.md +++ b/docs/architecture/SIMULATION_ARCHITECTURE.md @@ -100,6 +100,9 @@ format cannot be used for World 0 without a migration ADR. ## Extension seams and failure tests +Read-only proximity queries follow [SPATIAL_CONTRACT.md](SPATIAL_CONTRACT.md). +They inspect current rows without cached state or changes to simulation rules. + Future commands carry tick, entity identity, sequence and validated intention; duplicate/reordered input handling belongs to the host protocol boundary. Biology introduces separate immutable genomes, development and phenotypes before diff --git a/docs/architecture/SPATIAL_CONTRACT.md b/docs/architecture/SPATIAL_CONTRACT.md new file mode 100644 index 0000000..a4ff945 --- /dev/null +++ b/docs/architecture/SPATIAL_CONTRACT.md @@ -0,0 +1,55 @@ +# Local spatial contract + +M1.7 implements [ADR-0023](../adr/0023-local-neighborhood-queries.md). + +```cpp +// include/evo/simulation/spatial.hpp +auto ids = evo::query_neighbors(world, center, evo::Millimetres{16}); +``` + +| Input/result | Contract | +|---|---| +| Frame | Existing synthetic 2D torus, coordinates 0 through 1023 mm per axis | +| Center | Out-of-domain coordinates return `Error::invalid_position`, even for an empty world | +| Radius | Unsigned millimetres, zero through UINT32_MAX; no silent clamp or rejected large radius | +| Geometry | Shortest periodic Euclidean distance; equality with radius is included | +| Identity | Ascending unique IDs; coincident entities all included; caller explicitly excludes self if needed | +| Lifetime | Returned vector owns IDs, not entity references; later removal may invalidate an identity | +| Mutation | No state, tick, PRNG, snapshot or input changes; no clock/I/O/dependency | +| Concurrency | Owner provides a stable world for the duration of the call | + +For each axis, `d = min(abs(a-b), 1024-abs(a-b))`; membership is +`dx*dx + dy*dy <= radius*radius`, evaluated in u64. Maximum squared distance is +524,288. Thus radius 725 includes the entire domain; radius 724 can exclude the +diagonal antipode. Exactly opposite points have an ambiguous direction but a +unique distance; this API deliberately does not return displacement vectors. + +The scan observes current rows on each call, so scheduled creates/removals, +movement and restored state need no invalidation hook. Snapshots serialize only +authoritative state. Future indexes must preserve this query contract and measure +update/rebuild costs, not just warm query timings. Cross-region ghosts and senses +require separate ownership/perception contracts before integration. + +`evo-spatial-benchmark` reports seeded uniform and clustered worlds, 1k/10k/100k +entities, 128 queries, radii 0/16/128/725, one warmup and three measured samples. +Every result contributes to a checksum. Timing includes allocation/destruction, +excludes world/query construction, and has no portable pass/fail threshold. +Timing also includes result checksumming. This is a baseline measurement, not an +index comparison or an MMO capacity claim. + +Windows MSVC 19.44 Release on Ryzen 7 9800X3D (uncontrolled desktop, 2026-09-19): +median milliseconds for 128 queries over 100,000 entities: + +| Radius (mm) | Uniform | Clustered | +|---|---:|---:| +| 0 | 13.60 | 14.18 | +| 16 | 17.73 | 59.31 | +| 128 | 19.48 | 48.53 | +| 725 | 53.35 | 48.36 | + +Raw three-sample results and compiler metadata are in +[spatial-msvc1944.jsonl](../engineering/results/spatial-msvc1944.jsonl). +Clustered query centers are inside the same 32 mm patch as the entities; uniform +centers span the entire domain. Dense result allocation/checksumming matters as +well as scanning. This does not justify querying all 100,000 entities every tick; +measure an index against this baseline when interaction frequency is known. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index e3f594e..5a12105 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -154,3 +154,22 @@ Linux checks, the ECS experiment, separate TSan, and image smoke/publication. This closes the pending Linux validation for M1.6. The maintainer's independent dev image pin from `20e609d` was preserved during rebase. Kustomize renders the three expected dev resources successfully; no cluster execution is claimed. + +## M1.7 spatial queries (2026-09-19) + +Release and MSVC ASan passed 5/5 CTests. Tests cover periodic-image reference +comparison (32 seeds × 3 lifecycle/restore phases × 24 queries), hand-checked +seams/corners/inclusive radii, empty/full capacity, invalid centers and maximum +u32 radius. Queries leave snapshots unchanged; existing v1 goldens remain intact. +Native commands use `tools/windows-check.ps1 -Preset +-Action check` and Release `-Action format`. Initial analysis flagged an unnecessary +test-helper vector copy; the helper now takes a const reference. Final analysis, +Release, ASan and formatting passed after applying the helper's required line +wrapping. Linux CI is pending the source push. + +`build/release/evo-spatial-benchmark.exe` produced 72 measured records plus +metadata in results/spatial-msvc1944.jsonl. One warmup and three samples per +scenario; 1k/10k/100k entities, 128 queries, uniform/clustered positions, four radii. +Timing includes result allocation, destruction and checksum work, excludes setup; +no performance threshold. Desktop CPU load was not isolated. No cluster changes +are required for this library increment. diff --git a/docs/engineering/results/spatial-msvc1944.jsonl b/docs/engineering/results/spatial-msvc1944.jsonl new file mode 100644 index 0000000..3c27bff --- /dev/null +++ b/docs/engineering/results/spatial-msvc1944.jsonl @@ -0,0 +1,73 @@ +{"benchmark":"spatial_scan","seed":123456,"queries":128,"compiler":"MSVC 1944","build":"release"} +{"entities":1000,"clustered":false,"radius_mm":0,"sample":0,"milliseconds":0.14,"matches":0,"checksum":"8421ae126c7ced25"} +{"entities":1000,"clustered":false,"radius_mm":0,"sample":1,"milliseconds":0.14,"matches":0,"checksum":"8421ae126c7ced25"} +{"entities":1000,"clustered":false,"radius_mm":0,"sample":2,"milliseconds":0.14,"matches":0,"checksum":"8421ae126c7ced25"} +{"entities":1000,"clustered":false,"radius_mm":16,"sample":0,"milliseconds":0.1444,"matches":95,"checksum":"1edb741fbb624c04"} +{"entities":1000,"clustered":false,"radius_mm":16,"sample":1,"milliseconds":0.1588,"matches":95,"checksum":"1edb741fbb624c04"} +{"entities":1000,"clustered":false,"radius_mm":16,"sample":2,"milliseconds":0.1442,"matches":95,"checksum":"1edb741fbb624c04"} +{"entities":1000,"clustered":false,"radius_mm":128,"sample":0,"milliseconds":0.2507,"matches":6333,"checksum":"197b09fd12d23f92"} +{"entities":1000,"clustered":false,"radius_mm":128,"sample":1,"milliseconds":0.2408,"matches":6333,"checksum":"197b09fd12d23f92"} +{"entities":1000,"clustered":false,"radius_mm":128,"sample":2,"milliseconds":0.2412,"matches":6333,"checksum":"197b09fd12d23f92"} +{"entities":1000,"clustered":false,"radius_mm":725,"sample":0,"milliseconds":0.4142,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":false,"radius_mm":725,"sample":1,"milliseconds":0.4088,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":false,"radius_mm":725,"sample":2,"milliseconds":0.4097,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":0,"sample":0,"milliseconds":0.1447,"matches":116,"checksum":"95f849d9956a1289"} +{"entities":1000,"clustered":true,"radius_mm":0,"sample":1,"milliseconds":0.1449,"matches":116,"checksum":"95f849d9956a1289"} +{"entities":1000,"clustered":true,"radius_mm":0,"sample":2,"milliseconds":0.1448,"matches":116,"checksum":"95f849d9956a1289"} +{"entities":1000,"clustered":true,"radius_mm":16,"sample":0,"milliseconds":0.6474,"matches":64597,"checksum":"f5f0cd6facbaebcd"} +{"entities":1000,"clustered":true,"radius_mm":16,"sample":1,"milliseconds":0.6329,"matches":64597,"checksum":"f5f0cd6facbaebcd"} +{"entities":1000,"clustered":true,"radius_mm":16,"sample":2,"milliseconds":0.6276,"matches":64597,"checksum":"f5f0cd6facbaebcd"} +{"entities":1000,"clustered":true,"radius_mm":128,"sample":0,"milliseconds":0.4065,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":128,"sample":1,"milliseconds":0.4061,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":128,"sample":2,"milliseconds":0.418,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":725,"sample":0,"milliseconds":0.3854,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":725,"sample":1,"milliseconds":0.3843,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":1000,"clustered":true,"radius_mm":725,"sample":2,"milliseconds":0.4025,"matches":128000,"checksum":"a60febec7ab9e325"} +{"entities":10000,"clustered":false,"radius_mm":0,"sample":0,"milliseconds":1.3963,"matches":1,"checksum":"5e0835545cadf5ab"} +{"entities":10000,"clustered":false,"radius_mm":0,"sample":1,"milliseconds":1.3951,"matches":1,"checksum":"5e0835545cadf5ab"} +{"entities":10000,"clustered":false,"radius_mm":0,"sample":2,"milliseconds":1.394,"matches":1,"checksum":"5e0835545cadf5ab"} +{"entities":10000,"clustered":false,"radius_mm":16,"sample":0,"milliseconds":1.4488,"matches":1000,"checksum":"563898c0fe52a528"} +{"entities":10000,"clustered":false,"radius_mm":16,"sample":1,"milliseconds":1.4529,"matches":1000,"checksum":"563898c0fe52a528"} +{"entities":10000,"clustered":false,"radius_mm":16,"sample":2,"milliseconds":1.4505,"matches":1000,"checksum":"563898c0fe52a528"} +{"entities":10000,"clustered":false,"radius_mm":128,"sample":0,"milliseconds":2.0285,"matches":63039,"checksum":"81341d45cf02b3dc"} +{"entities":10000,"clustered":false,"radius_mm":128,"sample":1,"milliseconds":2.0117,"matches":63039,"checksum":"81341d45cf02b3dc"} +{"entities":10000,"clustered":false,"radius_mm":128,"sample":2,"milliseconds":2.0119,"matches":63039,"checksum":"81341d45cf02b3dc"} +{"entities":10000,"clustered":false,"radius_mm":725,"sample":0,"milliseconds":11.6859,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":false,"radius_mm":725,"sample":1,"milliseconds":11.5476,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":false,"radius_mm":725,"sample":2,"milliseconds":10.8332,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":0,"sample":0,"milliseconds":1.4016,"matches":1197,"checksum":"4f2e291b98eb201a"} +{"entities":10000,"clustered":true,"radius_mm":0,"sample":1,"milliseconds":1.4084,"matches":1197,"checksum":"4f2e291b98eb201a"} +{"entities":10000,"clustered":true,"radius_mm":0,"sample":2,"milliseconds":1.408,"matches":1197,"checksum":"4f2e291b98eb201a"} +{"entities":10000,"clustered":true,"radius_mm":16,"sample":0,"milliseconds":6.9693,"matches":632575,"checksum":"3e1fad9f2fc9870b"} +{"entities":10000,"clustered":true,"radius_mm":16,"sample":1,"milliseconds":7.0701,"matches":632575,"checksum":"3e1fad9f2fc9870b"} +{"entities":10000,"clustered":true,"radius_mm":16,"sample":2,"milliseconds":6.8308,"matches":632575,"checksum":"3e1fad9f2fc9870b"} +{"entities":10000,"clustered":true,"radius_mm":128,"sample":0,"milliseconds":7.0878,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":128,"sample":1,"milliseconds":6.371,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":128,"sample":2,"milliseconds":5.495,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":725,"sample":0,"milliseconds":4.3935,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":725,"sample":1,"milliseconds":3.5206,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":10000,"clustered":true,"radius_mm":725,"sample":2,"milliseconds":4.0367,"matches":1280000,"checksum":"de44a2f828c85925"} +{"entities":100000,"clustered":false,"radius_mm":0,"sample":0,"milliseconds":13.5221,"matches":15,"checksum":"50f14f987716b24b"} +{"entities":100000,"clustered":false,"radius_mm":0,"sample":1,"milliseconds":13.6047,"matches":15,"checksum":"50f14f987716b24b"} +{"entities":100000,"clustered":false,"radius_mm":0,"sample":2,"milliseconds":13.976,"matches":15,"checksum":"50f14f987716b24b"} +{"entities":100000,"clustered":false,"radius_mm":16,"sample":0,"milliseconds":16.5882,"matches":9749,"checksum":"a767f72bb2d9af4a"} +{"entities":100000,"clustered":false,"radius_mm":16,"sample":1,"milliseconds":17.7326,"matches":9749,"checksum":"a767f72bb2d9af4a"} +{"entities":100000,"clustered":false,"radius_mm":16,"sample":2,"milliseconds":17.9647,"matches":9749,"checksum":"a767f72bb2d9af4a"} +{"entities":100000,"clustered":false,"radius_mm":128,"sample":0,"milliseconds":19.5115,"matches":628078,"checksum":"f9038f5eff67bf56"} +{"entities":100000,"clustered":false,"radius_mm":128,"sample":1,"milliseconds":19.4755,"matches":628078,"checksum":"f9038f5eff67bf56"} +{"entities":100000,"clustered":false,"radius_mm":128,"sample":2,"milliseconds":19.4753,"matches":628078,"checksum":"f9038f5eff67bf56"} +{"entities":100000,"clustered":false,"radius_mm":725,"sample":0,"milliseconds":59.0369,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":false,"radius_mm":725,"sample":1,"milliseconds":53.3488,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":false,"radius_mm":725,"sample":2,"milliseconds":48.5176,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":0,"sample":0,"milliseconds":13.8904,"matches":12406,"checksum":"1b55d5c4811da009"} +{"entities":100000,"clustered":true,"radius_mm":0,"sample":1,"milliseconds":14.1833,"matches":12406,"checksum":"1b55d5c4811da009"} +{"entities":100000,"clustered":true,"radius_mm":0,"sample":2,"milliseconds":14.4217,"matches":12406,"checksum":"1b55d5c4811da009"} +{"entities":100000,"clustered":true,"radius_mm":16,"sample":0,"milliseconds":59.3131,"matches":6036142,"checksum":"736f3c780654854d"} +{"entities":100000,"clustered":true,"radius_mm":16,"sample":1,"milliseconds":58.9826,"matches":6036142,"checksum":"736f3c780654854d"} +{"entities":100000,"clustered":true,"radius_mm":16,"sample":2,"milliseconds":60.6342,"matches":6036142,"checksum":"736f3c780654854d"} +{"entities":100000,"clustered":true,"radius_mm":128,"sample":0,"milliseconds":48.6156,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":128,"sample":1,"milliseconds":48.431,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":128,"sample":2,"milliseconds":48.5293,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":725,"sample":0,"milliseconds":48.3565,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":725,"sample":1,"milliseconds":48.3364,"matches":12800000,"checksum":"269e3e46ea192525"} +{"entities":100000,"clustered":true,"radius_mm":725,"sample":2,"milliseconds":48.7952,"matches":12800000,"checksum":"269e3e46ea192525"} diff --git a/include/evo/simulation/spatial.hpp b/include/evo/simulation/spatial.hpp new file mode 100644 index 0000000..582cd40 --- /dev/null +++ b/include/evo/simulation/spatial.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include "evo/simulation/world.hpp" + +namespace evo { +// Read-only point-radius query on the proof torus. Inclusive radius, ascending +// IDs, no implicit self exclusion. Caller must provide a stable world. +[[nodiscard]] std::expected, Error> +query_neighbors(const SimulationWorld& world, Position2 center, Millimetres radius); +} // namespace evo diff --git a/src/simulation/spatial.cpp b/src/simulation/spatial.cpp new file mode 100644 index 0000000..8ce6719 --- /dev/null +++ b/src/simulation/spatial.cpp @@ -0,0 +1,30 @@ +#include "evo/simulation/spatial.hpp" + +#include + +namespace evo { +namespace { +std::uint64_t axis_distance(Millimetres first, Millimetres second) noexcept { + const auto direct = + first.value > second.value ? first.value - second.value : second.value - first.value; + return std::min(direct, domain_extent_mm - direct); +} +} // namespace + +std::expected, Error> query_neighbors(const SimulationWorld& world, + Position2 center, Millimetres radius) { + if (center.x.value >= domain_extent_mm || center.y.value >= domain_extent_mm) { + return std::unexpected{Error::invalid_position}; + } + const auto squared_radius = static_cast(radius.value) * radius.value; + std::vector matches; + for (const auto& entity : world.entities()) { + const auto dx = axis_distance(center.x, entity.position.x); + const auto dy = axis_distance(center.y, entity.position.y); + if (dx * dx + dy * dy <= squared_radius) { + matches.push_back(entity.id); + } + } + return matches; +} +} // namespace evo diff --git a/tests/benchmarks/spatial_benchmark.cpp b/tests/benchmarks/spatial_benchmark.cpp new file mode 100644 index 0000000..f435a14 --- /dev/null +++ b/tests/benchmarks/spatial_benchmark.cpp @@ -0,0 +1,77 @@ +#include "evo/simulation/spatial.hpp" + +#include +#include +#include +#include + +int main() try { + constexpr std::uint64_t seed = 123456; + std::cout << "{\"benchmark\":\"spatial_scan\",\"seed\":" << seed + << ",\"queries\":128,\"compiler\":\"" +#if defined(__clang__) + << "Clang " << __clang_version__ +#elif defined(_MSC_VER) + << "MSVC " << _MSC_VER +#else + << "GCC " << __VERSION__ +#endif + << "\",\"build\":\"" +#if defined(NDEBUG) + << "release" +#else + << "debug" +#endif + << "\"}\n"; + for (const auto count : {1'000U, 10'000U, 100'000U}) { + for (const auto clustered : {false, true}) { + evo::SimulationWorld world{seed}; + evo::Random random{seed}; + const auto coordinate = [&] { + return evo::Millimetres{ + static_cast(random.next() % (clustered ? 32U : 1024U))}; + }; + for (std::uint32_t index = 0; index < count; ++index) { + if (!world.create_entity({coordinate(), coordinate()})) { + throw std::runtime_error("benchmark setup failed"); + } + } + std::array centers{}; + for (auto& center : centers) { + center = {coordinate(), coordinate()}; + } + for (const auto radius : {0U, 16U, 128U, 725U}) { + for (int sample = -1; sample < 3; ++sample) { + std::uint64_t hash = 14695981039346656037ULL; + std::uint64_t matches{}; + const auto start = std::chrono::steady_clock::now(); + for (const auto center : centers) { + const auto found = + evo::query_neighbors(world, center, evo::Millimetres{radius}); + if (!found) { + throw std::runtime_error("benchmark query failed"); + } + matches += found->size(); + hash = (hash ^ found->size()) * 1099511628211ULL; + for (const auto id : *found) { + hash = (hash ^ id.value) * 1099511628211ULL; + } + } + const auto elapsed = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + if (sample >= 0) { + std::cout << "{\"entities\":" << count + << ",\"clustered\":" << (clustered ? "true" : "false") + << ",\"radius_mm\":" << radius << ",\"sample\":" << sample + << ",\"milliseconds\":" << elapsed << ",\"matches\":" << matches + << ",\"checksum\":\"" << std::hex << hash << std::dec << "\"}\n"; + } + } + } + } + } + return 0; +} catch (...) { + return 1; +} diff --git a/tests/simulation_tests.cpp b/tests/simulation_tests.cpp index b39f1d4..f2e2d6d 100644 --- a/tests/simulation_tests.cpp +++ b/tests/simulation_tests.cpp @@ -1,4 +1,5 @@ #include "evo/simulation/scheduler.hpp" +#include "evo/simulation/spatial.hpp" #include "evo/simulation/world.hpp" #include "evo/telemetry/sinks.hpp" @@ -220,6 +221,97 @@ void telemetry_is_host_owned() { CHECK(log.str() == "{\"level\":\"error\",\"event\":\"invalid_snapshot\"}\n"); } +std::vector spatial_reference(const evo::SimulationWorld& world, + evo::Position2 center, evo::Millimetres radius) { + std::vector result; + for (const auto& entity : world.entities()) { + auto nearest = std::numeric_limits::max(); + // Independent oracle: enumerate nine translated images, no minimum-image formula. + for (const auto x_shift : {-1024, 0, 1024}) { + for (const auto y_shift : {-1024, 0, 1024}) { + const auto dx = static_cast(entity.position.x.value) + x_shift - + static_cast(center.x.value); + const auto dy = static_cast(entity.position.y.value) + y_shift - + static_cast(center.y.value); + nearest = std::min(nearest, static_cast(dx * dx + dy * dy)); + } + } + if (nearest <= static_cast(radius.value) * radius.value) { + result.push_back(entity.id); + } + } + return result; +} + +void spatial_boundaries() { + evo::SimulationWorld world{1}; + const std::array positions{evo::Position2{}, + evo::Position2{}, + evo::Position2{{1023}, {0}}, + evo::Position2{{0}, {1023}}, + evo::Position2{{1023}, {1023}}, + evo::Position2{{3}, {4}}, + evo::Position2{{512}, {512}}}; + for (const auto position : positions) { + CHECK(world.create_entity(position)); + } + const auto expect = [&](std::uint32_t radius, const std::vector& ids) { + const auto found = evo::query_neighbors(world, {}, evo::Millimetres{radius}); + CHECK(found && *found == ids); + }; + expect(0, {{1}, {2}}); + expect(1, {{1}, {2}, {3}, {4}}); + expect(2, {{1}, {2}, {3}, {4}, {5}}); + expect(5, {{1}, {2}, {3}, {4}, {5}, {6}}); + expect(724, {{1}, {2}, {3}, {4}, {5}, {6}}); + expect(725, {{1}, {2}, {3}, {4}, {5}, {6}, {7}}); + expect(std::numeric_limits::max(), {{1}, {2}, {3}, {4}, {5}, {6}, {7}}); + for (const auto center : {evo::Position2{{1024}, {}}, evo::Position2{{}, {1024}}}) { + const auto invalid = evo::query_neighbors(world, center, evo::Millimetres{1}); + CHECK(!invalid && invalid.error() == evo::Error::invalid_position); + CHECK(!evo::query_neighbors(evo::SimulationWorld{0}, center, {})); + } + const auto empty = evo::query_neighbors(evo::SimulationWorld{0}, {}, {}); + CHECK(empty && empty->empty()); +} + +void spatial_properties() { + for (std::uint64_t seed = 0; seed < 32; ++seed) { + evo::SimulationWorld world{seed}; + evo::Random random{seed}; + const auto coordinate = [&] { + return evo::Millimetres{static_cast(random.next() % 1024)}; + }; + for (int index = 0; index < 127; ++index) { + CHECK(world.create_entity({coordinate(), coordinate()})); + } + for (int phase = 0; phase < 3; ++phase) { + const auto before = world.serialize(); + for (int query = 0; query < 24; ++query) { + const evo::Position2 center{coordinate(), coordinate()}; + const evo::Millimetres radius{static_cast(random.next() % 800)}; + const auto actual = evo::query_neighbors(world, center, radius); + CHECK(actual && *actual == spatial_reference(world, center, radius)); + CHECK(std::ranges::is_sorted(*actual)); + } + CHECK(world.serialize() == before); + if (phase == 0) { + const std::array commands{evo::Command{1, evo::RemoveEntity{{1}}}, + evo::Command{2, evo::CreateEntity{}}}; + CHECK(evo::advance(world, evo::Tick{1}, commands)); + } else { + auto restored = evo::SimulationWorld::restore(before); + CHECK(restored); + world = std::move(*restored); + } + } + } + const auto full = fixture(1, evo::max_entities); + const auto all = evo::query_neighbors(full, {}, {}); + CHECK(all && all->size() == evo::max_entities); + CHECK(all->front().value == 1 && all->back().value == evo::max_entities); +} + void scheduled_order_and_recovery() { for (std::uint64_t seed = 0; seed < 32; ++seed) { auto expected = fixture(seed, 2); @@ -340,7 +432,9 @@ int main(int argc, char**) try { Test{"canonical empty state", wire_layout_and_empty_state}, Test{"host telemetry", telemetry_is_host_owned}, Test{"scheduled order and recovery", scheduled_order_and_recovery}, - Test{"atomic scheduler rejection", scheduled_rejection}}; + Test{"atomic scheduler rejection", scheduled_rejection}, + Test{"spatial boundaries", spatial_boundaries}, + Test{"spatial oracle properties", spatial_properties}}; int failures = 0; for (const auto& test : tests) { try { diff --git a/tools/ci/linux-check.sh b/tools/ci/linux-check.sh index 79b1797..5bfa4d0 100644 --- a/tools/ci/linux-check.sh +++ b/tools/ci/linux-check.sh @@ -26,6 +26,7 @@ case "$suite" in check_preset analysis clang++-19 check_preset asan clang++-19 ./build/release/evo-benchmark + ./build/release/evo-spatial-benchmark ./build/release/evo-sim --seed 123456 --entities 8 --ticks 1000000 --verify-replay cmake --preset debug -B build/fuzz -DCMAKE_CXX_COMPILER=clang++-19 \