diff --git a/CMakeLists.txt b/CMakeLists.txt index f936192..f13eb99 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -76,7 +76,8 @@ add_library(evo_biology STATIC src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp src/biology/mutation.cpp src/biology/lineage.cpp src/biology/founder.cpp src/biology/cellular_motion.cpp src/biology/cellular_kinematics.cpp - src/biology/cellular_tuning.cpp + src/biology/cellular_tuning.cpp src/biology/cellular_currents.cpp + src/biology/cellular_deposit_motion.cpp src/biology/cellular_uptake.cpp src/biology/cellular_habitat.cpp src/biology/cellular_step.cpp src/biology/cellular_region_step.cpp src/biology/budding.cpp) @@ -498,6 +499,16 @@ if(BUILD_TESTING) add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests) endif() set_tests_properties(cellular-tuning-contracts PROPERTIES TIMEOUT 60) + add_executable(evo-cellular-currents-tests tests/cellular_currents_tests.cpp) + target_link_libraries(evo-cellular-currents-tests PRIVATE evo::biology) + evo_owned_target(evo-cellular-currents-tests) + add_test(NAME cellular-currents-contracts COMMAND evo-cellular-currents-tests) + set_tests_properties(cellular-currents-contracts PROPERTIES TIMEOUT 120) + add_executable(evo-cellular-deposit-motion-tests tests/cellular_deposit_motion_tests.cpp) + target_link_libraries(evo-cellular-deposit-motion-tests PRIVATE evo::biology) + evo_owned_target(evo-cellular-deposit-motion-tests) + add_test(NAME cellular-deposit-motion-contracts COMMAND evo-cellular-deposit-motion-tests) + set_tests_properties(cellular-deposit-motion-contracts PROPERTIES TIMEOUT 120) add_executable(evo-cellular-uptake-tests tests/cellular_uptake_tests.cpp) target_link_libraries(evo-cellular-uptake-tests PRIVATE evo::biology) evo_owned_target(evo-cellular-uptake-tests) diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index 4fa6b03..8c0fc89 100644 --- a/deploy/kubernetes/region/dev-session-route/listener.yaml +++ b/deploy/kubernetes/region/dev-session-route/listener.yaml @@ -12,7 +12,7 @@ spec: env: - {name: REGION_SESSION, value: "dev"} - {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"} - - {name: REGION_SESSION_WINDOW, value: "dev-20261021T203908-f12a35b4:1792629548"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261021T205045-d2835fc2:1792630245"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/include/evo/biology/cellular_currents.hpp b/include/evo/biology/cellular_currents.hpp new file mode 100644 index 0000000..abc6f30 --- /dev/null +++ b/include/evo/biology/cellular_currents.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "evo/biology/cellular_kinematics.hpp" + +#include +#include +#include +#include +#include +#include + +// Procedural currents (Cellular_Region_Changes.md, flows; ADR-0177): a fixed environmental +// condition, not stock. A seeded configuration generates 2-n closed looping routes inside the +// region, each with its own width, speed and direction, rasterized once into a Q10 velocity +// grid. Integer-only, so the client regenerates the identical field from the same +// configuration. +namespace evo::biology { +inline constexpr std::uint32_t max_cellular_current_pitch_um = 10'000; +inline constexpr std::size_t max_cellular_current_nodes = 1'048'576; +inline constexpr std::size_t cellular_current_route_points = 32; + +struct CellularCurrentConfig { + std::uint64_t seed{}; + std::uint32_t width_um{}, height_um{}, pitch_um{}; + std::uint32_t min_count{}, max_count{}; + std::uint32_t min_route_width_um{}, max_route_width_um{}; + std::uint32_t min_speed_um_per_s{}, max_speed_um_per_s{}; + auto operator<=>(const CellularCurrentConfig&) const = default; +}; +struct CellularRoutePoint { + std::int64_t x_um{}, y_um{}; + auto operator<=>(const CellularRoutePoint&) const = default; +}; +// A closed loop; points are in flow order (the last joins the first). +struct CellularCurrentRoute { + std::vector points; + std::uint32_t width_um{}, speed_um_per_s{}; + bool clockwise{}; + auto operator<=>(const CellularCurrentRoute&) const = default; +}; +enum class CellularCurrentError : std::uint8_t { invalid_config, region_too_small }; + +class CellularFlowField { + public: + [[nodiscard]] static std::expected + generate(const CellularCurrentConfig& config); + // Liquid velocity at a point, clamped into the region; bilinear between grid nodes. + [[nodiscard]] CellularFlowSample sample(std::int64_t x_um, std::int64_t y_um) const noexcept; + // At the centre of a square footprint whose lower-left corner is `position`. + [[nodiscard]] CellularFlowSample at_footprint(CellularPosition position, + std::uint32_t extent_um) const noexcept; + [[nodiscard]] const CellularCurrentConfig& config() const noexcept { + return config_; + } + [[nodiscard]] std::span routes() const noexcept { + return routes_; + } + [[nodiscard]] std::span nodes() const noexcept { + return nodes_; + } + [[nodiscard]] std::size_t columns() const noexcept { + return columns_; + } + [[nodiscard]] std::size_t rows() const noexcept { + return rows_; + } + // Fingerprint of the generated grid, for comparing server and client fields. + [[nodiscard]] std::uint64_t digest() const noexcept; + + private: + CellularFlowField() = default; + CellularCurrentConfig config_{}; + std::vector routes_; + std::vector nodes_; + std::size_t columns_{}, rows_{}; +}; +} // namespace evo::biology diff --git a/include/evo/biology/cellular_deposit_motion.hpp b/include/evo/biology/cellular_deposit_motion.hpp new file mode 100644 index 0000000..3aa88e6 --- /dev/null +++ b/include/evo/biology/cellular_deposit_motion.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include "evo/biology/cellular_currents.hpp" +#include "evo/biology/cellular_habitat.hpp" + +#include +#include +#include +#include + +// Moving food (Cellular_Region_Movement_Plan.md, moving food; rules 12). After each tick's +// lives have fed against the deposits where they were, every bubble moves with the local flow +// plus the drift that passing cells induced, bubbles that touch merge (stock is summed, never +// created), and addresses are made unique again. Pools stay where they were placed. +namespace evo::biology { +// A living cell's world velocity this tick, for the drift it induces on nearby bubbles. +struct CellularWake { + CellularPosition position; + std::uint32_t extent_um{}; + std::int32_t velocity_x_q10{}, velocity_y_q10{}; + auto operator<=>(const CellularWake&) const = default; +}; +struct CellularDepositMotionRules { + std::uint32_t drift_radius_um{}; // Cells push bubbles closer than this. + std::int32_t max_drift_q10{}; // Largest induced drift speed. + std::uint32_t drift_decay_ppm{}; // Induced drift lost per tick. + std::uint16_t merged_cap{}; // Bubbles stop merging at this many scattered ones. + std::uint32_t bubble_radius_um{}; // Radius of one unmerged bubble. + auto operator<=>(const CellularDepositMotionRules&) const = default; +}; +struct CellularDepositMotionReport { + std::uint32_t moved{}, merges{}, nudged{}; + auto operator<=>(const CellularDepositMotionReport&) const = default; +}; +struct CellularDepositMotion { + CellularHabitatConfig config; + CellularDepositMotionReport report; +}; + +// Radius of a bubble holding `merged` scattered bubbles: area grows with the count. +[[nodiscard]] std::uint32_t cellular_merged_radius(std::uint32_t bubble_radius_um, + std::uint16_t merged) noexcept; + +// Detached: returns the next format-3 configuration, or an error when the input is not a +// format-3 habitat matching the field's area. `wakes` must be ordered by stable life id. +[[nodiscard]] std::expected +advect_cellular_deposits(const CellularHabitatConfig& config, const CellularFlowField& field, + std::span wakes, + const CellularDepositMotionRules& rules); +} // namespace evo::biology diff --git a/include/evo/biology/cellular_habitat.hpp b/include/evo/biology/cellular_habitat.hpp index 9806a3f..7f6226d 100644 --- a/include/evo/biology/cellular_habitat.hpp +++ b/include/evo/biology/cellular_habitat.hpp @@ -21,11 +21,19 @@ inline constexpr std::uint32_t cellular_habitat_format = 1; // ADR-0136 step A: format 2 holds deposits (pools and bubbles) at free micrometre centres, // each with a stable id, a radius and a kind, and the next id to give a new deposit. inline constexpr std::uint32_t cellular_habitat_deposit_format = 2; +// Format 3 (rules 12, Cellular_Region_Movement_Plan.md): format 2 deposits that move. Each +// record adds the deposit's induced drift, its sub-micrometre carry and how many scattered +// bubbles merged into it. Addresses stay unique: they change between ticks, never within one. +inline constexpr std::uint32_t cellular_habitat_liquid_format = 3; +inline constexpr std::size_t max_cellular_liquid_deposits = 8'192; inline constexpr std::size_t cellular_habitat_header_bytes = 72; inline constexpr std::size_t cellular_patch_record_bytes = 56; inline constexpr std::size_t cellular_deposit_record_bytes = 64; +inline constexpr std::size_t cellular_liquid_record_bytes = cellular_deposit_record_bytes + 20; inline constexpr std::size_t max_cellular_habitat_bytes = - cellular_habitat_header_bytes + cellular_deposit_record_bytes * max_cellular_patches + 8; + cellular_habitat_header_bytes + cellular_liquid_record_bytes * max_cellular_liquid_deposits + 8; +// Carry below one micrometre, in Q10 velocity-microseconds (as CellularMotionState). +inline constexpr std::uint32_t cellular_deposit_carry_limit = 1'024U * 1'000'000U; // A bubble's contact radius (tunable); pools carry their own. inline constexpr std::uint32_t cellular_mote_radius_um = 30; inline constexpr std::uint32_t max_cellular_deposit_radius_um = 5'000; @@ -45,6 +53,11 @@ struct CellularPatch { accounting::Inventory stock{}; std::uint32_t id{}, radius_um{}; CellularDepositKind kind{}; + // Format 3 only (zero otherwise): drift induced by passing cells (Q10 velocity), the + // sub-micrometre carry, and the scattered bubbles merged into this one (1 when unmerged). + std::int32_t drift_x_q10{}, drift_y_q10{}; + std::uint32_t carry_x{}, carry_y{}; + std::uint16_t merged{}; auto operator<=>(const CellularPatch&) const = default; }; struct CellularHabitatConfig { diff --git a/src/biology/cellular_currents.cpp b/src/biology/cellular_currents.cpp new file mode 100644 index 0000000..fdaf113 --- /dev/null +++ b/src/biology/cellular_currents.cpp @@ -0,0 +1,227 @@ +#include "evo/biology/cellular_currents.hpp" + +#include "evo/core/random.hpp" + +#include +#include + +namespace evo::biology { +namespace { +constexpr std::int64_t per_mille = 1'000; +constexpr std::int64_t trig = cellular_trig_one; +// Low-frequency radius wobble, at most this share of the loop radius per harmonic. +constexpr std::int64_t max_wobble_per_mille = 75; + +std::uint64_t integer_sqrt(std::uint64_t value) noexcept { + std::uint64_t result{}, bit = std::uint64_t{1} << 62U; + while (bit > value) + bit >>= 2U; + while (bit != 0) { + if (value >= result + bit) { + value -= result + bit; + result = (result >> 1U) + bit; + } else { + result >>= 1U; + } + bit >>= 2U; + } + return result; +} + +// Inclusive uniform draw; the modulo bias is far below anything gameplay can see and the +// draw is deterministic either way. +std::int64_t uniform(Random& random, std::int64_t low, std::int64_t high) noexcept { + if (high <= low) + return low; + return low + + static_cast(random.next() % static_cast(high - low + 1)); +} + +bool valid(const CellularCurrentConfig& c) noexcept { + return c.width_um != 0 && c.height_um != 0 && c.width_um <= cellular_motion_axis_limit_um && + c.height_um <= cellular_motion_axis_limit_um && c.pitch_um != 0 && + c.pitch_um <= max_cellular_current_pitch_um && c.min_count <= c.max_count && + c.max_count <= 16 && c.min_route_width_um != 0 && + c.min_route_width_um <= c.max_route_width_um && + c.min_speed_um_per_s <= c.max_speed_um_per_s && + std::int64_t{c.max_speed_um_per_s} * cellular_velocity_q10_per_um_s <= + cellular_velocity_limit_q10; +} + +std::expected +generate_route(Random& random, const CellularCurrentConfig& c) { + CellularCurrentRoute route; + route.width_um = + static_cast(uniform(random, c.min_route_width_um, c.max_route_width_um)); + route.speed_um_per_s = + static_cast(uniform(random, c.min_speed_um_per_s, c.max_speed_um_per_s)); + route.clockwise = (random.next() & 1U) != 0; + // Keep the whole stream, wobble included, a grid cell clear of every wall. + const std::int64_t margin = std::int64_t{route.width_um} / 2 + c.pitch_um; + const std::int64_t span_x = std::int64_t{c.width_um} - 2 * margin; + const std::int64_t span_y = std::int64_t{c.height_um} - 2 * margin; + if (span_x < 8 || span_y < 8) + return std::unexpected{CellularCurrentError::region_too_small}; + const auto radius_x = uniform(random, span_x / 8, span_x * 2 / 5); + const auto radius_y = uniform(random, span_y / 8, span_y * 2 / 5); + const std::int64_t wobble_limit = per_mille + 2 * max_wobble_per_mille; + const auto reach_x = radius_x * wobble_limit / per_mille; + const auto reach_y = radius_y * wobble_limit / per_mille; + const auto centre_x = uniform(random, margin + reach_x, c.width_um - margin - reach_x); + const auto centre_y = uniform(random, margin + reach_y, c.height_um - margin - reach_y); + const auto wobble_2 = uniform(random, 0, max_wobble_per_mille); + const auto wobble_3 = uniform(random, 0, max_wobble_per_mille); + const auto phase_2 = static_cast(random.next()); + const auto phase_3 = static_cast(random.next()); + constexpr auto step = cellular_heading_turn / cellular_current_route_points; + for (std::size_t k = 0; k < cellular_current_route_points; ++k) { + const auto theta = static_cast(k * step); + const auto radius = + per_mille + + wobble_2 * cellular_cos_q14(static_cast(2 * theta + phase_2)) / trig + + wobble_3 * cellular_cos_q14(static_cast(3 * theta + phase_3)) / trig; + route.points.push_back( + {centre_x + radius_x * radius * cellular_cos_q14(theta) / (per_mille * trig), + centre_y + radius_y * radius * cellular_sin_q14(theta) / (per_mille * trig)}); + } + if (route.clockwise) + std::ranges::reverse(route.points); + return route; +} + +struct Contribution { + std::int64_t x{}, y{}; + bool inside{}; +}; + +// Velocity of one route at a point: along the nearest segment, full at the centreline and +// falling to zero at the stream's edge. +Contribution route_velocity(const CellularCurrentRoute& route, std::int64_t px, + std::int64_t py) noexcept { + std::int64_t best = std::numeric_limits::max(); + std::int64_t tangent_x{}, tangent_y{}; + const auto count = route.points.size(); + for (std::size_t index = 0; index < count; ++index) { + const auto& a = route.points[index]; + const auto& b = route.points[(index + 1) % count]; + const auto abx = b.x_um - a.x_um, aby = b.y_um - a.y_um; + const auto length_squared = abx * abx + aby * aby; + if (length_squared == 0) + continue; + const auto along = + std::clamp((px - a.x_um) * abx + (py - a.y_um) * aby, 0, length_squared); + const auto dx = px - (a.x_um + abx * along / length_squared); + const auto dy = py - (a.y_um + aby * along / length_squared); + const auto distance_squared = dx * dx + dy * dy; + if (distance_squared < best) { + best = distance_squared; + tangent_x = abx; + tangent_y = aby; + } + } + const std::int64_t half = route.width_um / 2; + if (best >= half * half) + return {}; + const auto profile = per_mille - best * per_mille / (half * half); + const auto length = static_cast( + integer_sqrt(static_cast(tangent_x * tangent_x + tangent_y * tangent_y))); + const auto speed = std::int64_t{route.speed_um_per_s} * cellular_velocity_q10_per_um_s; + return {speed * profile / per_mille * tangent_x / length, + speed * profile / per_mille * tangent_y / length, true}; +} + +// Overlapping streams add, capped at the fastest contributing stream's speed. +CellularFlowSample node_velocity(std::span routes, std::int64_t x, + std::int64_t y) noexcept { + std::int64_t vx{}, vy{}, cap{}; + for (const auto& route : routes) { + const auto part = route_velocity(route, x, y); + if (!part.inside) + continue; + vx += part.x; + vy += part.y; + cap = std::max(cap, std::int64_t{route.speed_um_per_s} * cellular_velocity_q10_per_um_s); + } + const auto speed = + static_cast(integer_sqrt(static_cast(vx * vx + vy * vy))); + if (speed > cap && speed > 0) { + vx = vx * cap / speed; + vy = vy * cap / speed; + } + return {static_cast(vx), static_cast(vy)}; +} +} // namespace + +std::expected +CellularFlowField::generate(const CellularCurrentConfig& config) { + if (!valid(config)) + return std::unexpected{CellularCurrentError::invalid_config}; + const auto columns = std::size_t{config.width_um} / config.pitch_um + 2; + const auto rows = std::size_t{config.height_um} / config.pitch_um + 2; + if (columns * rows > max_cellular_current_nodes) + return std::unexpected{CellularCurrentError::invalid_config}; + CellularFlowField field; + field.config_ = config; + field.columns_ = columns; + field.rows_ = rows; + Random random{config.seed}; + const auto count = uniform(random, config.min_count, config.max_count); + for (std::int64_t index = 0; index < count; ++index) { + auto route = generate_route(random, config); + if (!route) + return std::unexpected{route.error()}; + field.routes_.push_back(std::move(*route)); + } + field.nodes_.reserve(columns * rows); + for (std::size_t row = 0; row < rows; ++row) + for (std::size_t column = 0; column < columns; ++column) + field.nodes_.push_back( + node_velocity(field.routes_, static_cast(column * config.pitch_um), + static_cast(row * config.pitch_um))); + return field; +} + +CellularFlowSample CellularFlowField::sample(std::int64_t x_um, std::int64_t y_um) const noexcept { + const std::int64_t pitch = config_.pitch_um; + const auto x = std::clamp(x_um, 0, config_.width_um); + const auto y = std::clamp(y_um, 0, config_.height_um); + const auto column = static_cast(x / pitch); + const auto row = static_cast(y / pitch); + const auto fx = x % pitch, fy = y % pitch; + const auto at = [this](std::size_t c, std::size_t r) -> const CellularFlowSample& { + return nodes_[r * columns_ + c]; + }; + const auto& n00 = at(column, row); + const auto& n10 = at(column + 1, row); + const auto& n01 = at(column, row + 1); + const auto& n11 = at(column + 1, row + 1); + const auto blend = [&](std::int64_t v00, std::int64_t v10, std::int64_t v01, std::int64_t v11) { + return (v00 * (pitch - fx) * (pitch - fy) + v10 * fx * (pitch - fy) + + v01 * (pitch - fx) * fy + v11 * fx * fy) / + (pitch * pitch); + }; + return {static_cast(blend(n00.x_q10, n10.x_q10, n01.x_q10, n11.x_q10)), + static_cast(blend(n00.y_q10, n10.y_q10, n01.y_q10, n11.y_q10))}; +} + +CellularFlowSample CellularFlowField::at_footprint(CellularPosition position, + std::uint32_t extent_um) const noexcept { + return sample(static_cast(position.x_um + extent_um / 2), + static_cast(position.y_um + extent_um / 2)); +} + +std::uint64_t CellularFlowField::digest() const noexcept { + std::uint64_t hash = 14695981039346656037ULL; + const auto mix = [&hash](std::uint64_t value) { + for (int byte = 0; byte < 8; ++byte) { + hash = (hash ^ (value & 0xffU)) * 1099511628211ULL; + value >>= 8U; + } + }; + for (const auto& node : nodes_) { + mix(static_cast(node.x_q10)); + mix(static_cast(node.y_q10)); + } + return hash; +} +} // namespace evo::biology diff --git a/src/biology/cellular_deposit_motion.cpp b/src/biology/cellular_deposit_motion.cpp new file mode 100644 index 0000000..229ecc2 --- /dev/null +++ b/src/biology/cellular_deposit_motion.cpp @@ -0,0 +1,279 @@ +#include "evo/biology/cellular_deposit_motion.hpp" + +#include +#include +#include +#include + +namespace evo::biology { +namespace { +constexpr std::int64_t carry_per_um = cellular_velocity_q10_per_um_s * 1'000'000; +constexpr std::int64_t tick_microseconds = cellular_motion_tick_microseconds; +// Induced drift closes this share of the gap to the pushing cells' velocity each tick. +constexpr std::int64_t drift_blend_divisor = 4; + +std::uint64_t integer_sqrt(std::uint64_t value) noexcept { + std::uint64_t result{}, bit = std::uint64_t{1} << 62U; + while (bit > value) + bit >>= 2U; + while (bit != 0) { + if (value >= result + bit) { + value -= result + bit; + result = (result >> 1U) + bit; + } else { + result >>= 1U; + } + bit >>= 2U; + } + return result; +} + +std::int64_t floor_div(std::int64_t value, std::int64_t divisor) noexcept { + const auto quotient = value / divisor; + return value % divisor != 0 && value < 0 ? quotient - 1 : quotient; +} + +std::int64_t decay(std::int64_t v, std::uint32_t ppm) noexcept { + if (v == 0 || ppm == 0) + return v; + const auto size = v < 0 ? -v : v; + const auto loss = std::min(size, (size * ppm + cellular_drag_ppm_limit - 1) / + cellular_drag_ppm_limit); + return v < 0 ? v + loss : v - loss; +} + +bool add(accounting::Inventory& to, const accounting::Inventory& from) noexcept { + constexpr auto top = std::numeric_limits::max(); + if (from.energy.value > top - to.energy.value) + return false; + for (std::size_t channel = 0; channel < to.matter.size(); ++channel) + if (from.matter[channel].value > top - to.matter[channel].value) + return false; + to.energy.value += from.energy.value; + for (std::size_t channel = 0; channel < to.matter.size(); ++channel) + to.matter[channel].value += from.matter[channel].value; + return true; +} + +// Fixed-size square buckets over the region; keys are row-major. +struct Buckets { + std::int64_t size{}, columns{}; + [[nodiscard]] std::int64_t key(std::int64_t x, std::int64_t y) const noexcept { + return (y / size) * columns + x / size; + } +}; + +// (bucket, item) pairs sorted by bucket then item, so a bucket's items keep their order. +std::vector> +bucketed(const Buckets& buckets, std::size_t count, const auto& position_of) { + std::vector> entries; + entries.reserve(count); + for (std::size_t index = 0; index < count; ++index) { + const auto [x, y] = position_of(index); + entries.emplace_back(buckets.key(x, y), index); + } + std::ranges::sort(entries); + return entries; +} + +// Items in the 3 x 3 buckets around a point. +void neighbours(const Buckets& buckets, + const std::vector>& entries, std::int64_t x, + std::int64_t y, std::vector& out) { + out.clear(); + const auto column = x / buckets.size, row = y / buckets.size; + for (std::int64_t r = row - 1; r <= row + 1; ++r) { + for (std::int64_t c = column - 1; c <= column + 1; ++c) { + if (r < 0 || c < 0 || c >= buckets.columns) + continue; + const auto key = r * buckets.columns + c; + auto it = std::ranges::lower_bound(entries, std::pair{key, std::size_t{0}}); + for (; it != entries.end() && it->first == key; ++it) + out.push_back(it->second); + } + } + std::ranges::sort(out); +} +} // namespace + +std::uint32_t cellular_merged_radius(std::uint32_t bubble_radius_um, + std::uint16_t merged) noexcept { + const auto scale = integer_sqrt(std::uint64_t{merged} * 1'000'000); + return static_cast(std::min( + max_cellular_deposit_radius_um, std::uint64_t{bubble_radius_um} * scale / 1'000)); +} + +std::expected +advect_cellular_deposits(const CellularHabitatConfig& config, const CellularFlowField& field, + std::span wakes, + const CellularDepositMotionRules& rules) { + if (config.format != cellular_habitat_liquid_format || + field.config().width_um != config.width_um || + field.config().height_um != config.height_um || rules.merged_cap == 0 || + rules.bubble_radius_um == 0 || rules.bubble_radius_um > max_cellular_deposit_radius_um || + rules.max_drift_q10 < 0 || rules.max_drift_q10 > cellular_velocity_limit_q10 || + rules.drift_decay_ppm >= cellular_drag_ppm_limit) + return std::unexpected{CellularHabitatError::invalid_config}; + + CellularDepositMotion result{config, {}}; + auto& patches = result.config.patches; + const std::int64_t width = config.width_um, height = config.height_um; + + // Wakes indexed by drift radius, so each bubble checks only nearby cells. + const std::int64_t radius = rules.drift_radius_um; + const Buckets wake_buckets{std::max(radius, 1), + width / std::max(radius, 1) + 1}; + const auto wake_centre = [&wakes](std::size_t index) { + const auto& wake = wakes[index]; + return std::pair{static_cast(wake.position.x_um + wake.extent_um / 2), + static_cast(wake.position.y_um + wake.extent_um / 2)}; + }; + const auto wake_index = radius > 0 ? bucketed(wake_buckets, wakes.size(), wake_centre) + : std::vector>{}; + std::vector nearby; + + for (auto& patch : patches) { + if (patch.kind != CellularDepositKind::mote) + continue; + const std::int64_t x = patch.address.x_um, y = patch.address.y_um; + std::int64_t drift_x = patch.drift_x_q10, drift_y = patch.drift_y_q10; + if (radius > 0) { + neighbours(wake_buckets, wake_index, x, y, nearby); + std::int64_t target_x{}, target_y{}; + bool pushed = false; + for (const auto index : nearby) { + const auto [cx, cy] = wake_centre(index); + const auto dx = x - cx, dy = y - cy; + const auto distance_squared = dx * dx + dy * dy; + if (distance_squared >= radius * radius) + continue; + const auto distance = static_cast( + integer_sqrt(static_cast(distance_squared))); + target_x += + std::int64_t{wakes[index].velocity_x_q10} * (radius - distance) / radius; + target_y += + std::int64_t{wakes[index].velocity_y_q10} * (radius - distance) / radius; + pushed = true; + } + if (pushed) { + drift_x += (target_x - drift_x) / drift_blend_divisor; + drift_y += (target_y - drift_y) / drift_blend_divisor; + } + const auto speed = static_cast( + integer_sqrt(static_cast(drift_x * drift_x + drift_y * drift_y))); + if (speed > rules.max_drift_q10 && speed > 0) { + drift_x = drift_x * rules.max_drift_q10 / speed; + drift_y = drift_y * rules.max_drift_q10 / speed; + } + } + const auto flow = field.sample(x, y); + auto carry_x = std::int64_t{patch.carry_x} + (flow.x_q10 + drift_x) * tick_microseconds; + auto carry_y = std::int64_t{patch.carry_y} + (flow.y_q10 + drift_y) * tick_microseconds; + const auto step_x = floor_div(carry_x, carry_per_um); + const auto step_y = floor_div(carry_y, carry_per_um); + carry_x -= step_x * carry_per_um; + carry_y -= step_y * carry_per_um; + auto next_x = x + step_x, next_y = y + step_y; + // Region edges stop a bubble; its carry and drift into the edge are dropped. + if (next_x < 0 || next_x > width - 1) { + next_x = std::clamp(next_x, 0, width - 1); + carry_x = 0; + drift_x = 0; + } + if (next_y < 0 || next_y > height - 1) { + next_y = std::clamp(next_y, 0, height - 1); + carry_y = 0; + drift_y = 0; + } + if (next_x != x || next_y != y) + ++result.report.moved; + patch.address = {static_cast(next_x), static_cast(next_y)}; + patch.carry_x = static_cast(carry_x); + patch.carry_y = static_cast(carry_y); + patch.drift_x_q10 = static_cast(decay(drift_x, rules.drift_decay_ppm)); + patch.drift_y_q10 = static_cast(decay(drift_y, rules.drift_decay_ppm)); + } + + // Merge touching bubbles in ascending id: the lower id absorbs the higher one. + std::vector motes; + for (std::size_t index = 0; index < patches.size(); ++index) + if (patches[index].kind == CellularDepositKind::mote) + motes.push_back(index); + std::ranges::sort(motes, {}, [&patches](std::size_t index) { return patches[index].id; }); + const auto largest = static_cast( + std::max(cellular_merged_radius(rules.bubble_radius_um, rules.merged_cap), + max_cellular_deposit_radius_um / 8)); + const Buckets merge_buckets{2 * largest, width / (2 * largest) + 1}; + const auto mote_index = bucketed(merge_buckets, motes.size(), [&](std::size_t order) { + const auto& patch = patches[motes[order]]; + return std::pair{static_cast(patch.address.x_um), + static_cast(patch.address.y_um)}; + }); + std::vector absorbed(motes.size(), false); + for (std::size_t order = 0; order < motes.size(); ++order) { + if (absorbed[order]) + continue; + auto& keeper = patches[motes[order]]; + neighbours(merge_buckets, mote_index, keeper.address.x_um, keeper.address.y_um, nearby); + for (const auto other : nearby) { + if (other <= order || absorbed[other] || keeper.merged >= rules.merged_cap) + continue; + const auto& taken = patches[motes[other]]; + if (std::uint32_t{keeper.merged} + taken.merged > rules.merged_cap) + continue; + const auto dx = std::int64_t{keeper.address.x_um} - taken.address.x_um; + const auto dy = std::int64_t{keeper.address.y_um} - taken.address.y_um; + const auto reach = std::int64_t{keeper.radius_um} + taken.radius_um; + if (dx * dx + dy * dy > reach * reach) + continue; + if (!add(keeper.stock, taken.stock)) + return std::unexpected{CellularHabitatError::overflow}; + const std::int64_t mass = keeper.merged, more = taken.merged; + keeper.drift_x_q10 = static_cast( + (keeper.drift_x_q10 * mass + taken.drift_x_q10 * more) / (mass + more)); + keeper.drift_y_q10 = static_cast( + (keeper.drift_y_q10 * mass + taken.drift_y_q10 * more) / (mass + more)); + keeper.merged = static_cast(mass + more); + keeper.radius_um = + std::max({keeper.radius_um, taken.radius_um, + cellular_merged_radius(rules.bubble_radius_um, keeper.merged)}); + absorbed[other] = true; + ++result.report.merges; + } + } + if (result.report.merges != 0) { + std::vector removed(patches.size(), false); + for (std::size_t order = 0; order < motes.size(); ++order) + if (absorbed[order]) + removed[motes[order]] = true; + std::vector kept; + kept.reserve(patches.size() - result.report.merges); + for (std::size_t index = 0; index < patches.size(); ++index) + if (!removed[index]) + kept.push_back(patches[index]); + patches = std::move(kept); + } + + // Addresses are unique: a later id sharing an address steps one micrometre along x. + const auto order = [](const CellularPatch& a, const CellularPatch& b) { + return std::pair{a.address, a.id} < std::pair{b.address, b.id}; + }; + std::ranges::sort(patches, order); + for (bool clash = true; clash;) { + clash = false; + for (std::size_t index = 1; index < patches.size(); ++index) { + if (patches[index].address != patches[index - 1].address) + continue; + auto& moved = patches[index].kind == CellularDepositKind::pool ? patches[index - 1] + : patches[index]; + moved.address.x_um = moved.address.x_um + 1 < config.width_um ? moved.address.x_um + 1 + : moved.address.x_um - 1; + ++result.report.nudged; + clash = true; + } + if (clash) + std::ranges::sort(patches, order); + } + return result; +} +} // namespace evo::biology diff --git a/src/biology/cellular_habitat.cpp b/src/biology/cellular_habitat.cpp index eedb8c7..ff3e671 100644 --- a/src/biology/cellular_habitat.cpp +++ b/src/biology/cellular_habitat.cpp @@ -1,5 +1,7 @@ #include "evo/biology/cellular_habitat.hpp" +#include "evo/biology/cellular_kinematics.hpp" + #include #include #include @@ -96,12 +98,16 @@ CellularHabitat::create(CellularHabitatConfig config) { config.height_um > cellular_motion_axis_limit_um || config.width_um % cellular_patch_pitch_um != 0 || config.height_um % cellular_patch_pitch_um != 0 || - config.patches.size() > max_cellular_patches || (config.format != cellular_habitat_format && - config.format != cellular_habitat_deposit_format) || + config.format != cellular_habitat_deposit_format && + config.format != cellular_habitat_liquid_format) || + config.patches.size() > (config.format == cellular_habitat_liquid_format + ? max_cellular_liquid_deposits + : max_cellular_patches) || (config.format == cellular_habitat_format && config.next_deposit != 0)) return std::unexpected{CellularHabitatError::invalid_config}; - const bool deposits = config.format == cellular_habitat_deposit_format; + const bool liquid = config.format == cellular_habitat_liquid_format; + const bool deposits = config.format == cellular_habitat_deposit_format || liquid; accounting::Inventory totals{}; std::vector ids; @@ -121,6 +127,19 @@ CellularHabitat::create(CellularHabitatConfig config) { patch.radius_um > max_cellular_deposit_radius_um || (patch.kind != CellularDepositKind::pool && patch.kind != CellularDepositKind::mote))) return std::unexpected{CellularHabitatError::invalid_patch}; + const bool moving = patch.drift_x_q10 != 0 || patch.drift_y_q10 != 0 || + patch.carry_x != 0 || patch.carry_y != 0; + // Format 3: bounded drift and carry on bubbles only; every deposit counts at least one + // merged bubble. Earlier formats carry none of these fields. + if (liquid ? (patch.merged == 0 || patch.carry_x >= cellular_deposit_carry_limit || + patch.carry_y >= cellular_deposit_carry_limit || + patch.drift_x_q10 < -cellular_velocity_limit_q10 || + patch.drift_x_q10 > cellular_velocity_limit_q10 || + patch.drift_y_q10 < -cellular_velocity_limit_q10 || + patch.drift_y_q10 > cellular_velocity_limit_q10 || + (patch.kind == CellularDepositKind::pool && (moving || patch.merged != 1))) + : (moving || patch.merged != 0)) + return std::unexpected{CellularHabitatError::invalid_patch}; if (deposits) ids.push_back(patch.id); if (index != 0 && !(config.patches[index - 1].address < patch.address)) @@ -237,7 +256,8 @@ std::vector CellularHabitat::snapshot() const { cellular_patch_record_bytes * config_.patches.size() + 8); Writer out{bytes}; out.put(habitat_magic); - const bool deposits = config_.format == cellular_habitat_deposit_format; + const bool liquid = config_.format == cellular_habitat_liquid_format; + const bool deposits = config_.format == cellular_habitat_deposit_format || liquid; out.put(config_.format, 4); out.put(habitat_rules, 4); out.put(config_.world); @@ -258,6 +278,14 @@ std::vector CellularHabitat::snapshot() const { out.put(static_cast(patch.kind), 1); out.put(0, 1); } + if (liquid) { + out.put(static_cast(patch.drift_x_q10), 4); + out.put(static_cast(patch.drift_y_q10), 4); + out.put(patch.carry_x, 4); + out.put(patch.carry_y, 4); + out.put(patch.merged, 2); + out.put(0, 2); + } out.put(patch.source); out.inventory(patch.stock); } @@ -278,10 +306,12 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl if (in.get() != habitat_magic) return std::unexpected{CellularHabitatError::format}; const auto format = in.get(4); - if ((format != cellular_habitat_format && format != cellular_habitat_deposit_format) || + if ((format != cellular_habitat_format && format != cellular_habitat_deposit_format && + format != cellular_habitat_liquid_format) || in.get(4) != habitat_rules) return std::unexpected{CellularHabitatError::version}; - const bool deposits = format == cellular_habitat_deposit_format; + const bool liquid = format == cellular_habitat_liquid_format; + const bool deposits = format == cellular_habitat_deposit_format || liquid; CellularHabitatConfig config; config.format = static_cast(format); config.world = in.get(); @@ -295,8 +325,10 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl return std::unexpected{CellularHabitatError::version}; const auto count = in.get(4); const auto next_deposit = in.get(); - const auto record = deposits ? cellular_deposit_record_bytes : cellular_patch_record_bytes; - if (in.get() != 0 || count > max_cellular_patches || + const auto record = liquid ? cellular_liquid_record_bytes + : deposits ? cellular_deposit_record_bytes + : cellular_patch_record_bytes; + if (in.get() != 0 || count > (liquid ? max_cellular_liquid_deposits : max_cellular_patches) || next_deposit > std::numeric_limits::max() || bytes.size() != cellular_habitat_header_bytes + record * count + 8) return std::unexpected{CellularHabitatError::format}; @@ -314,6 +346,15 @@ CellularHabitat::restore(std::span bytes, std::uint64_t worl return std::unexpected{CellularHabitatError::format}; patch.kind = static_cast(kind); } + if (liquid) { + patch.drift_x_q10 = static_cast(static_cast(in.get(4))); + patch.drift_y_q10 = static_cast(static_cast(in.get(4))); + patch.carry_x = static_cast(in.get(4)); + patch.carry_y = static_cast(in.get(4)); + patch.merged = static_cast(in.get(2)); + if (in.get(2) != 0) + return std::unexpected{CellularHabitatError::format}; + } patch.source = in.get(); patch.stock = in.inventory(); config.patches.push_back(patch); diff --git a/src/biology/cellular_tuning.cpp b/src/biology/cellular_tuning.cpp index dbbbad7..6957c3c 100644 --- a/src/biology/cellular_tuning.cpp +++ b/src/biology/cellular_tuning.cpp @@ -43,7 +43,7 @@ constexpr std::array fields{ speed_limit}, Field{"currents.max_speed_um_per_s", &CellularTuning::currents_max_speed_um_per_s, 0, speed_limit}, - Field{"currents.grid_pitch_um", &CellularTuning::currents_grid_pitch_um, 10, 100'000}, + Field{"currents.grid_pitch_um", &CellularTuning::currents_grid_pitch_um, 10, 10'000}, Field{"food.merged_bubble_cap_multiple", &CellularTuning::food_merged_bubble_cap_multiple, 1, 1'000}, Field{"food.visible_moving_bubbles", &CellularTuning::food_visible_moving_bubbles, 0, 512}, diff --git a/tests/cellular_currents_tests.cpp b/tests/cellular_currents_tests.cpp new file mode 100644 index 0000000..fb1d16d --- /dev/null +++ b/tests/cellular_currents_tests.cpp @@ -0,0 +1,172 @@ +#include "evo/biology/cellular_currents.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::biology; +void check(bool value, std::source_location at = std::source_location::current()) { + if (!value) + throw std::runtime_error("cellular currents line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) + +constexpr std::int64_t um_per_s = cellular_velocity_q10_per_um_s; + +// The v0 tuning: 60 x 60 mm, 2-4 routes, 3-6 mm wide, 60-300 um/s, 250 um grid. +CellularCurrentConfig v0(std::uint64_t seed) { + return {seed, 60'000, 60'000, 250, 2, 4, 3'000, 6'000, 60, 300}; +} + +CellularFlowField generate(const CellularCurrentConfig& config) { + auto field = CellularFlowField::generate(config); + check(field.has_value()); + return std::move(*field); +} + +std::int64_t speed(CellularFlowSample sample) { + const auto x = static_cast(sample.x_q10), y = static_cast(sample.y_q10); + return std::llround(std::sqrt(x * x + y * y)); +} + +void deterministic_generation() { + const auto first = generate(v0(7)); + const auto second = generate(v0(7)); + CHECK(first.digest() == second.digest() && first.routes().size() == second.routes().size()); + CHECK(generate(v0(8)).digest() != first.digest()); + CHECK(first.columns() == 242 && first.rows() == 242); + std::printf("current field digest %llu\n", static_cast(first.digest())); + CHECK(first.digest() == 6'763'241'105'898'603'476ULL); +} + +void routes_within_configuration() { + for (std::uint64_t seed = 1; seed <= 40; ++seed) { + const auto field = generate(v0(seed)); + CHECK(field.routes().size() >= 2 && field.routes().size() <= 4); + for (const auto& route : field.routes()) { + CHECK(route.width_um >= 3'000 && route.width_um <= 6'000); + CHECK(route.speed_um_per_s >= 60 && route.speed_um_per_s <= 300); + CHECK(route.points.size() == cellular_current_route_points); + const std::int64_t clear = route.width_um / 2; + for (const auto& point : route.points) + CHECK(point.x_um > clear && point.x_um < 60'000 - clear && point.y_um > clear && + point.y_um < 60'000 - clear); + } + } +} + +void bounded_with_quiet_water_and_still_walls() { + for (std::uint64_t seed = 1; seed <= 20; ++seed) { + const auto field = generate(v0(seed)); + std::size_t still{}, flowing{}; + for (const auto& node : field.nodes()) { + CHECK(speed(node) <= 300 * um_per_s); + (node.x_q10 == 0 && node.y_q10 == 0 ? still : flowing) += 1; + } + // Both quiet water and currents exist in every region. + CHECK(still > field.nodes().size() / 5 && flowing > field.nodes().size() / 20); + // Walls are still, so nothing is carried into them. + for (std::int64_t along = 0; along <= 60'000; along += 250) { + CHECK(field.sample(0, along) == CellularFlowSample{}); + CHECK(field.sample(60'000, along) == CellularFlowSample{}); + CHECK(field.sample(along, 0) == CellularFlowSample{}); + CHECK(field.sample(along, 60'000) == CellularFlowSample{}); + } + } +} + +void route_centreline_runs_at_route_speed() { + const auto field = generate(v0(3)); + const auto& route = field.routes().front(); + const auto& a = route.points[4]; + const auto& b = route.points[5]; + const auto middle = field.sample((a.x_um + b.x_um) / 2, (a.y_um + b.y_um) / 2); + const auto expected = std::int64_t{route.speed_um_per_s} * um_per_s; + // Near full speed at the centreline, allowing for overlap and the grid. + CHECK(speed(middle) > expected * 8 / 10 && speed(middle) <= expected); + // Flow follows the route direction. + const auto along = (b.x_um - a.x_um) * middle.x_q10 + (b.y_um - a.y_um) * middle.y_q10; + CHECK(along > 0); +} + +void interpolation_is_continuous() { + const auto field = generate(v0(5)); + for (std::int64_t y = 1'000; y < 59'000; y += 1'777) + for (std::int64_t x = 1'000; x < 59'000; x += 13) { + const auto here = field.sample(x, y), next = field.sample(x + 1, y); + CHECK(std::abs(std::int64_t{here.x_q10} - next.x_q10) < 4 * um_per_s); + CHECK(std::abs(std::int64_t{here.y_q10} - next.y_q10) < 4 * um_per_s); + } +} + +// A passive cell placed in a stream circulates for minutes without reaching a wall. +void passive_drift_circulates() { + const auto field = generate(v0(11)); + const auto& start = field.routes().front().points.front(); + constexpr std::uint32_t extent = 20; + CellularPosition position{static_cast(start.x_um - extent / 2), + static_cast(start.y_um - extent / 2)}; + CellularMotionState state{}; + const CellularHandling passive{.forward_drag_ppm = 95'163, .lateral_drag_ppm = 95'163}; + std::uint64_t travelled{}; + for (int tick = 0; tick < 20 * 60 * 5; ++tick) { + const auto next = + step_cellular_kinematics({60'000, 60'000}, position, extent, state, {}, passive, + field.at_footprint(position, extent), {}); + CHECK(next.has_value()); + travelled += next->path_um; + position = next->position; + state = next->state; + CHECK(position.x_um > 0 && position.y_um > 0 && position.x_um < 60'000 - extent && + position.y_um < 60'000 - extent); + } + // Five minutes in a 60-300 um/s stream covers several centimetres. + CHECK(travelled > 10'000); +} + +void invalid_configurations() { + auto bad = v0(1); + bad.pitch_um = 0; + CHECK(!CellularFlowField::generate(bad)); + bad = v0(1); + bad.pitch_um = max_cellular_current_pitch_um + 1; + CHECK(!CellularFlowField::generate(bad)); + bad = v0(1); + bad.min_count = 5; + CHECK(!CellularFlowField::generate(bad)); + bad = v0(1); + bad.max_speed_um_per_s = 2'000'000; + CHECK(!CellularFlowField::generate(bad)); + bad = v0(1); + bad.width_um = 3'000; + const auto tiny = CellularFlowField::generate(bad); + CHECK(!tiny && tiny.error() == CellularCurrentError::region_too_small); + auto none = v0(1); + none.min_count = none.max_count = 0; + const auto still = generate(none); + CHECK(still.routes().empty() && still.sample(30'000, 30'000) == CellularFlowSample{}); +} +} // namespace + +int main() { + try { + routes_within_configuration(); + bounded_with_quiet_water_and_still_walls(); + route_centreline_runs_at_route_speed(); + interpolation_is_continuous(); + passive_drift_circulates(); + invalid_configurations(); + deterministic_generation(); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } + std::puts("cellular currents contracts passed"); + return 0; +} diff --git a/tests/cellular_deposit_motion_tests.cpp b/tests/cellular_deposit_motion_tests.cpp new file mode 100644 index 0000000..d0942a4 --- /dev/null +++ b/tests/cellular_deposit_motion_tests.cpp @@ -0,0 +1,225 @@ +#include "evo/biology/cellular_deposit_motion.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::biology; +using evo::accounting::Inventory; +void check(bool value, std::source_location at = std::source_location::current()) { + if (!value) + throw std::runtime_error("cellular deposit motion line " + std::to_string(at.line())); +} +#define CHECK(...) check(static_cast(__VA_ARGS__)) + +constexpr std::int32_t um_per_s = 1'024; +constexpr CellularDepositMotionRules rules{.drift_radius_um = 200, + .max_drift_q10 = 100 * um_per_s, + .drift_decay_ppm = 95'163, + .merged_cap = 8, + .bubble_radius_um = cellular_mote_radius_um}; + +Inventory energy(std::uint64_t amount) { + Inventory value{}; + value.energy.value = amount; + return value; +} + +CellularPatch bubble(std::uint32_t id, std::uint32_t x, std::uint32_t y, + std::uint64_t amount = 10) { + CellularPatch patch{ + {x, y}, 1, energy(amount), id, cellular_mote_radius_um, CellularDepositKind::mote}; + patch.merged = 1; + return patch; +} + +CellularHabitatConfig liquid(std::vector patches, std::uint32_t size = 60'000) { + std::ranges::sort(patches, {}, &CellularPatch::address); + std::uint32_t next{}; + for (const auto& patch : patches) + next = std::max(next, patch.id + 1); + return {100, 1, 9, size, size, std::move(patches), cellular_habitat_liquid_format, next}; +} + +CellularFlowField still(std::uint32_t size = 60'000) { + auto field = CellularFlowField::generate({1, size, size, 250, 0, 0, 3'000, 6'000, 60, 300}); + check(field.has_value()); + return std::move(*field); +} + +CellularFlowField currents() { + auto field = + CellularFlowField::generate({11, 60'000, 60'000, 250, 2, 4, 3'000, 6'000, 60, 300}); + check(field.has_value()); + return std::move(*field); +} + +CellularDepositMotion advect(const CellularHabitatConfig& config, const CellularFlowField& field, + std::span wakes = {}) { + auto moved = advect_cellular_deposits(config, field, wakes, rules); + check(moved.has_value()); + check(CellularHabitat::create(moved->config).has_value()); + return std::move(*moved); +} + +void format_three_round_trip() { + auto moving = bubble(1, 500, 600); + moving.drift_x_q10 = -3'000; + moving.carry_y = 1'000; + moving.merged = 3; + CellularPatch pool{{9'000, 9'000}, 2, energy(500), 2, 500, CellularDepositKind::pool}; + pool.merged = 1; + const auto habitat = CellularHabitat::create(liquid({moving, pool})); + CHECK(habitat); + const auto bytes = (*habitat)->snapshot(); + CHECK(bytes.size() == cellular_habitat_header_bytes + 2 * cellular_liquid_record_bytes + 8); + const auto restored = CellularHabitat::restore(bytes, 100, 1, 9); + CHECK(restored && (*restored)->config() == (*habitat)->config()); + + auto unmerged = liquid({bubble(1, 500, 600)}); + unmerged.patches[0].merged = 0; + CHECK(!CellularHabitat::create(unmerged)); + auto drifting_pool = liquid({pool}); + drifting_pool.patches[0].drift_x_q10 = 1; + CHECK(!CellularHabitat::create(drifting_pool)); + auto old = liquid({bubble(1, 500, 600)}); + old.format = cellular_habitat_deposit_format; + CHECK(!CellularHabitat::create(old)); // Format 2 carries no motion fields. + old.patches[0].merged = 0; + CHECK(CellularHabitat::create(old)); +} + +void still_water_keeps_bubbles() { + const auto config = liquid({bubble(1, 5'000, 5'000), bubble(2, 9'000, 9'000)}); + const auto moved = advect(config, still()); + CHECK(moved.config == config && moved.report == CellularDepositMotionReport{}); +} + +void passing_cells_push_and_drift_decays() { + const auto field = still(); + auto config = liquid({bubble(1, 30'000, 30'000)}); + // A cell passing at 190 um/s right beside the bubble. + const CellularWake wake{{29'950, 29'990}, 20, 190 * um_per_s, 0}; + for (int tick = 0; tick < 10; ++tick) + config = advect(config, field, std::span{&wake, 1}).config; + const auto pushed = config.patches[0]; + CHECK(pushed.address.x_um > 30'000 && pushed.address.y_um == 30'000); + CHECK(pushed.drift_x_q10 > 0 && pushed.drift_x_q10 <= 100 * um_per_s); + // A distant cell does nothing. + const CellularWake far{{20'000, 20'000}, 20, 190 * um_per_s, 0}; + const auto untouched = advect(liquid({bubble(1, 30'000, 30'000)}), field, std::span{&far, 1}); + CHECK(untouched.config.patches[0].address == CellularPatchAddress{30'000, 30'000}); + // Without cells the induced drift decays and the bubble stops. + int ticks{}; + while (config.patches[0].drift_x_q10 != 0) { + config = advect(config, field).config; + CHECK(++ticks < 400); + } + const auto resting = config.patches[0].address; + CHECK(advect(config, field).config.patches[0].address == resting); +} + +void touching_bubbles_merge_up_to_the_cap() { + const auto field = still(); + const auto merged = + advect(liquid({bubble(4, 1'000, 1'000, 10), bubble(9, 1'050, 1'000, 7)}), field); + CHECK(merged.report.merges == 1 && merged.config.patches.size() == 1); + const auto& keeper = merged.config.patches[0]; + CHECK(keeper.id == 4 && keeper.stock.energy.value == 17 && keeper.merged == 2); + CHECK(keeper.address == CellularPatchAddress{1'000, 1'000}); + CHECK(keeper.radius_um == cellular_merged_radius(cellular_mote_radius_um, 2) && + keeper.radius_um == 42); + // Apart, nothing merges. + CHECK(advect(liquid({bubble(1, 1'000, 1'000), bubble(2, 1'061, 1'000)}), field).report.merges == + 0); + // At the cap, bubbles stay separate. + auto full = bubble(1, 1'000, 1'000); + full.merged = 8; + full.radius_um = cellular_merged_radius(cellular_mote_radius_um, 8); + CHECK(advect(liquid({full, bubble(2, 1'010, 1'000)}), field).report.merges == 0); + // Pools never merge or move. + CellularPatch pool{{2'000, 2'000}, 2, energy(500), 3, 500, CellularDepositKind::pool}; + pool.merged = 1; + const auto beside = advect(liquid({pool, bubble(5, 2'010, 2'000)}), field); + CHECK(beside.report.merges == 0 && beside.config.patches.size() == 2); +} + +void shared_addresses_are_separated() { + // Two bubbles at the cap landing on one address stay distinct. + auto a = bubble(1, 3'000, 3'000), b = bubble(2, 3'000, 3'000); + a.merged = b.merged = 8; + const auto separated = advect_cellular_deposits( + {100, 1, 9, 60'000, 60'000, {a, b}, cellular_habitat_liquid_format, 3}, still(), {}, rules); + CHECK(separated && separated->report.nudged == 1); + CHECK(CellularHabitat::create(separated->config)); +} + +void currents_carry_food_without_loss_or_piles() { + const auto field = currents(); + CellularHabitatConfig base{100, 1, 9, 60'000, 60'000, {}, cellular_habitat_deposit_format, 1}; + const auto scattered = scatter_deposits(base, {}, {1'800, 7, energy(70), 99}); + CHECK(scattered); + auto config = *scattered; + config.format = cellular_habitat_liquid_format; + for (auto& patch : config.patches) + patch.merged = 1; + const auto total = [](const CellularHabitatConfig& c) { + std::uint64_t sum{}; + for (const auto& patch : c.patches) + sum += patch.stock.energy.value; + return sum; + }; + const auto opening = total(config); + std::uint32_t merges{}, moved{}; + for (int tick = 0; tick < 2'000; ++tick) { + const auto next = advect(config, field); + merges += next.report.merges; + moved += next.report.moved; + config = next.config; + } + CHECK(total(config) == opening); + CHECK(config.patches.size() + merges == 1'800); + CHECK(moved > 10'000 && merges > 0); + // Nothing collects against the walls: the edges are still water. + const auto at_edge = std::ranges::count_if(config.patches, [](const CellularPatch& p) { + return p.address.x_um == 0 || p.address.y_um == 0 || p.address.x_um == 59'999 || + p.address.y_um == 59'999; + }); + CHECK(at_edge < 20); + // Deterministic. + CHECK(advect(config, field).config == advect(config, field).config); +} + +void refusals() { + auto two = liquid({bubble(1, 1'000, 1'000)}); + two.format = cellular_habitat_deposit_format; + CHECK(!advect_cellular_deposits(two, still(), {}, rules)); + CHECK(!advect_cellular_deposits(liquid({bubble(1, 1'000, 1'000)}, 30'000), still(), {}, rules)); + auto bad = rules; + bad.merged_cap = 0; + CHECK(!advect_cellular_deposits(liquid({bubble(1, 1'000, 1'000)}), still(), {}, bad)); +} +} // namespace + +int main() { + try { + format_three_round_trip(); + still_water_keeps_bubbles(); + passing_cells_push_and_drift_decays(); + touching_bubbles_merge_up_to_the_cap(); + shared_addresses_are_separated(); + currents_carry_food_without_loss_or_piles(); + refusals(); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } + std::puts("cellular deposit motion contracts passed"); + return 0; +}