Files
aevolution/src/biology/cellular_region_step.cpp
T
dingoandClaude Opus 5.5 76d21b4815
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 31s
Foundation / server-image (push) Successful in 4m24s
Foundation / image (push) Successful in 5m3s
feat(cellular): rules 13 feeding, matter as energy, spent pool and predation
Phase 2 of the cellular revamp build plan (ADR-0179), server half.

- Matter as energy: when an energy cost exceeds the reserve's energy, reserve
  matter stands in for the rest at each channel's burn rate (pJ per 1,000 fg,
  scaled by the genome's burn efficiency), largest channel first. Upkeep may
  burn any channel; thrust only channels the player has not excluded. Burned
  matter adds no heat; it goes to the region's spent pool. A cell dies only when
  nothing can pay its upkeep.
- Collection: per-channel limits scaled by the genome's collection indices, a
  shared limit on all matter, a tunable cost per membrane point, and only the
  genome's kept share (energy conversion) of bubble energy reaching the reserve.
- Predation: engulf mass carries a tunable share of reserve matter, the
  predator's engulf capacity scales its side and the prey's membrane (now in
  nanometres) its own; kill absorption scales the predator's intake; the kill's
  remainder is split between bubbles at the prey and the spent pool, and a full
  habitat sends overflow to the pool.
- The spent pool is owner format 11 state, counted in conservation, and drips
  back as seeded random bubbles every interval tick.
- Reserve matter is carried as load: slower thrust and turning, costlier thrust.
- Channel exclusions are a 4-bit step intent field, trace byte 14; only owned
  lives under rules 13 may send them.

All values come from the revamp tuning file. Rules up to 12 are unchanged. Tests
cover payments and their conservation over 400 seeds, the rules-13 region step
(collection, membrane, kept energy, burning, engulfment and kill splits with
closure), the drip, load, exclusions, a 700-tick run with closure and exact
restore, and trace replay with exclusions. Session v14 and the client follow
the server phases (build plan). Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:35:31 -04:00

614 lines
34 KiB
C++

