Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
190a66ad5e | ||
|
|
40dc2b12ad |
+17
-1
@@ -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,21 @@ 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-liquid-step-tests tests/cellular_liquid_step_tests.cpp)
|
||||
target_link_libraries(evo-cellular-liquid-step-tests PRIVATE evo::biology)
|
||||
evo_owned_target(evo-cellular-liquid-step-tests)
|
||||
add_test(NAME cellular-liquid-step-contracts COMMAND evo-cellular-liquid-step-tests)
|
||||
set_tests_properties(cellular-liquid-step-contracts PROPERTIES TIMEOUT 60)
|
||||
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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/biology/cellular_kinematics.hpp"
|
||||
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
// 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<CellularRoutePoint> 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<CellularFlowField, CellularCurrentError>
|
||||
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<const CellularCurrentRoute> routes() const noexcept {
|
||||
return routes_;
|
||||
}
|
||||
[[nodiscard]] std::span<const CellularFlowSample> 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<CellularCurrentRoute> routes_;
|
||||
std::vector<CellularFlowSample> nodes_;
|
||||
std::size_t columns_{}, rows_{};
|
||||
};
|
||||
} // namespace evo::biology
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/biology/cellular_currents.hpp"
|
||||
#include "evo/biology/cellular_habitat.hpp"
|
||||
|
||||
#include <compare>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <span>
|
||||
|
||||
// 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<CellularDepositMotion, CellularHabitatError>
|
||||
advect_cellular_deposits(const CellularHabitatConfig& config, const CellularFlowField& field,
|
||||
std::span<const CellularWake> wakes,
|
||||
const CellularDepositMotionRules& rules);
|
||||
} // namespace evo::biology
|
||||
@@ -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 {
|
||||
@@ -71,6 +84,12 @@ struct CellularPatchPerception {
|
||||
// Whether a cell's square footprint touches a patch (format 1 square) or a deposit's disc.
|
||||
[[nodiscard]] bool cellular_patch_contact(CellularPosition position, std::uint32_t extent_um,
|
||||
const CellularPatch& patch) noexcept;
|
||||
// Whether a footprint moving in a straight line from `from` to `to` touches the deposit at any
|
||||
// point, sampled no further apart than half the smaller of the deposit's radius and the
|
||||
// footprint, so a fast cell cannot pass over food.
|
||||
[[nodiscard]] bool cellular_path_contact(CellularPosition from, CellularPosition to,
|
||||
std::uint32_t extent_um,
|
||||
const CellularPatch& patch) noexcept;
|
||||
enum class CellularHabitatError : std::uint8_t {
|
||||
invalid_config,
|
||||
invalid_patch,
|
||||
|
||||
@@ -39,6 +39,9 @@ struct CellularLifeStepInput {
|
||||
MetabolicBudget budget;
|
||||
std::uint32_t membrane_um{}; // Genome membrane thickness; contests engulfment (rules 3).
|
||||
std::uint64_t source{}; // Provenance for a detritus patch this life creates (rules 3).
|
||||
// Rules 12: liquid motion, required exactly when the habitat is format 3. The movement
|
||||
// intent becomes the propulsion command.
|
||||
std::optional<CellularLiquidInput> liquid{};
|
||||
auto operator<=>(const CellularLifeStepInput&) const = default;
|
||||
};
|
||||
enum class CellularEngulfStatus : std::uint8_t {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "evo/biology/cellular_habitat.hpp"
|
||||
#include "evo/biology/cellular_kinematics.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
@@ -48,12 +49,31 @@ struct CellularStepCandidate {
|
||||
CellularMovementStatus movement_status{CellularMovementStatus::not_requested};
|
||||
CellularIntakeStatus intake_status{CellularIntakeStatus::not_requested};
|
||||
std::optional<CellularPatchUptakeProposal> intake;
|
||||
// Rules 12 (liquid motion): the motion state after the tick and the path travelled.
|
||||
CellularMotionState motion{};
|
||||
std::uint64_t path_um{};
|
||||
auto operator<=>(const CellularStepCandidate&) const = default;
|
||||
};
|
||||
// Rules 12: liquid-relative motion inputs for one life (Cellular_Region_Movement_Plan.md).
|
||||
struct CellularLiquidInput {
|
||||
CellularMotionState motion;
|
||||
CellularHandling handling;
|
||||
CellularFlowSample flow; // Sampled at the footprint centre by the caller.
|
||||
bool brake{};
|
||||
auto operator<=>(const CellularLiquidInput&) const = default;
|
||||
};
|
||||
|
||||
[[nodiscard]] std::expected<CellularStepCandidate, CellularStepError>
|
||||
propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position,
|
||||
std::uint32_t extent_um, CellularStepIntent intent,
|
||||
accounting::Inventory reserve, accounting::Inventory heat,
|
||||
const MetabolicBudget& budget, const CellularHabitat& habitat) noexcept;
|
||||
// Rules 12: maintenance first, then one kinematic tick funded from what is left; thrust it
|
||||
// cannot fund is not applied and the cell coasts with the flow. No targeted intake: liquid
|
||||
// regions feed by contact in the region step.
|
||||
[[nodiscard]] std::expected<CellularStepCandidate, CellularStepError>
|
||||
propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position,
|
||||
std::uint32_t extent_um, CellularIntent movement,
|
||||
const CellularLiquidInput& liquid, accounting::Inventory reserve,
|
||||
accounting::Inventory heat, const MetabolicBudget& budget) noexcept;
|
||||
} // namespace evo::biology
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
#include "evo/biology/cellular_currents.hpp"
|
||||
|
||||
#include "evo/core/random.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
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<std::int64_t>(random.next() % static_cast<std::uint64_t>(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<CellularCurrentRoute, CellularCurrentError>
|
||||
generate_route(Random& random, const CellularCurrentConfig& c) {
|
||||
CellularCurrentRoute route;
|
||||
route.width_um =
|
||||
static_cast<std::uint32_t>(uniform(random, c.min_route_width_um, c.max_route_width_um));
|
||||
route.speed_um_per_s =
|
||||
static_cast<std::uint32_t>(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<std::uint16_t>(random.next());
|
||||
const auto phase_3 = static_cast<std::uint16_t>(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<std::uint16_t>(k * step);
|
||||
const auto radius =
|
||||
per_mille +
|
||||
wobble_2 * cellular_cos_q14(static_cast<std::uint16_t>(2 * theta + phase_2)) / trig +
|
||||
wobble_3 * cellular_cos_q14(static_cast<std::uint16_t>(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<std::int64_t>::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<std::int64_t>((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<std::int64_t>(
|
||||
integer_sqrt(static_cast<std::uint64_t>(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<const CellularCurrentRoute> 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<std::int64_t>(integer_sqrt(static_cast<std::uint64_t>(vx * vx + vy * vy)));
|
||||
if (speed > cap && speed > 0) {
|
||||
vx = vx * cap / speed;
|
||||
vy = vy * cap / speed;
|
||||
}
|
||||
return {static_cast<std::int32_t>(vx), static_cast<std::int32_t>(vy)};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::expected<CellularFlowField, CellularCurrentError>
|
||||
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<std::int64_t>(column * config.pitch_um),
|
||||
static_cast<std::int64_t>(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<std::int64_t>(x_um, 0, config_.width_um);
|
||||
const auto y = std::clamp<std::int64_t>(y_um, 0, config_.height_um);
|
||||
const auto column = static_cast<std::size_t>(x / pitch);
|
||||
const auto row = static_cast<std::size_t>(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<std::int32_t>(blend(n00.x_q10, n10.x_q10, n01.x_q10, n11.x_q10)),
|
||||
static_cast<std::int32_t>(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<std::int64_t>(position.x_um + extent_um / 2),
|
||||
static_cast<std::int64_t>(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<std::uint32_t>(node.x_q10));
|
||||
mix(static_cast<std::uint32_t>(node.y_q10));
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
} // namespace evo::biology
|
||||
@@ -0,0 +1,279 @@
|
||||
#include "evo/biology/cellular_deposit_motion.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<std::int64_t>(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<std::uint64_t>::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<std::pair<std::int64_t, std::size_t>>
|
||||
bucketed(const Buckets& buckets, std::size_t count, const auto& position_of) {
|
||||
std::vector<std::pair<std::int64_t, std::size_t>> 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<std::pair<std::int64_t, std::size_t>>& entries, std::int64_t x,
|
||||
std::int64_t y, std::vector<std::size_t>& 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::uint32_t>(std::min<std::uint64_t>(
|
||||
max_cellular_deposit_radius_um, std::uint64_t{bubble_radius_um} * scale / 1'000));
|
||||
}
|
||||
|
||||
std::expected<CellularDepositMotion, CellularHabitatError>
|
||||
advect_cellular_deposits(const CellularHabitatConfig& config, const CellularFlowField& field,
|
||||
std::span<const CellularWake> 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<std::int64_t>(radius, 1),
|
||||
width / std::max<std::int64_t>(radius, 1) + 1};
|
||||
const auto wake_centre = [&wakes](std::size_t index) {
|
||||
const auto& wake = wakes[index];
|
||||
return std::pair{static_cast<std::int64_t>(wake.position.x_um + wake.extent_um / 2),
|
||||
static_cast<std::int64_t>(wake.position.y_um + wake.extent_um / 2)};
|
||||
};
|
||||
const auto wake_index = radius > 0 ? bucketed(wake_buckets, wakes.size(), wake_centre)
|
||||
: std::vector<std::pair<std::int64_t, std::size_t>>{};
|
||||
std::vector<std::size_t> 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<std::int64_t>(
|
||||
integer_sqrt(static_cast<std::uint64_t>(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<std::int64_t>(
|
||||
integer_sqrt(static_cast<std::uint64_t>(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<std::int64_t>(next_x, 0, width - 1);
|
||||
carry_x = 0;
|
||||
drift_x = 0;
|
||||
}
|
||||
if (next_y < 0 || next_y > height - 1) {
|
||||
next_y = std::clamp<std::int64_t>(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<std::uint32_t>(next_x), static_cast<std::uint32_t>(next_y)};
|
||||
patch.carry_x = static_cast<std::uint32_t>(carry_x);
|
||||
patch.carry_y = static_cast<std::uint32_t>(carry_y);
|
||||
patch.drift_x_q10 = static_cast<std::int32_t>(decay(drift_x, rules.drift_decay_ppm));
|
||||
patch.drift_y_q10 = static_cast<std::int32_t>(decay(drift_y, rules.drift_decay_ppm));
|
||||
}
|
||||
|
||||
// Merge touching bubbles in ascending id: the lower id absorbs the higher one.
|
||||
std::vector<std::size_t> 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::int64_t>(
|
||||
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<std::int64_t>(patch.address.x_um),
|
||||
static_cast<std::int64_t>(patch.address.y_um)};
|
||||
});
|
||||
std::vector<bool> 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<std::int32_t>(
|
||||
(keeper.drift_x_q10 * mass + taken.drift_x_q10 * more) / (mass + more));
|
||||
keeper.drift_y_q10 = static_cast<std::int32_t>(
|
||||
(keeper.drift_y_q10 * mass + taken.drift_y_q10 * more) / (mass + more));
|
||||
keeper.merged = static_cast<std::uint16_t>(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<bool> removed(patches.size(), false);
|
||||
for (std::size_t order = 0; order < motes.size(); ++order)
|
||||
if (absorbed[order])
|
||||
removed[motes[order]] = true;
|
||||
std::vector<CellularPatch> 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
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "evo/biology/cellular_habitat.hpp"
|
||||
|
||||
#include "evo/biology/cellular_kinematics.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
@@ -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<std::uint32_t> 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<std::uint8_t> 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<std::uint8_t> CellularHabitat::snapshot() const {
|
||||
out.put(static_cast<std::uint8_t>(patch.kind), 1);
|
||||
out.put(0, 1);
|
||||
}
|
||||
if (liquid) {
|
||||
out.put(static_cast<std::uint32_t>(patch.drift_x_q10), 4);
|
||||
out.put(static_cast<std::uint32_t>(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<const std::uint8_t> 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<std::uint32_t>(format);
|
||||
config.world = in.get();
|
||||
@@ -295,8 +325,10 @@ CellularHabitat::restore(std::span<const std::uint8_t> 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<std::uint32_t>::max() ||
|
||||
bytes.size() != cellular_habitat_header_bytes + record * count + 8)
|
||||
return std::unexpected{CellularHabitatError::format};
|
||||
@@ -314,6 +346,15 @@ CellularHabitat::restore(std::span<const std::uint8_t> bytes, std::uint64_t worl
|
||||
return std::unexpected{CellularHabitatError::format};
|
||||
patch.kind = static_cast<CellularDepositKind>(kind);
|
||||
}
|
||||
if (liquid) {
|
||||
patch.drift_x_q10 = static_cast<std::int32_t>(static_cast<std::uint32_t>(in.get(4)));
|
||||
patch.drift_y_q10 = static_cast<std::int32_t>(static_cast<std::uint32_t>(in.get(4)));
|
||||
patch.carry_x = static_cast<std::uint32_t>(in.get(4));
|
||||
patch.carry_y = static_cast<std::uint32_t>(in.get(4));
|
||||
patch.merged = static_cast<std::uint16_t>(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);
|
||||
@@ -409,6 +450,28 @@ scatter_deposits(CellularHabitatConfig base, std::span<const CellularPatch> pool
|
||||
return base;
|
||||
}
|
||||
|
||||
bool cellular_path_contact(CellularPosition from, CellularPosition to, std::uint32_t extent_um,
|
||||
const CellularPatch& patch) noexcept {
|
||||
if (from == to)
|
||||
return cellular_patch_contact(to, extent_um, patch);
|
||||
const auto dx = static_cast<std::int64_t>(to.x_um) - static_cast<std::int64_t>(from.x_um);
|
||||
const auto dy = static_cast<std::int64_t>(to.y_um) - static_cast<std::int64_t>(from.y_um);
|
||||
const auto reach = std::max<std::int64_t>(
|
||||
1, std::min<std::int64_t>(patch.radius_um == 0 ? cellular_patch_pitch_um : patch.radius_um,
|
||||
extent_um) /
|
||||
2);
|
||||
const auto span = std::max(dx < 0 ? -dx : dx, dy < 0 ? -dy : dy);
|
||||
const auto steps = std::clamp<std::int64_t>((span + reach - 1) / reach, 1, 256);
|
||||
for (std::int64_t step = 0; step <= steps; ++step) {
|
||||
const CellularPosition at{
|
||||
static_cast<std::uint64_t>(static_cast<std::int64_t>(from.x_um) + dx * step / steps),
|
||||
static_cast<std::uint64_t>(static_cast<std::int64_t>(from.y_um) + dy * step / steps)};
|
||||
if (cellular_patch_contact(at, extent_um, patch))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool cellular_patch_contact(CellularPosition position, std::uint32_t extent_um,
|
||||
const CellularPatch& patch) noexcept {
|
||||
if (patch.kind == CellularDepositKind::patch)
|
||||
|
||||
@@ -66,11 +66,17 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
if (lives.size() > max_cellular_tick_lives)
|
||||
return std::unexpected{CellularRegionStepError::too_many_lives};
|
||||
|
||||
const bool liquid = habitat.config().format == cellular_habitat_liquid_format;
|
||||
const auto deposit_limit = liquid ? max_cellular_liquid_deposits : max_cellular_patches;
|
||||
std::vector<const CellularLifeStepInput*> ordered;
|
||||
ordered.reserve(lives.size());
|
||||
for (const auto& life : lives) {
|
||||
if (life.life_id == 0)
|
||||
return std::unexpected{CellularRegionStepError::invalid_life_id};
|
||||
// Rules 12: liquid motion in a format-3 habitat, for every life, and nowhere else.
|
||||
if (life.liquid.has_value() != liquid ||
|
||||
(liquid && (life.intent.intake_target || !rules.contact_feeding)))
|
||||
return std::unexpected{CellularRegionStepError::invalid_intent};
|
||||
if (life.intent.frozen &&
|
||||
(life.intent.movement != CellularIntent{} || life.intent.intake_target ||
|
||||
life.intent.engulf || life.intent.bud))
|
||||
@@ -111,6 +117,8 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
frozen.position = life->position;
|
||||
frozen.reserve_after = life->reserve;
|
||||
frozen.heat_after = life->heat;
|
||||
if (life->liquid)
|
||||
frozen.motion = life->liquid->motion; // Anchored while frozen.
|
||||
candidate.lives.push_back({life->life_id, frozen});
|
||||
survivors.push_back(life);
|
||||
continue;
|
||||
@@ -121,8 +129,12 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
intent.intake_target.reset();
|
||||
intent.engulf = false;
|
||||
const auto step =
|
||||
propose_cellular_step(begin_tick, area, life->position, life->extent_um, intent,
|
||||
life->reserve, life->heat, life->budget, habitat);
|
||||
life->liquid
|
||||
? propose_liquid_cellular_step(begin_tick, area, life->position, life->extent_um,
|
||||
intent.movement, *life->liquid, life->reserve,
|
||||
life->heat, life->budget)
|
||||
: propose_cellular_step(begin_tick, area, life->position, life->extent_um, intent,
|
||||
life->reserve, life->heat, life->budget, habitat);
|
||||
if (!step && step.error() == CellularStepError::insufficient_maintenance) {
|
||||
CellularCorpseCandidate corpse{life->life_id, life->position, life->reserve};
|
||||
for (std::size_t channel = 0; channel < corpse.inventory.matter.size(); ++channel) {
|
||||
@@ -187,7 +199,11 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
std::optional<std::size_t> first;
|
||||
for (std::size_t index = 0; index < patch_stock.size(); ++index) {
|
||||
const auto& deposit = habitat.patches()[index];
|
||||
if (!cellular_patch_contact(result.position, life->extent_um, deposit))
|
||||
// Liquid motion sweeps its whole path, so a fast cell cannot skip food.
|
||||
if (life->liquid
|
||||
? !cellular_path_contact(life->position, result.position, life->extent_um,
|
||||
deposit)
|
||||
: !cellular_patch_contact(result.position, life->extent_um, deposit))
|
||||
continue;
|
||||
bool took = false;
|
||||
for (std::size_t channel = 0; channel < limit.size(); ++channel) {
|
||||
@@ -337,8 +353,7 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
continue;
|
||||
accounting::Inventory single{};
|
||||
channel_of(single, channel) = amount;
|
||||
if (habitat.patches().size() + candidate.new_patches.size() >=
|
||||
max_cellular_patches) {
|
||||
if (habitat.patches().size() + candidate.new_patches.size() >= deposit_limit) {
|
||||
overflow.push_back({deposit.life_id, deposit.source, deposit.position,
|
||||
single, deposit.extent_um});
|
||||
continue;
|
||||
@@ -356,9 +371,12 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
address.x_um = address.x_um + 1 < area.width_um ? address.x_um + 1 : 0;
|
||||
const auto at = std::ranges::lower_bound(candidate.new_patches, address, {},
|
||||
&CellularPatch::address);
|
||||
candidate.new_patches.insert(at, CellularPatch{address, deposit.source, single,
|
||||
0, cellular_mote_radius_um,
|
||||
CellularDepositKind::mote});
|
||||
CellularPatch bubble{
|
||||
address, deposit.source, single,
|
||||
0, cellular_mote_radius_um, CellularDepositKind::mote};
|
||||
if (liquid)
|
||||
bubble.merged = 1;
|
||||
candidate.new_patches.insert(at, bubble);
|
||||
}
|
||||
}
|
||||
deposits = std::move(overflow); // A full habitat: the nearest deposit takes it.
|
||||
@@ -377,7 +395,7 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
|
||||
return std::unexpected{CellularRegionStepError::overflow};
|
||||
continue;
|
||||
}
|
||||
if (habitat.patches().size() + candidate.new_patches.size() < max_cellular_patches) {
|
||||
if (habitat.patches().size() + candidate.new_patches.size() < deposit_limit) {
|
||||
candidate.new_patches.insert(made, {address, deposit.source, deposit.inventory});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -96,4 +96,61 @@ propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosit
|
||||
candidate.intake = *intake;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
std::expected<CellularStepCandidate, CellularStepError>
|
||||
propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position,
|
||||
std::uint32_t extent_um, CellularIntent movement,
|
||||
const CellularLiquidInput& liquid, accounting::Inventory reserve,
|
||||
accounting::Inventory heat, const MetabolicBudget& budget) noexcept {
|
||||
if (begin_tick == std::numeric_limits<std::uint64_t>::max())
|
||||
return std::unexpected{CellularStepError::invalid_tick};
|
||||
if (budget.rate_microseconds != rate_period_microseconds)
|
||||
return std::unexpected{CellularStepError::unsupported_rate_period};
|
||||
const auto maintenance = accounting::per_tick(
|
||||
budget.maintenance.value, cellular_motion_tick_microseconds, accounting::Rounding::up);
|
||||
if (!maintenance)
|
||||
return std::unexpected{CellularStepError::overflow};
|
||||
if (reserve.energy.value < *maintenance)
|
||||
return std::unexpected{CellularStepError::insufficient_maintenance};
|
||||
if (!credit_heat(heat, *maintenance))
|
||||
return std::unexpected{CellularStepError::overflow};
|
||||
reserve.energy.value -= *maintenance;
|
||||
|
||||
const auto motion =
|
||||
step_cellular_kinematics(area, position, extent_um, liquid.motion, {movement, liquid.brake},
|
||||
liquid.handling, liquid.flow, reserve.energy);
|
||||
if (!motion)
|
||||
return std::unexpected{CellularStepError::motion};
|
||||
if (!credit_heat(heat, motion->cost.value))
|
||||
return std::unexpected{CellularStepError::overflow};
|
||||
reserve.energy.value -= motion->cost.value;
|
||||
|
||||
CellularStepCandidate candidate{};
|
||||
candidate.begin_tick = begin_tick;
|
||||
candidate.end_tick = begin_tick + 1;
|
||||
candidate.position = motion->position;
|
||||
candidate.reserve_after = reserve;
|
||||
candidate.heat_after = heat;
|
||||
candidate.maintenance_cost = {*maintenance};
|
||||
candidate.movement_cost = motion->cost;
|
||||
candidate.motion = motion->state;
|
||||
candidate.path_um = motion->path_um;
|
||||
switch (motion->thrust) {
|
||||
case CellularThrustStatus::idle:
|
||||
candidate.movement_status = CellularMovementStatus::not_requested;
|
||||
break;
|
||||
case CellularThrustStatus::unfunded:
|
||||
candidate.movement_status = CellularMovementStatus::insufficient_reserve;
|
||||
break;
|
||||
case CellularThrustStatus::applied:
|
||||
// Blocked only when an edge stopped it; a sub-micrometre start is still moving.
|
||||
candidate.movement_status = motion->position == position &&
|
||||
motion->state.velocity_x_q10 == 0 &&
|
||||
motion->state.velocity_y_q10 == 0
|
||||
? CellularMovementStatus::blocked
|
||||
: CellularMovementStatus::moved;
|
||||
break;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
} // namespace evo::biology
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
#include "evo/biology/cellular_currents.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
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<bool>(__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<double>(sample.x_q10), y = static_cast<double>(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<unsigned long long>(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<std::uint64_t>(start.x_um - extent / 2),
|
||||
static_cast<std::uint64_t>(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;
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
#include "evo/biology/cellular_deposit_motion.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<bool>(__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<CellularPatch> 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<const CellularWake> 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;
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
#include "evo/biology/cellular_region_step.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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 liquid step line " + std::to_string(at.line()));
|
||||
}
|
||||
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
|
||||
|
||||
constexpr CellularArea area{60'000, 60'000};
|
||||
constexpr std::int32_t um_per_s = 1'024;
|
||||
constexpr CellularRegionRules rules{.engulf_and_detritus = true, .contact_feeding = true};
|
||||
|
||||
MetabolicBudget budget() {
|
||||
MetabolicBudget value{};
|
||||
value.rate_microseconds = 1'000'000;
|
||||
value.maintenance = {20}; // One picojoule per tick.
|
||||
value.intake_limit = {{1'000'000}, {{{1'000'000}, {1'000'000}, {1'000'000}, {1'000'000}}}};
|
||||
value.phenotype.total_mass = 1'000;
|
||||
return value;
|
||||
}
|
||||
|
||||
CellularHandling handling() {
|
||||
return {.thrust_q10 = 20'480,
|
||||
.reverse_thrust_q10 = 20'480,
|
||||
.forward_drag_ppm = 95'163,
|
||||
.lateral_drag_ppm = 95'163,
|
||||
.turn = 3'277,
|
||||
.thrust_cost = {10},
|
||||
.reverse_cost = {10}};
|
||||
}
|
||||
|
||||
CellularPatch bubble(std::uint32_t id, std::uint32_t x, std::uint32_t y) {
|
||||
CellularPatch patch{
|
||||
{x, y}, 1, {{50}, {}}, id, cellular_mote_radius_um, CellularDepositKind::mote};
|
||||
patch.merged = 1;
|
||||
return patch;
|
||||
}
|
||||
|
||||
std::unique_ptr<CellularHabitat> liquid_habitat(std::vector<CellularPatch> patches = {}) {
|
||||
std::uint32_t next = 1;
|
||||
for (const auto& patch : patches)
|
||||
next = std::max(next, patch.id + 1);
|
||||
auto made = CellularHabitat::create(
|
||||
{100, 1, 9, 60'000, 60'000, std::move(patches), cellular_habitat_liquid_format, next});
|
||||
check(made.has_value());
|
||||
return std::move(*made);
|
||||
}
|
||||
|
||||
CellularLifeStepInput life(std::uint64_t id, CellularPosition position, CellularIntent movement,
|
||||
Inventory reserve = {{1'000}, {}},
|
||||
CellularLiquidInput liquid = {{}, handling(), {}, false}) {
|
||||
CellularLifeStepInput input{};
|
||||
input.life_id = id;
|
||||
input.position = position;
|
||||
input.extent_um = 20;
|
||||
input.intent.movement = movement;
|
||||
input.body = {{0}, {{{5}, {5}, {5}, {5}}}};
|
||||
input.reserve = reserve;
|
||||
input.budget = budget();
|
||||
input.membrane_um = 1;
|
||||
input.source = 7;
|
||||
input.liquid = liquid;
|
||||
return input;
|
||||
}
|
||||
|
||||
void propulsion_moves_and_pays() {
|
||||
const auto map = liquid_habitat();
|
||||
const std::array lives{life(1, {30'000, 30'000}, {1'000, 0})};
|
||||
const auto tick = propose_cellular_region_step(4, area, lives, *map, rules);
|
||||
CHECK(tick && tick->lives.size() == 1);
|
||||
const auto& step = tick->lives[0].candidate;
|
||||
CHECK(step.movement_status == CellularMovementStatus::moved);
|
||||
CHECK(step.motion.velocity_x_q10 > 0 && step.position.x_um == 30'000);
|
||||
// First tick: 20 um/s * 50 ms leaves sub-micrometre carry; maintenance 1 + thrust 10.
|
||||
CHECK(step.motion.remainder_x > 0);
|
||||
CHECK(step.maintenance_cost.value == 1 && step.movement_cost.value == 10);
|
||||
CHECK(step.reserve_after.energy.value == 989 && step.heat_after.energy.value == 11);
|
||||
}
|
||||
|
||||
void unfunded_thrust_coasts_with_the_flow() {
|
||||
const auto map = liquid_habitat();
|
||||
// Enough for maintenance, not for thrust; a 100 um/s current still carries the cell.
|
||||
const auto broke = life(1, {30'000, 30'000}, {1'000, 0}, {{5}, {}},
|
||||
{{}, handling(), {100 * um_per_s, 0}, false});
|
||||
const std::array lives{broke};
|
||||
const auto tick = propose_cellular_region_step(4, area, lives, *map, rules);
|
||||
CHECK(tick && tick->lives.size() == 1);
|
||||
const auto& step = tick->lives[0].candidate;
|
||||
CHECK(step.movement_status == CellularMovementStatus::insufficient_reserve);
|
||||
CHECK(step.movement_cost.value == 0 && step.reserve_after.energy.value == 4);
|
||||
CHECK(step.position.x_um == 30'005);
|
||||
}
|
||||
|
||||
void fast_cells_feed_along_their_path() {
|
||||
// A bubble lies between where a very fast cell starts and where it ends this tick.
|
||||
const auto map = liquid_habitat({bubble(1, 30'040, 30'010)});
|
||||
const auto moving =
|
||||
life(1, {30'000, 30'000}, {}, {{1'000}, {}},
|
||||
{{.velocity_x_q10 = 2'000 * um_per_s}, handling(), {1'000 * um_per_s, 0}, false});
|
||||
const std::array lives{moving};
|
||||
const auto tick = propose_cellular_region_step(4, area, lives, *map, rules);
|
||||
CHECK(tick && tick->lives.size() == 1);
|
||||
const auto& step = tick->lives[0].candidate;
|
||||
// It ends well past the bubble's reach, yet it fed on the way.
|
||||
CHECK(step.position.x_um > 30'040 + cellular_mote_radius_um + 20);
|
||||
CHECK(step.intake_status == CellularIntakeStatus::acquired);
|
||||
CHECK(tick->patches.size() == 1 && tick->patches[0].stock == Inventory{});
|
||||
}
|
||||
|
||||
void starved_cells_leave_merged_bubbles() {
|
||||
const auto map = liquid_habitat();
|
||||
auto starving = life(1, {30'000, 30'000}, {}, {{0}, {}});
|
||||
starving.body = {{0}, {{{3}, {0}, {2}, {0}}}};
|
||||
const std::array lives{starving};
|
||||
const auto tick = propose_cellular_region_step(4, area, lives, *map, rules);
|
||||
CHECK(tick && tick->lives.empty() && tick->starved.size() == 1);
|
||||
CHECK(tick->new_patches.size() == 2);
|
||||
for (const auto& patch : tick->new_patches)
|
||||
CHECK(patch.kind == CellularDepositKind::mote && patch.merged == 1);
|
||||
}
|
||||
|
||||
void frozen_cells_keep_their_motion() {
|
||||
const auto map = liquid_habitat();
|
||||
const CellularMotionState held{.velocity_x_q10 = 50 * um_per_s, .heading = 99};
|
||||
auto frozen = life(1, {30'000, 30'000}, {}, {{1'000}, {}},
|
||||
{held, handling(), {200 * um_per_s, 0}, false});
|
||||
frozen.intent.frozen = true;
|
||||
const std::array lives{frozen};
|
||||
const auto tick = propose_cellular_region_step(4, area, lives, *map, rules);
|
||||
CHECK(tick && tick->lives.size() == 1);
|
||||
const auto& step = tick->lives[0].candidate;
|
||||
CHECK(step.position == CellularPosition{30'000, 30'000});
|
||||
CHECK(step.motion == held && step.reserve_after.energy.value == 1'000);
|
||||
}
|
||||
|
||||
void liquid_and_format_must_match() {
|
||||
const std::array liquid_life{life(1, {1'000, 1'000}, {})};
|
||||
auto old = CellularHabitat::create(
|
||||
{100, 1, 9, 60'000, 60'000, {}, cellular_habitat_deposit_format, 1});
|
||||
CHECK(old);
|
||||
const auto mismatched = propose_cellular_region_step(4, area, liquid_life, **old, rules);
|
||||
CHECK(!mismatched && mismatched.error() == CellularRegionStepError::invalid_intent);
|
||||
auto plain = life(1, {1'000, 1'000}, {});
|
||||
plain.liquid.reset();
|
||||
const std::array plain_life{plain};
|
||||
const auto missing =
|
||||
propose_cellular_region_step(4, area, plain_life, *liquid_habitat(), rules);
|
||||
CHECK(!missing && missing.error() == CellularRegionStepError::invalid_intent);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
try {
|
||||
propulsion_moves_and_pays();
|
||||
unfunded_thrust_coasts_with_the_flow();
|
||||
fast_cells_feed_along_their_path();
|
||||
starved_cells_leave_merged_bubbles();
|
||||
frozen_cells_keep_their_motion();
|
||||
liquid_and_format_must_match();
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "%s\n", error.what());
|
||||
return 1;
|
||||
}
|
||||
std::puts("cellular liquid step contracts passed");
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user