#include "evo/biology/cellular_region_step.hpp" #include "evo/accounting/rates.hpp" #include #include #include namespace evo::biology { namespace { constexpr auto u64_max = std::numeric_limits::max(); bool add(std::uint64_t& to, std::uint64_t amount) noexcept { if (amount > u64_max - to) return false; to += amount; return true; } bool add(accounting::Inventory& to, const accounting::Inventory& from) noexcept { if (!add(to.energy.value, from.energy.value)) return false; for (std::size_t channel = 0; channel < to.matter.size(); ++channel) if (!add(to.matter[channel].value, from.matter[channel].value)) return false; return true; } // a * ka >= b * kb without overflow: compares the exact 128-bit products. bool product_at_least(std::uint64_t a, std::uint64_t ka, std::uint64_t b, std::uint64_t kb) { const auto wide = [](std::uint64_t x, std::uint64_t y) { const std::uint64_t x0 = x & 0xFFFFFFFFU, x1 = x >> 32U; const std::uint64_t y0 = y & 0xFFFFFFFFU, y1 = y >> 32U; const std::uint64_t p00 = x0 * y0, p01 = x0 * y1, p10 = x1 * y0, p11 = x1 * y1; const std::uint64_t middle = (p00 >> 32U) + (p01 & 0xFFFFFFFFU) + (p10 & 0xFFFFFFFFU); const std::uint64_t high = p11 + (p01 >> 32U) + (p10 >> 32U) + (middle >> 32U); const std::uint64_t low = (middle << 32U) | (p00 & 0xFFFFFFFFU); return std::pair{high, low}; }; return wide(a, ka) >= wide(b, kb); } CellularPatchAddress cell_of(CellularPosition position) noexcept { return {static_cast(position.x_um / cellular_patch_pitch_um * cellular_patch_pitch_um), static_cast(position.y_um / cellular_patch_pitch_um * cellular_patch_pitch_um)}; } struct Deposit { std::uint64_t life_id{}, source{}; CellularPosition position; accounting::Inventory inventory; }; } // namespace std::expected propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, std::span lives, const CellularHabitat& habitat, CellularRegionRules rules) { if (begin_tick == std::numeric_limits::max()) return std::unexpected{CellularRegionStepError::invalid_tick}; if (lives.size() > max_cellular_tick_lives) return std::unexpected{CellularRegionStepError::too_many_lives}; std::vector ordered; ordered.reserve(lives.size()); for (const auto& life : lives) { if (life.life_id == 0) return std::unexpected{CellularRegionStepError::invalid_life_id}; if (life.intent.frozen && (life.intent.movement != CellularIntent{} || life.intent.intake_target || life.intent.engulf || life.intent.bud)) return std::unexpected{CellularRegionStepError::invalid_intent}; if (rules.engulf_and_detritus && (life.membrane_um == 0 || life.source == 0 || (life.intent.engulf && life.intent.intake_target))) return std::unexpected{CellularRegionStepError::invalid_intent}; ordered.push_back(&life); } std::ranges::sort(ordered, {}, [](const auto* life) { return life->life_id; }); for (std::size_t i = 1; i < ordered.size(); ++i) if (ordered[i - 1]->life_id == ordered[i]->life_id) return std::unexpected{CellularRegionStepError::duplicate_life_id}; CellularRegionStepCandidate candidate{begin_tick, begin_tick + 1, {}, {}, {}, {}, {}}; candidate.lives.reserve(ordered.size()); candidate.starved.reserve(ordered.size()); std::vector patch_stock; patch_stock.reserve(habitat.patches().size()); for (const auto& patch : habitat.patches()) patch_stock.push_back(patch.stock); // Inputs of the lives still in candidate.lives, in the same order. std::vector survivors; survivors.reserve(ordered.size()); std::vector deposits; for (const auto* life : ordered) { if (life->body.energy.value != 0) return std::unexpected{CellularRegionStepError::invalid_body}; if (std::ranges::any_of(life->heat.matter, [](const auto& channel) { return channel.value != 0; })) return std::unexpected{CellularRegionStepError::invalid_heat}; if (life->intent.frozen) { // ADR-0128: a frozen cell is unchanged and pays nothing; it can still be prey. CellularStepCandidate frozen{}; frozen.begin_tick = begin_tick; frozen.end_tick = begin_tick + 1; frozen.position = life->position; frozen.reserve_after = life->reserve; frozen.heat_after = life->heat; candidate.lives.push_back({life->life_id, frozen}); survivors.push_back(life); continue; } auto intent = life->intent; const auto target = intent.intake_target; 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); 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) { const auto body_matter = life->body.matter[channel].value; const auto reserve_matter = life->reserve.matter[channel].value; if (reserve_matter > std::numeric_limits::max() - body_matter) return std::unexpected{CellularRegionStepError::overflow}; corpse.inventory.matter[channel].value = body_matter + reserve_matter; } if (life->heat.energy.value > std::numeric_limits::max() - candidate.heat_released.value) return std::unexpected{CellularRegionStepError::overflow}; candidate.heat_released.value += life->heat.energy.value; if (rules.engulf_and_detritus) { deposits.push_back({life->life_id, life->source, life->position, corpse.inventory}); corpse.inventory = {}; } candidate.starved.push_back(corpse); continue; } if (!step) return std::unexpected{CellularRegionStepError::life_step}; auto result = *step; if (target) { const auto index = habitat.find(*target); if (!index) { result.intake_status = CellularIntakeStatus::missing; } else { const auto intake = habitat.propose_uptake_from_stock( *target, result.position, life->extent_um, patch_stock[*index], result.reserve_after, life->budget); if (!intake) { if (intake.error() == CellularHabitatError::not_in_contact) { result.intake_status = CellularIntakeStatus::out_of_contact; } else { return std::unexpected{CellularRegionStepError::habitat}; } } else { patch_stock[*index] = intake->transfer.patch_after; result.reserve_after = intake->transfer.reserve_after; result.intake_status = CellularIntakeStatus::acquired; result.intake = *intake; } } } CellularLifeStepResult life_result{life->life_id, result}; if (life->intent.engulf) life_result.engulf = rules.engulf_and_detritus ? CellularEngulfStatus::no_eligible_prey : CellularEngulfStatus::unsupported; candidate.lives.push_back(life_result); survivors.push_back(life); } if (rules.engulf_and_detritus) { // Engulf phase (ADR-0124): ascending predator id; each takes at most the lowest-id // eligible survivor in contact. A taken life neither acts nor is taken again. std::vector taken(candidate.lives.size(), false); for (std::size_t p = 0; p < candidate.lives.size(); ++p) { if (taken[p] || !survivors[p]->intent.engulf) continue; auto& predator = candidate.lives[p]; const auto* hunter = survivors[p]; // Why nothing was taken, for the owner: no contact, too large, or membrane. bool membrane_blocked = false; predator.engulf = CellularEngulfStatus::no_contact; for (std::size_t q = 0; q < candidate.lives.size(); ++q) { if (q == p || taken[q]) continue; const auto* prey = survivors[q]; const auto& prey_step = candidate.lives[q].candidate; if (!cellular_footprints_contact(predator.candidate.position, hunter->extent_um, prey_step.position, prey->extent_um)) continue; if (!product_at_least(hunter->budget.phenotype.total_mass, 1'000, prey->budget.phenotype.total_mass, cellular_engulf_ratio_milli_per_membrane_um * prey->membrane_um)) { membrane_blocked = membrane_blocked || product_at_least(hunter->budget.phenotype.total_mass, 1'000, prey->budget.phenotype.total_mass, cellular_engulf_ratio_milli_per_membrane_um); predator.engulf = membrane_blocked ? CellularEngulfStatus::membrane_too_thick : CellularEngulfStatus::prey_too_large; continue; } // The prey's whole inventory moves once: body matter and its post-step reserve. accounting::Inventory whole = prey_step.reserve_after; if (!add(whole, prey->body)) return std::unexpected{CellularRegionStepError::overflow}; if (!add(candidate.heat_released.value, prey_step.heat_after.energy.value)) return std::unexpected{CellularRegionStepError::overflow}; // Capacity: what is left of the predator's per-tick intake limit this tick. const auto remaining = [&](std::uint64_t per_second, std::uint64_t already) -> std::optional { const auto limit = accounting::per_tick( per_second, cellular_motion_tick_microseconds, accounting::Rounding::down); if (!limit) return std::nullopt; return *limit > already ? *limit - already : 0; }; const auto acquired = predator.candidate.intake ? predator.candidate.intake->transfer.acquired : accounting::Inventory{}; accounting::Inventory taken_in{}; const auto energy_room = remaining(hunter->budget.intake_limit.energy.value, acquired.energy.value); if (!energy_room) return std::unexpected{CellularRegionStepError::overflow}; taken_in.energy.value = std::min(whole.energy.value, *energy_room); for (std::size_t channel = 0; channel < whole.matter.size(); ++channel) { const auto room = remaining(hunter->budget.intake_limit.matter[channel].value, acquired.matter[channel].value); if (!room) return std::unexpected{CellularRegionStepError::overflow}; taken_in.matter[channel].value = std::min(whole.matter[channel].value, *room); } if (!add(predator.candidate.reserve_after, taken_in)) return std::unexpected{CellularRegionStepError::overflow}; accounting::Inventory detritus = whole; detritus.energy.value -= taken_in.energy.value; for (std::size_t channel = 0; channel < detritus.matter.size(); ++channel) detritus.matter[channel].value -= taken_in.matter[channel].value; deposits.push_back({prey->life_id, prey->source, prey_step.position, detritus}); CellularCorpseCandidate corpse{prey->life_id, prey_step.position, {}}; corpse.cause = CellularDeathCause::engulfed; corpse.predator_id = hunter->life_id; candidate.starved.push_back(corpse); predator.engulf = CellularEngulfStatus::engulfed; predator.prey_id = prey->life_id; taken[q] = true; break; } } std::vector remaining_lives; remaining_lives.reserve(candidate.lives.size()); for (std::size_t i = 0; i < candidate.lives.size(); ++i) if (!taken[i]) remaining_lives.push_back(candidate.lives[i]); candidate.lives = std::move(remaining_lives); std::ranges::sort(candidate.starved, {}, &CellularCorpseCandidate::life_id); // Detritus: each dead life's inventory goes to the patch at its cell, a new patch at // an empty cell, or the nearest patch once the habitat is full. std::ranges::sort(deposits, {}, &Deposit::life_id); for (const auto& deposit : deposits) { const auto address = cell_of(deposit.position); if (const auto index = habitat.find(address)) { if (!add(patch_stock[*index], deposit.inventory)) return std::unexpected{CellularRegionStepError::overflow}; continue; } const auto made = std::ranges::lower_bound(candidate.new_patches, address, {}, &CellularPatch::address); if (made != candidate.new_patches.end() && made->address == address) { if (!add(made->stock, deposit.inventory)) return std::unexpected{CellularRegionStepError::overflow}; continue; } if (habitat.patches().size() + candidate.new_patches.size() < max_cellular_patches) { candidate.new_patches.insert(made, {address, deposit.source, deposit.inventory}); continue; } // Full habitat: nearest existing patch, lowest address on a tie. const auto distance = [&](CellularPatchAddress other) { const auto dx = static_cast(other.x_um) - address.x_um; const auto dy = static_cast(other.y_um) - address.y_um; return static_cast(dx * dx) + static_cast(dy * dy); }; std::optional> best; for (const auto& patch : habitat.patches()) if (!best || std::pair{distance(patch.address), patch.address} < *best) best = std::pair{distance(patch.address), patch.address}; for (const auto& patch : candidate.new_patches) if (!best || std::pair{distance(patch.address), patch.address} < *best) best = std::pair{distance(patch.address), patch.address}; if (!best) return std::unexpected{CellularRegionStepError::habitat}; if (const auto index = habitat.find(best->second)) { if (!add(patch_stock[*index], deposit.inventory)) return std::unexpected{CellularRegionStepError::overflow}; } else { const auto nearest = std::ranges::lower_bound(candidate.new_patches, best->second, {}, &CellularPatch::address); if (!add(nearest->stock, deposit.inventory)) return std::unexpected{CellularRegionStepError::overflow}; } } } for (std::size_t i = 0; i < patch_stock.size(); ++i) if (patch_stock[i] != habitat.patches()[i].stock) candidate.patches.push_back({habitat.patches()[i].address, patch_stock[i]}); return candidate; } } // namespace evo::biology