#include "evo/biology/cellular_region_step.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
#include <array>
#include <limits>
#include <optional>
#include <utility>
namespace evo::biology {
namespace {
constexpr auto u64_max = std::numeric_limits<std::uint64_t>::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<std::uint32_t>(position.x_um / cellular_patch_pitch_um *
cellular_patch_pitch_um),
static_cast<std::uint32_t>(position.y_um / cellular_patch_pitch_um *
cellular_patch_pitch_um)};
}
struct Deposit {
std::uint64_t life_id{}, source{};
CellularPosition position;
accounting::Inventory inventory;
std::uint32_t extent_um{};
};
// One channel of an inventory: 0 energy, 1-4 matter.
std::uint64_t& channel_of(accounting::Inventory& value, std::size_t channel) noexcept {
return channel == 0 ? value.energy.value : value.matter[channel - 1].value;
}
std::uint64_t value_of(const accounting::Inventory& value, std::size_t channel) noexcept {
return channel == 0 ? value.energy.value : value.matter[channel - 1].value;
}
std::uint64_t matter_of(const accounting::Inventory& value) noexcept {
std::uint64_t total{};
for (const auto& channel : value.matter)
total = channel.value > u64_max - total ? u64_max : total + channel.value;
return total;
}
// Rules 13: a life's per-tick collection limits: the budget's founder-composed limits scaled by
// its collection indices and its membrane, and the shared limit on all matter together.
struct Limits {
std::array<std::uint64_t, 5> channel{};
std::uint64_t shared{};
};
std::optional<Limits> revamp_limits(const CellularLifeStepInput& life,
const CellularRevampStepRules& rules) {
if (!life.revamp)
return std::nullopt;
const auto& own = *life.revamp;
const auto points = static_cast<std::int64_t>(own.membrane_nm / 10);
const auto mult = std::clamp<std::int64_t>(
1'000 - static_cast<std::int64_t>(rules.membrane_collection_per_mille_per_point) *
(points - 100),
100, 2'000);
Limits limits{};
std::uint64_t shared{};
for (std::size_t channel = 0; channel < limits.channel.size(); ++channel) {
const auto per_second = channel == 0 ? life.budget.intake_limit.energy.value
: life.budget.intake_limit.matter[channel - 1].value;
const auto base = accounting::per_tick(per_second, cellular_motion_tick_microseconds,
accounting::Rounding::down);
if (!base || *base > u64_max / 2'000)
return std::nullopt;
limits.channel.at(channel) = *base / 100 * own.collection.at(channel) +
*base % 100 * own.collection.at(channel) / 100;
if (limits.channel.at(channel) > u64_max / 2'000)
return std::nullopt;
limits.channel.at(channel) =
limits.channel.at(channel) * static_cast<std::uint64_t>(mult) / 1'000;
if (channel != 0)
shared += *base;
}
limits.shared = shared * static_cast<std::uint64_t>(mult) / 1'000;
return limits;
}
// Rules 13: engulf mass is the body plus the declared share of reserve matter.
std::uint64_t engulf_mass(const CellularLifeStepInput& life, const accounting::Inventory& reserve,
const CellularRevampStepRules& rules) noexcept {
const auto carried = matter_of(reserve) / 100 * rules.engulf_reserve_percent +
matter_of(reserve) % 100 * rules.engulf_reserve_percent / 100;
const auto body = life.budget.phenotype.total_mass;
return carried > u64_max - body ? u64_max : body + carried;
}
} // namespace
std::expected<CellularRegionStepCandidate, CellularRegionStepError>
propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
std::span<const CellularLifeStepInput> lives,
const CellularHabitat& habitat, CellularRegionRules rules) {
if (begin_tick == std::numeric_limits<std::uint64_t>::max())
return std::unexpected{CellularRegionStepError::invalid_tick};
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))
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};
// Rules 13: a revamp input for every life, only in a liquid contact-feeding region.
if (life.revamp.has_value() != rules.revamp.has_value() ||
(rules.revamp && (!liquid || !rules.contact_feeding || life.revamp->membrane_nm == 0 ||
life.revamp->energy_kept_per_thousand > 1'000)))
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<accounting::Inventory> 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<const CellularLifeStepInput*> survivors;
survivors.reserve(ordered.size());
std::vector<Deposit> 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;
if (life->liquid)
frozen.motion = life->liquid->motion; // Anchored while frozen.
candidate.lives.push_back({life->life_id, frozen});
survivors.push_back(life);
continue;
}
auto intent = life->intent;
// Contact feeding needs no target; one sent anyway is ignored (ADR-0136).
const auto target = rules.contact_feeding ? std::nullopt : intent.intake_target;
intent.intake_target.reset();
intent.engulf = false;
const auto step =
life->liquid
? propose_liquid_cellular_step(begin_tick, area, life->position, life->extent_um,
intent.movement, *life->liquid, life->reserve,
life->heat, life->budget,
life->revamp ? &life->revamp->burn : nullptr)
: 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<std::uint64_t>::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<std::uint64_t>::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,
life->extent_um});
corpse.inventory = {};
}
candidate.starved.push_back(corpse);
continue;
}
if (!step)
return std::unexpected{CellularRegionStepError::life_step};
auto result = *step;
if (!add(candidate.spent, result.spent))
return std::unexpected{CellularRegionStepError::overflow};
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;
}
}
}
if (rules.contact_feeding && rules.revamp) {
// Rules 13: per-channel collection scaled by the genome and membrane, a shared limit
// on all matter, and only the kept share of bubble energy reaching the reserve.
const auto limits = revamp_limits(*life, *rules.revamp);
if (!limits)
return std::unexpected{CellularRegionStepError::overflow};
accounting::Inventory drained{}, acquired{};
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_path_contact(life->position, result.position, life->extent_um,
deposit))
continue;
bool took = false;
for (std::size_t channel = 0; channel < limits->channel.size(); ++channel) {
auto& stock = channel_of(patch_stock[index], channel);
auto& taken = channel_of(drained, channel);
auto allowance = limits->channel.at(channel) - taken;
if (channel != 0) {
const auto matter = matter_of(drained);
allowance = std::min(allowance,
limits->shared > matter ? limits->shared - matter : 0);
}
if (deposit.kind == CellularDepositKind::pool)
allowance =
std::min(allowance, limits->channel.at(channel) *
cellular_pool_yield_per_thousand / 1000);
auto& reserve = channel_of(result.reserve_after, channel);
const auto take = std::min({stock, allowance, u64_max - reserve});
if (take == 0)
continue;
stock -= take;
taken += take;
auto kept = take;
if (channel == 0) {
kept = take / 1'000 * life->revamp->energy_kept_per_thousand +
take % 1'000 * life->revamp->energy_kept_per_thousand / 1'000;
if (!add(result.heat_after.energy.value, take - kept))
return std::unexpected{CellularRegionStepError::overflow};
}
reserve += kept;
channel_of(acquired, channel) += kept;
took = true;
}
if (took && !first)
first = index;
}
if (first) {
result.intake_status = CellularIntakeStatus::acquired;
result.intake = CellularPatchUptakeProposal{
habitat.patches()[*first].address,
{patch_stock[*first], result.reserve_after, acquired}};
}
} else if (rules.contact_feeding) {
// ADR-0136: drain every touched deposit (ascending address) up to the per-tick
// intake limit; a pool gives at most a quarter of that limit.
std::array<std::uint64_t, 5> limit{};
for (std::size_t channel = 0; channel < limit.size(); ++channel) {
const auto per_second = channel == 0
? life->budget.intake_limit.energy.value
: life->budget.intake_limit.matter[channel - 1].value;
const auto per_tick = accounting::per_tick(
per_second, cellular_motion_tick_microseconds, accounting::Rounding::down);
if (!per_tick)
return std::unexpected{CellularRegionStepError::overflow};
limit.at(channel) = *per_tick;
}
accounting::Inventory acquired{};
std::optional<std::size_t> first;
for (std::size_t index = 0; index < patch_stock.size(); ++index) {
const auto& deposit = habitat.patches()[index];
// 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) {
auto& stock = channel_of(patch_stock[index], channel);
auto& gained = channel_of(acquired, channel);
auto& reserve = channel_of(result.reserve_after, channel);
auto allowance = limit.at(channel) - gained;
if (deposit.kind == CellularDepositKind::pool)
allowance = std::min(
allowance, limit.at(channel) * cellular_pool_yield_per_thousand / 1000);
const auto take = std::min({stock, allowance, u64_max - reserve});
if (take == 0)
continue;
stock -= take;
gained += take;
reserve += take;
took = true;
}
if (took && !first)
first = index;
}
if (first) {
result.intake_status = CellularIntakeStatus::acquired;
result.intake = CellularPatchUptakeProposal{
habitat.patches()[*first].address,
{patch_stock[*first], result.reserve_after, acquired}};
}
}
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<bool> 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;
// Rules 13: engulf masses carry reserve matter, the predator's capacity scales
// its side and the prey's membrane (nanometres; 1,000 is the founder) its own.
const auto& revamp = rules.revamp;
const auto hunter_mass =
revamp ? engulf_mass(*hunter, predator.candidate.reserve_after, *revamp)
: hunter->budget.phenotype.total_mass;
const auto prey_mass = revamp ? engulf_mass(*prey, prey_step.reserve_after, *revamp)
: prey->budget.phenotype.total_mass;
const auto hunter_scale =
revamp ? std::uint64_t{hunter->revamp->engulf_capacity} * 10'000 : 1'000;
const auto prey_scale =
revamp ? std::uint64_t{revamp->engulf_ratio_milli} * prey->revamp->membrane_nm
: cellular_engulf_ratio_milli_per_membrane_um * prey->membrane_um;
const auto founder_scale = revamp
? std::uint64_t{revamp->engulf_ratio_milli} * 1'000
: cellular_engulf_ratio_milli_per_membrane_um;
if (!product_at_least(hunter_mass, hunter_scale, prey_mass, prey_scale)) {
membrane_blocked =
membrane_blocked ||
product_at_least(hunter_mass, hunter_scale, prey_mass, founder_scale);
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<std::uint64_t> {
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{};
if (revamp) {
// Rules 13: the collection limits scaled by kill absorption; only the kept
// share of the prey's energy reaches the reserve, the rest is heat.
const auto limits = revamp_limits(*hunter, *revamp);
if (!limits)
return std::unexpected{CellularRegionStepError::overflow};
for (std::size_t channel = 0; channel < 5; ++channel) {
const auto limit =
limits->channel.at(channel) / 100 * hunter->revamp->kill_absorption +
limits->channel.at(channel) % 100 * hunter->revamp->kill_absorption /
100;
const auto already = value_of(acquired, channel);
channel_of(taken_in, channel) = std::min(
value_of(whole, channel), limit > already ? limit - already : 0);
}
auto kept_in = taken_in;
kept_in.energy.value =
taken_in.energy.value / 1'000 * hunter->revamp->energy_kept_per_thousand +
taken_in.energy.value % 1'000 * hunter->revamp->energy_kept_per_thousand /
1'000;
if (!add(predator.candidate.heat_after.energy.value,
taken_in.energy.value - kept_in.energy.value) ||
!add(predator.candidate.reserve_after, kept_in))
return std::unexpected{CellularRegionStepError::overflow};
accounting::Inventory bubbles = whole;
accounting::Inventory spent{};
for (std::size_t channel = 0; channel < 5; ++channel) {
const auto rest = value_of(bubbles, channel) - value_of(taken_in, channel);
const auto left = rest / 1'000 * revamp->kill_bubble_per_thousand +
rest % 1'000 * revamp->kill_bubble_per_thousand / 1'000;
channel_of(bubbles, channel) = left;
channel_of(spent, channel) = rest - left;
}
if (!add(candidate.spent, spent))
return std::unexpected{CellularRegionStepError::overflow};
deposits.push_back({prey->life_id, prey->source, prey_step.position, bubbles,
prey->extent_um});
CellularCorpseCandidate eaten{prey->life_id, prey_step.position, {}};
eaten.cause = CellularDeathCause::engulfed;
eaten.predator_id = hunter->life_id;
candidate.starved.push_back(eaten);
predator.engulf = CellularEngulfStatus::engulfed;
predator.prey_id = prey->life_id;
taken[q] = true;
break;
}
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, prey->extent_um});
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<CellularLifeStepResult> 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. Under contact
// feeding (ADR-0136) it breaks into one bubble per non-empty channel instead.
std::ranges::sort(deposits, {}, &Deposit::life_id);
if (rules.contact_feeding) {
const auto taken_address = [&](CellularPatchAddress address) {
if (habitat.find(address))
return true;
const auto made = std::ranges::lower_bound(candidate.new_patches, address, {},
&CellularPatch::address);
return made != candidate.new_patches.end() && made->address == address;
};
std::vector<Deposit> overflow;
for (const auto& deposit : deposits) {
const auto centre_x = deposit.position.x_um + deposit.extent_um / 2;
const auto centre_y = deposit.position.y_um + deposit.extent_um / 2;
for (std::size_t channel = 0; channel < 5; ++channel) {
auto inventory = deposit.inventory;
const auto amount = channel_of(inventory, channel);
if (amount == 0)
continue;
accounting::Inventory single{};
channel_of(single, channel) = amount;
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;
}
// A small ring around the corpse's centre; nudged east past any taken spot.
const std::int64_t offset = (static_cast<std::int64_t>(channel) - 2) *
std::int64_t{cellular_mote_radius_um};
auto x = static_cast<std::int64_t>(centre_x) + offset;
x = std::clamp<std::int64_t>(x, 0,
static_cast<std::int64_t>(area.width_um) - 1);
CellularPatchAddress address{static_cast<std::uint32_t>(x),
static_cast<std::uint32_t>(std::min<std::uint64_t>(
centre_y, area.height_um - 1))};
while (taken_address(address))
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);
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.
if (rules.revamp) {
// Rules 13: the spent pool takes it instead, so it seeps back elsewhere.
for (const auto& deposit : deposits)
if (!add(candidate.spent, deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
deposits.clear();
}
}
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() < deposit_limit) {
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<std::int64_t>(other.x_um) - address.x_um;
const auto dy = static_cast<std::int64_t>(other.y_um) - address.y_um;
return static_cast<std::uint64_t>(dx * dx) + static_cast<std::uint64_t>(dy * dy);
};
std::optional<std::pair<std::uint64_t, CellularPatchAddress>> 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