Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 24s
Foundation / server-image (push) Successful in 4m33s
Foundation / image (push) Successful in 4m59s
Session v14 carries the rules-13 revamp: a body block in the owner's view (members, emergence threshold, exclusions, Emerge open, payable energy, mass and the 20 traits), become, emerge and channel exclusions on actions, become on mutation choices, catalog offers (id, chance, cost) and the emerged ending. Older sessions never see a v14 field. The client shows Stay / Become offspring offers named from the shared catalog, continuing as a bud, the organism and its Emerge button, kept channels, the body and the emerged end screen. Bundle 15 (rules 13 on owner format 11) is durable: schema 60 admits it raw-only, stores become as bit 15 of the choice's operator, widens the action input and mutation results, and publishes the 14 -> 15 revamp profile migration. evo-world-clone opens cellular-v10 (cellular-v9 plus the revamp upgrade from --revamp-tuning), resumable and recoverable. Wildlife counts reserve matter as energy, waits for the bud fee, grows organisms one short of emerging, and hunts by the region step's rules-13 engulf test. The play summary adds organisms, offers and the spent pool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3607 lines
194 KiB
C++
3607 lines
194 KiB
C++
#include "evo/server/lifecycle/cellular_lives.hpp"
|
|
|
|
#include "evo/biology/budding.hpp"
|
|
#include "evo/biology/founder.hpp"
|
|
#include "evo/core/random.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <bit>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <ranges>
|
|
#include <set>
|
|
#include <stdexcept>
|
|
#include <utility>
|
|
|
|
namespace evo::server {
|
|
namespace {
|
|
constexpr std::uint64_t cellular_lives_v1_magic = 0x3130564C43564541ULL; // AEVCLV01
|
|
constexpr std::uint64_t cellular_lives_v2_magic = 0x3230564C43564541ULL; // AEVCLV02
|
|
constexpr std::uint64_t cellular_lives_v3_magic = 0x3330564C43564541ULL; // AEVCLV03
|
|
constexpr std::uint64_t cellular_lives_v4_magic = 0x3430564C43564541ULL; // AEVCLV04
|
|
constexpr std::uint64_t cellular_lives_v5_magic = 0x3530564C43564541ULL; // AEVCLV05
|
|
constexpr std::uint64_t cellular_lives_v6_magic = 0x3630564C43564541ULL; // AEVCLV06
|
|
constexpr std::uint64_t cellular_lives_v7_magic = 0x3730564C43564541ULL; // AEVCLV07
|
|
constexpr std::uint64_t cellular_lives_v8_magic = 0x3830564C43564541ULL; // AEVCLV08
|
|
constexpr std::uint64_t cellular_lives_v9_magic = 0x3930564C43564541ULL; // AEVCLV09
|
|
constexpr std::uint64_t cellular_lives_v10_magic = 0x3031564C43564541ULL; // AEVCLV10
|
|
constexpr std::uint64_t cellular_lives_v11_magic = 0x3131564C43564541ULL; // AEVCLV11
|
|
constexpr std::size_t cellular_lives_header_bytes = 212;
|
|
constexpr std::size_t cellular_site_bytes = 8;
|
|
constexpr std::size_t cellular_life_v1_bytes = 168;
|
|
constexpr std::size_t cellular_life_v2_bytes = 480;
|
|
constexpr std::size_t cellular_corpse_bytes = 100;
|
|
// Format 4: cause (1), 7 zero bytes and the predator's life id (8).
|
|
constexpr std::size_t cellular_corpse_v4_bytes = cellular_corpse_bytes + 16;
|
|
// Format 5 (ADR-0125): the header adds the next bud sequence, each life and each corpse
|
|
// its parent life (8 bytes each).
|
|
constexpr std::size_t cellular_lives_v5_header_bytes = cellular_lives_header_bytes + 8;
|
|
constexpr std::size_t cellular_life_v5_bytes = cellular_life_v2_bytes + 8;
|
|
constexpr std::size_t cellular_corpse_v5_bytes = cellular_corpse_v4_bytes + 8;
|
|
// Format 6 (ADR-0128): each life adds presence (1), 7 zero bytes and its freeze tick (8).
|
|
constexpr std::size_t cellular_life_v6_bytes = cellular_life_v5_bytes + 16;
|
|
// Format 7: two boundary-flow inventories and nonresident count/reserved.
|
|
constexpr std::size_t cellular_lives_v7_header_bytes = cellular_lives_v5_header_bytes + 88;
|
|
constexpr std::size_t cellular_lives_v8_header_bytes = cellular_lives_v7_header_bytes + 8;
|
|
// Format 9 (ADR-0175): light numerator, denominator, entitlement, moving share and
|
|
// reserved (4 each for the last two), and the cumulative captured energy.
|
|
constexpr std::size_t cellular_lives_v9_header_bytes = cellular_lives_v8_header_bytes + 40;
|
|
// Format 10 (rules 12): the current seed and nine 4-byte current fields (44), five founder
|
|
// handling fields (20), five deposit motion fields and reserved (24): 88 bytes. Each life adds
|
|
// its motion state (two velocities, heading, reserved, two carries), 20 bytes.
|
|
constexpr std::size_t cellular_lives_v10_header_bytes = cellular_lives_v9_header_bytes + 88;
|
|
constexpr std::size_t cellular_life_motion_bytes = 20;
|
|
// Format 11 (rules 13, ADR-0179): the revamp rules and the spent pool. Essential upkeep share and
|
|
// a reserved zero (8), four burn rates (32), membrane collection cost, engulf ratio, engulf
|
|
// reserve share and kill bubble share (16), drip interval and a reserved zero (8), drip bubble
|
|
// energy and matter (16), and the spent pool (40): 120 bytes. The word after the drip interval
|
|
// is the reserve load share. Later build phases extend this
|
|
// block before format 11 is deployed.
|
|
// Then the growth rate and a reserved zero (8), the offer rules (seven 4-byte fields and a
|
|
// reserved zero, 32), the catalog bounds (five 4-byte fields, a reserved zero and the carbon
|
|
// gate, 32), the offer interval and a reserved zero (8), and 49 mutation tunables of 80 bytes.
|
|
constexpr std::size_t cellular_revamp_mutation_bytes = 80;
|
|
// Then the reproduction tunables: split share, split growth, organism cap, fee scale (16) and
|
|
// the bud fee (40).
|
|
constexpr std::size_t cellular_lives_v11_header_bytes =
|
|
cellular_lives_v10_header_bytes + 120 + 8 + 32 + 32 + 8 +
|
|
biology::cellular_catalog_size * cellular_revamp_mutation_bytes + 56 + 24;
|
|
// Each format-11 life adds its mutation state: 49 scores and a reserved zero (100), 98 trigger
|
|
// states of 24 bytes (2,352), lineage progress and the cadence counter (16), the last brake,
|
|
// three zeros and the growth carry (8), the offers made (8), and the pending offer (88).
|
|
constexpr std::size_t cellular_trigger_state_bytes = 24;
|
|
constexpr std::size_t cellular_life_revamp_bytes =
|
|
100 + 2 * biology::cellular_catalog_size * cellular_trigger_state_bytes + 16 + 8 + 8 + 88;
|
|
|
|
bool valid_motion(const biology::CellularMotionState& m) noexcept {
|
|
constexpr std::int64_t carry = biology::cellular_velocity_q10_per_um_s * 1'000'000;
|
|
return m.velocity_x_q10 >= -biology::cellular_velocity_limit_q10 &&
|
|
m.velocity_x_q10 <= biology::cellular_velocity_limit_q10 &&
|
|
m.velocity_y_q10 >= -biology::cellular_velocity_limit_q10 &&
|
|
m.velocity_y_q10 <= biology::cellular_velocity_limit_q10 && m.remainder_x >= 0 &&
|
|
m.remainder_x < carry && m.remainder_y >= 0 && m.remainder_y < carry;
|
|
}
|
|
constexpr std::size_t cellular_offspring_revision_bytes = 32;
|
|
|
|
std::uint64_t checksum(std::span<const std::uint8_t> bytes) noexcept {
|
|
std::uint64_t value = 14695981039346656037ULL;
|
|
for (const auto byte : bytes)
|
|
value = (value ^ byte) * 1099511628211ULL;
|
|
return value;
|
|
}
|
|
|
|
std::uint64_t mutation_seed(std::uint64_t world, std::uint64_t region, std::uint64_t life,
|
|
std::uint64_t event) noexcept {
|
|
auto value = 14695981039346656037ULL;
|
|
for (const auto part : {world, region, life, event}) {
|
|
for (unsigned index = 0; index < 8; ++index) {
|
|
value = (value ^ static_cast<std::uint8_t>(part >> (index * 8U))) * 1099511628211ULL;
|
|
}
|
|
}
|
|
return value == 0 ? 1 : value;
|
|
}
|
|
|
|
class Writer {
|
|
public:
|
|
explicit Writer(std::vector<std::uint8_t>& bytes) : bytes_{bytes} {}
|
|
void put(std::uint64_t value, unsigned width = 8) {
|
|
for (unsigned i = 0; i < width; ++i, value >>= 8U)
|
|
bytes_.push_back(static_cast<std::uint8_t>(value & 255U));
|
|
}
|
|
void inventory(const accounting::Inventory& value) {
|
|
put(value.energy.value);
|
|
for (const auto mass : value.matter)
|
|
put(mass.value);
|
|
}
|
|
void site(SpawnSite value) {
|
|
put(std::bit_cast<std::uint32_t>(value.x_um), 4);
|
|
put(std::bit_cast<std::uint32_t>(value.y_um), 4);
|
|
}
|
|
template <std::size_t N> void bytes(const std::array<std::uint8_t, N>& value) {
|
|
bytes_.insert(bytes_.end(), value.begin(), value.end());
|
|
}
|
|
void raw(std::span<const std::uint8_t> value) {
|
|
bytes_.insert(bytes_.end(), value.begin(), value.end());
|
|
}
|
|
void zeros(std::size_t count) {
|
|
bytes_.insert(bytes_.end(), count, 0);
|
|
}
|
|
|
|
private:
|
|
std::vector<std::uint8_t>& bytes_;
|
|
};
|
|
|
|
class Reader {
|
|
public:
|
|
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_{bytes} {}
|
|
std::uint64_t get(unsigned width = 8) {
|
|
std::uint64_t value{};
|
|
for (unsigned i = 0; i < width; ++i)
|
|
value |= std::uint64_t{bytes_[at_++]} << (8U * i);
|
|
return value;
|
|
}
|
|
accounting::Inventory inventory() {
|
|
accounting::Inventory value{};
|
|
value.energy.value = get();
|
|
for (auto& mass : value.matter)
|
|
mass.value = get();
|
|
return value;
|
|
}
|
|
SpawnSite site() {
|
|
return {std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(get(4))),
|
|
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(get(4)))};
|
|
}
|
|
template <std::size_t N> std::array<std::uint8_t, N> bytes() {
|
|
std::array<std::uint8_t, N> result{};
|
|
std::ranges::copy(bytes_.subspan(at_, N), result.begin());
|
|
at_ += N;
|
|
return result;
|
|
}
|
|
std::span<const std::uint8_t> raw(std::size_t size) {
|
|
const auto result = bytes_.subspan(at_, size);
|
|
at_ += size;
|
|
return result;
|
|
}
|
|
|
|
private:
|
|
std::span<const std::uint8_t> bytes_;
|
|
std::size_t at_{};
|
|
};
|
|
|
|
bool add_inventory(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
|
|
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
|
|
if (value.energy.value > maximum - total.energy.value)
|
|
return false;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
if (value.matter[channel].value > maximum - total.matter[channel].value)
|
|
return false;
|
|
total.energy.value += value.energy.value;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
total.matter[channel].value += value.matter[channel].value;
|
|
return true;
|
|
}
|
|
|
|
bool subtract_inventory(accounting::Inventory& total, const accounting::Inventory& value) noexcept {
|
|
if (value.energy.value > total.energy.value)
|
|
return false;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
if (value.matter[channel].value > total.matter[channel].value)
|
|
return false;
|
|
total.energy.value -= value.energy.value;
|
|
for (std::size_t channel = 0; channel < total.matter.size(); ++channel)
|
|
total.matter[channel].value -= value.matter[channel].value;
|
|
return true;
|
|
}
|
|
|
|
// Format 11: the revamp rules' offer settings and a life's mutation state.
|
|
void write_trigger(Writer& out, const biology::CellularTriggerState& s) {
|
|
out.put(s.first);
|
|
out.put(s.second);
|
|
out.put(s.ticks, 4);
|
|
out.put(s.heading, 2);
|
|
out.put(s.running, 1);
|
|
out.put(0, 1);
|
|
}
|
|
std::optional<biology::CellularTriggerState> read_trigger(Reader& in) {
|
|
biology::CellularTriggerState s{};
|
|
s.first = in.get();
|
|
s.second = in.get();
|
|
s.ticks = static_cast<std::uint32_t>(in.get(4));
|
|
s.heading = static_cast<std::uint16_t>(in.get(2));
|
|
const auto running = in.get(1);
|
|
if (running > 1 || in.get(1) != 0)
|
|
return std::nullopt;
|
|
s.running = static_cast<std::uint8_t>(running);
|
|
return s;
|
|
}
|
|
void write_revamp_offers(Writer& out, const CellularRevampRules& r) {
|
|
out.put(r.growth_per_tick_centi_mille, 4);
|
|
out.put(0, 4);
|
|
const auto& o = r.offers;
|
|
for (const auto value : {o.options, o.floor_ppm, o.cap_ppm})
|
|
out.put(value, 4);
|
|
out.put(static_cast<std::uint32_t>(o.score_min), 4);
|
|
out.put(static_cast<std::uint32_t>(o.score_max), 4);
|
|
out.put(o.max_multiplier_per_mille, 4);
|
|
out.put(o.min_multiplier_per_mille, 4);
|
|
out.put(0, 4);
|
|
const auto& b = r.bounds;
|
|
for (const auto value :
|
|
{b.min_points, b.max_points, b.recipe_min_share, b.max_litter, b.buds_for_adhesion})
|
|
out.put(value, 4);
|
|
out.put(0, 4);
|
|
out.put(b.carbon_for_light);
|
|
out.put(r.offer_interval_ticks, 4);
|
|
out.put(0, 4);
|
|
for (const auto& m : r.mutations) {
|
|
out.put(m.enabled ? 1 : 0, 1);
|
|
out.zeros(3);
|
|
out.put(m.base_weight, 4);
|
|
out.put(static_cast<std::uint32_t>(m.increase_points), 4);
|
|
out.put(static_cast<std::uint32_t>(m.decrease_points), 4);
|
|
for (const auto value : {m.primary_step, m.paired_step, m.spread_step, m.increase_ticks,
|
|
m.decrease_ticks, m.cost_scale_percent})
|
|
out.put(value, 4);
|
|
out.inventory(m.cost);
|
|
}
|
|
for (const auto value :
|
|
{r.split_share_per_thousand, r.split_min_growth, r.organism_cap, r.bud_fee_scale_percent})
|
|
out.put(value, 4);
|
|
out.inventory(r.bud_fee);
|
|
out.put(r.organism_load_per_thousand, 4);
|
|
out.put(r.emerge_members, 4);
|
|
out.put(r.emerge_mass_fg);
|
|
out.put(r.emerge_reserve_pj);
|
|
}
|
|
bool read_revamp_offers(Reader& in, CellularRevampRules& r) {
|
|
const auto u32 = [&in] { return static_cast<std::uint32_t>(in.get(4)); };
|
|
const auto i32 = [&in] {
|
|
return static_cast<std::int32_t>(static_cast<std::uint32_t>(in.get(4)));
|
|
};
|
|
bool zero = true;
|
|
r.growth_per_tick_centi_mille = u32();
|
|
zero = zero && in.get(4) == 0;
|
|
auto& o = r.offers;
|
|
o.options = u32();
|
|
o.floor_ppm = u32();
|
|
o.cap_ppm = u32();
|
|
o.score_min = i32();
|
|
o.score_max = i32();
|
|
o.max_multiplier_per_mille = u32();
|
|
o.min_multiplier_per_mille = u32();
|
|
zero = zero && in.get(4) == 0;
|
|
auto& b = r.bounds;
|
|
b.min_points = u32();
|
|
b.max_points = u32();
|
|
b.recipe_min_share = u32();
|
|
b.max_litter = u32();
|
|
b.buds_for_adhesion = u32();
|
|
zero = zero && in.get(4) == 0;
|
|
b.carbon_for_light = in.get();
|
|
r.offer_interval_ticks = u32();
|
|
zero = zero && in.get(4) == 0;
|
|
for (auto& m : r.mutations) {
|
|
const auto enabled = in.get(1);
|
|
zero = zero && enabled <= 1 && in.get(3) == 0;
|
|
m.enabled = enabled == 1;
|
|
m.base_weight = u32();
|
|
m.increase_points = i32();
|
|
m.decrease_points = i32();
|
|
m.primary_step = u32();
|
|
m.paired_step = u32();
|
|
m.spread_step = u32();
|
|
m.increase_ticks = u32();
|
|
m.decrease_ticks = u32();
|
|
m.cost_scale_percent = u32();
|
|
m.cost = in.inventory();
|
|
}
|
|
r.split_share_per_thousand = u32();
|
|
r.split_min_growth = u32();
|
|
r.organism_cap = u32();
|
|
r.bud_fee_scale_percent = u32();
|
|
r.bud_fee = in.inventory();
|
|
r.organism_load_per_thousand = u32();
|
|
r.emerge_members = u32();
|
|
r.emerge_mass_fg = in.get();
|
|
r.emerge_reserve_pj = in.get();
|
|
return zero;
|
|
}
|
|
void write_revamp_life(Writer& out, const CellularRevampLife& life) {
|
|
for (const auto score : life.affinity.score)
|
|
out.put(static_cast<std::uint16_t>(score), 2);
|
|
out.put(0, 2);
|
|
for (const auto& s : life.affinity.increase)
|
|
write_trigger(out, s);
|
|
for (const auto& s : life.affinity.decrease)
|
|
write_trigger(out, s);
|
|
out.put(life.progress.carbon_burned);
|
|
out.put(life.progress.buds, 4);
|
|
out.put(life.active_ticks, 4);
|
|
out.put(life.last_brake, 1);
|
|
out.zeros(1);
|
|
out.put(life.members, 2);
|
|
out.put(life.growth_carry, 4);
|
|
out.put(life.events);
|
|
const auto& offer = life.offer;
|
|
out.put(offer.event_index);
|
|
out.put(offer.offer_tick);
|
|
out.put(offer.count, 1);
|
|
out.zeros(7);
|
|
for (const auto id : offer.ids)
|
|
out.put(id, 2);
|
|
for (const auto chance : offer.chances)
|
|
out.put(chance, 4);
|
|
out.zeros(4);
|
|
}
|
|
std::optional<CellularRevampLife> read_revamp_life(Reader& in) {
|
|
CellularRevampLife life{};
|
|
for (auto& score : life.affinity.score)
|
|
score = static_cast<std::int16_t>(static_cast<std::uint16_t>(in.get(2)));
|
|
bool zero = in.get(2) == 0;
|
|
for (auto& s : life.affinity.increase) {
|
|
const auto read = read_trigger(in);
|
|
if (!read)
|
|
return std::nullopt;
|
|
s = *read;
|
|
}
|
|
for (auto& s : life.affinity.decrease) {
|
|
const auto read = read_trigger(in);
|
|
if (!read)
|
|
return std::nullopt;
|
|
s = *read;
|
|
}
|
|
life.progress.carbon_burned = in.get();
|
|
life.progress.buds = static_cast<std::uint32_t>(in.get(4));
|
|
life.active_ticks = static_cast<std::uint32_t>(in.get(4));
|
|
const auto brake = in.get(1);
|
|
zero = zero && brake <= 1 && in.get(1) == 0;
|
|
life.last_brake = static_cast<std::uint8_t>(brake);
|
|
life.members = static_cast<std::uint16_t>(in.get(2));
|
|
zero = zero && life.members >= 1;
|
|
life.growth_carry = static_cast<std::uint32_t>(in.get(4));
|
|
life.events = in.get();
|
|
auto& offer = life.offer;
|
|
offer.event_index = in.get();
|
|
offer.offer_tick = in.get();
|
|
const auto count = in.get(1);
|
|
zero = zero && in.get(7) == 0 && count <= max_cellular_offer_options;
|
|
offer.count = static_cast<std::uint8_t>(count);
|
|
for (auto& id : offer.ids)
|
|
id = static_cast<std::uint16_t>(in.get(2));
|
|
for (auto& chance : offer.chances)
|
|
chance = static_cast<std::uint32_t>(in.get(4));
|
|
zero = zero && in.get(4) == 0;
|
|
// A pending offer names catalog mutations once each, with chances, and nothing after them;
|
|
// no offer leaves every slot zero.
|
|
for (std::size_t k = 0; k < max_cellular_offer_options; ++k) {
|
|
const bool used = k < offer.count;
|
|
if (used != (offer.ids.at(k) != 0) ||
|
|
(used &&
|
|
(biology::cellular_mutation(offer.ids.at(k)) == nullptr || offer.chances.at(k) == 0 ||
|
|
offer.chances.at(k) > biology::cellular_chance_whole)) ||
|
|
(!used && offer.chances.at(k) != 0))
|
|
return std::nullopt;
|
|
for (std::size_t j = 0; j < k && used; ++j)
|
|
if (offer.ids.at(j) == offer.ids.at(k))
|
|
return std::nullopt;
|
|
}
|
|
if (!zero || (offer.count == 0 && (offer.event_index != 0 || offer.offer_tick != 0)) ||
|
|
(offer.count != 0 && offer.event_index != life.events) || life.growth_carry >= 100)
|
|
return std::nullopt;
|
|
return life;
|
|
}
|
|
|
|
// Rules 13 (reproduction plan section 6): a multicellular organism develops as its genome with
|
|
// the target size times its members, so mass, footprint, upkeep and growth follow from it.
|
|
std::expected<biology::Genome, CellularLivesError> organism_genome(const biology::Genome& genome,
|
|
std::uint32_t members) {
|
|
if (members <= 1)
|
|
return genome;
|
|
biology::GenomeDraft draft;
|
|
draft.schema_version = genome.schema_version();
|
|
draft.id = genome.id();
|
|
draft.origin_event = genome.origin_event();
|
|
draft.development_version = genome.development_version();
|
|
draft.parents.assign(genome.parents().begin(), genome.parents().end());
|
|
draft.capabilities.assign(genome.capabilities().begin(), genome.capabilities().end());
|
|
draft.movement_arrangement = genome.movement_arrangement();
|
|
draft.cellular_traits = genome.cellular_traits();
|
|
for (auto& record : draft.capabilities)
|
|
if (record.kind == biology::Capability::target_size) {
|
|
if (record.parameter > std::numeric_limits<std::uint32_t>::max() / members)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
record.parameter *= members;
|
|
}
|
|
const auto made = biology::Genome::create(draft);
|
|
if (!made)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
return *made;
|
|
}
|
|
std::expected<biology::Genome, CellularLivesError>
|
|
life_genome(const biology::LineageArchive& archive, const CellularOwnedLife& life) {
|
|
const auto genome = archive.find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
return organism_genome(*genome, life.revamp.members);
|
|
}
|
|
// Moves `body` to `target`: added matter from `reserve` per channel with construction energy
|
|
// (to `heat`) at `price` pJ per 1,000 fg added, freed matter back to the reserve. Changes nothing
|
|
// and returns false when the reserve cannot pay.
|
|
bool rebody(accounting::Inventory& body, accounting::Inventory& reserve,
|
|
accounting::Inventory& heat, const accounting::Inventory& target, std::uint64_t price) {
|
|
auto next_reserve = reserve;
|
|
std::uint64_t added{};
|
|
for (std::size_t c = 0; c < body.matter.size(); ++c) {
|
|
const auto have = body.matter[c].value, want = target.matter[c].value;
|
|
if (want > have) {
|
|
if (next_reserve.matter[c].value < want - have)
|
|
return false;
|
|
next_reserve.matter[c].value -= want - have;
|
|
added += want - have;
|
|
} else {
|
|
next_reserve.matter[c].value += have - want;
|
|
}
|
|
}
|
|
const auto energy = added / 1'000 * price + added % 1'000 * price / 1'000;
|
|
if (next_reserve.energy.value < energy)
|
|
return false;
|
|
next_reserve.energy.value -= energy;
|
|
reserve = next_reserve;
|
|
heat.energy.value += energy;
|
|
body = target;
|
|
body.energy = {};
|
|
return true;
|
|
}
|
|
|
|
std::expected<biology::MetabolicBudget, CellularLivesError>
|
|
budget_for(const biology::LineageArchive& archive, const CellularOwnedLife& life,
|
|
std::uint32_t temperature,
|
|
const biology::BodyTuning& body = biology::default_body_tuning) {
|
|
const auto genome = life_genome(archive, life);
|
|
if (!genome)
|
|
return std::unexpected{genome.error()};
|
|
const auto budget =
|
|
biology::metabolic_budget(*genome, life.growth, {temperature, {}}, 1000, body);
|
|
if (!budget)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
return *budget;
|
|
}
|
|
|
|
bool separated(std::uint64_t left, std::uint64_t right, std::uint32_t left_extent,
|
|
std::uint32_t right_extent) noexcept {
|
|
return left < right ? right - left >= left_extent : left - right >= right_extent;
|
|
}
|
|
|
|
// ADR-0125 placement: touching the parent, centres (parent + bud extent) / 2 + 1 apart on
|
|
// each moved axis, trying east and then counter-clockwise in 45-degree steps. The first
|
|
// spot inside the area and clear of every living cell wins; none is a refusal.
|
|
std::expected<std::optional<biology::CellularPosition>, CellularLivesError>
|
|
bud_position(const CellularOwnedLife& parent, std::uint32_t parent_extent, std::uint32_t bud_extent,
|
|
std::span<const CellularOwnedLife> lives, const biology::LineageArchive& archive,
|
|
const CellularLivesConfig& config) {
|
|
constexpr std::array<std::array<std::int64_t, 2>, 8> directions{
|
|
{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}};
|
|
if (bud_extent == 0 || bud_extent > config.area.width_um || bud_extent > config.area.height_um)
|
|
return std::optional<biology::CellularPosition>{};
|
|
std::vector<std::uint32_t> extents;
|
|
extents.reserve(lives.size());
|
|
for (const auto& living : lives) {
|
|
const auto budget = budget_for(archive, living, config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
extents.push_back(budget->phenotype.extent);
|
|
}
|
|
// Doubled centre coordinates keep half extents exact.
|
|
const auto step = std::int64_t{parent_extent} + bud_extent + 2;
|
|
// Twice the bud's corner coordinate on one axis; negative is outside the area.
|
|
const auto doubled_corner = [&](std::uint64_t parent_corner, std::int64_t direction) {
|
|
return 2 * static_cast<std::int64_t>(parent_corner) + parent_extent + direction * step -
|
|
std::int64_t{bud_extent};
|
|
};
|
|
for (const auto& [dx, dy] : directions) {
|
|
const auto twice_x = doubled_corner(parent.position.x_um, dx);
|
|
const auto twice_y = doubled_corner(parent.position.y_um, dy);
|
|
const auto x = twice_x / 2;
|
|
const auto y = twice_y / 2;
|
|
if (twice_x < 0 || twice_y < 0 ||
|
|
static_cast<std::uint64_t>(x) > config.area.width_um - bud_extent ||
|
|
static_cast<std::uint64_t>(y) > config.area.height_um - bud_extent)
|
|
continue;
|
|
const biology::CellularPosition candidate{static_cast<std::uint64_t>(x),
|
|
static_cast<std::uint64_t>(y)};
|
|
bool clear = true;
|
|
for (std::size_t i = 0; i < lives.size() && clear; ++i)
|
|
clear = lives[i].presence == CellularPresence::suspended ||
|
|
separated(candidate.x_um, lives[i].position.x_um, bud_extent, extents[i]) ||
|
|
separated(candidate.y_um, lives[i].position.y_um, bud_extent, extents[i]);
|
|
if (clear)
|
|
return std::optional{candidate};
|
|
}
|
|
return std::optional<biology::CellularPosition>{};
|
|
}
|
|
|
|
// ADR-0128 resume: its own position if clear of every cell in the world, else the first
|
|
// clear spot at one, two or three of its extents in the eight fixed directions.
|
|
std::expected<std::optional<biology::CellularPosition>, CellularLivesError>
|
|
resume_position(const CellularOwnedLife& life, std::uint32_t extent,
|
|
std::span<const CellularOwnedLife> lives, const biology::LineageArchive& archive,
|
|
const CellularLivesConfig& config) {
|
|
constexpr std::array<std::array<std::int64_t, 2>, 8> directions{
|
|
{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}};
|
|
if (extent == 0 || extent > config.area.width_um || extent > config.area.height_um)
|
|
return std::optional<biology::CellularPosition>{};
|
|
std::vector<std::pair<const CellularOwnedLife*, std::uint32_t>> present;
|
|
for (const auto& other : lives) {
|
|
if (other.presence == CellularPresence::suspended ||
|
|
other.identity.life == life.identity.life)
|
|
continue;
|
|
const auto budget = budget_for(archive, other, config.ambient_temperature_millikelvin);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
present.emplace_back(&other, budget->phenotype.extent);
|
|
}
|
|
const auto clear = [&](std::int64_t x, std::int64_t y) {
|
|
if (x < 0 || y < 0 || static_cast<std::uint64_t>(x) > config.area.width_um - extent ||
|
|
static_cast<std::uint64_t>(y) > config.area.height_um - extent)
|
|
return false;
|
|
return std::ranges::all_of(present, [&](const auto& entry) {
|
|
const auto& [other, other_extent] = entry;
|
|
return separated(static_cast<std::uint64_t>(x), other->position.x_um, extent,
|
|
other_extent) ||
|
|
separated(static_cast<std::uint64_t>(y), other->position.y_um, extent,
|
|
other_extent);
|
|
});
|
|
};
|
|
const auto x0 = static_cast<std::int64_t>(life.position.x_um);
|
|
const auto y0 = static_cast<std::int64_t>(life.position.y_um);
|
|
if (clear(x0, y0))
|
|
return std::optional{life.position};
|
|
for (std::uint32_t ring = 1; ring <= cellular_resume_extents; ++ring)
|
|
for (const auto& [dx, dy] : directions) {
|
|
const auto step = static_cast<std::int64_t>(ring) * extent;
|
|
if (clear(x0 + dx * step, y0 + dy * step))
|
|
return std::optional{
|
|
biology::CellularPosition{static_cast<std::uint64_t>(x0 + dx * step),
|
|
static_cast<std::uint64_t>(y0 + dy * step)}};
|
|
}
|
|
return std::optional<biology::CellularPosition>{};
|
|
}
|
|
|
|
std::expected<accounting::Inventory, CellularLivesError>
|
|
sum_state(accounting::Inventory nursery, accounting::Inventory heat,
|
|
const biology::CellularHabitat& habitat, std::span<const CellularOwnedLife> lives,
|
|
std::span<const CellularOwnedCorpse> corpses) noexcept {
|
|
auto total = nursery;
|
|
if (!add_inventory(total, heat))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
if (!add_inventory(total, habitat.totals()))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
for (const auto& life : lives)
|
|
if (!add_inventory(total, life.body) || !add_inventory(total, life.reserve))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
for (const auto& corpse : corpses)
|
|
if (!add_inventory(total, corpse.inventory))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
return total;
|
|
}
|
|
|
|
bool validate_plans(std::span<const CellularOwnedLife> lives,
|
|
std::span<const CellularOwnedCorpse> corpses,
|
|
const biology::LineageArchive& archive,
|
|
std::span<const CellularOffspringRevision> history, std::uint64_t tick,
|
|
bool transfers = false) {
|
|
if (history.size() > biology::max_archived_genomes)
|
|
return false;
|
|
struct Plan {
|
|
std::uint64_t life, expressed, current, final, editable_after, died;
|
|
bool selectable;
|
|
};
|
|
std::vector<Plan> plans;
|
|
std::map<std::uint64_t, std::uint64_t> earliest_birth;
|
|
std::map<std::uint64_t, std::uint64_t> last_expression;
|
|
for (const auto& revision : archive.revisions())
|
|
last_expression[revision.organism] =
|
|
std::max(last_expression[revision.organism], revision.at.value);
|
|
const auto observe = [&](std::uint64_t genome, std::uint64_t born) {
|
|
const auto [position, inserted] = earliest_birth.emplace(genome, born);
|
|
if (!inserted)
|
|
position->second = std::min(position->second, born);
|
|
};
|
|
plans.reserve(lives.size() + corpses.size());
|
|
for (const auto& life : lives) {
|
|
plans.push_back(
|
|
{life.identity.life, life.identity.genome, life.identity.genome, life.offspring_genome,
|
|
std::max(life.identity.born.value, last_expression[life.identity.organism]), 0,
|
|
transfers || life.account != LifeAccount{}});
|
|
observe(life.identity.genome, life.identity.born.value);
|
|
}
|
|
for (const auto& corpse : corpses) {
|
|
const auto record = archive.organism(corpse.organism);
|
|
const auto expressed = archive.current_genome(corpse.organism);
|
|
if (!record || !expressed)
|
|
return false;
|
|
plans.push_back({corpse.life_id, *expressed, *expressed, corpse.offspring_genome,
|
|
std::max(record->born.value, last_expression[corpse.organism]),
|
|
corpse.died_tick, transfers || corpse.parent_life == 0});
|
|
observe(record->genome, record->born.value);
|
|
observe(*expressed, record->born.value);
|
|
}
|
|
std::ranges::sort(plans, {}, &Plan::life);
|
|
std::set<std::uint64_t> successors;
|
|
for (std::size_t index = 0; index < history.size(); ++index) {
|
|
const auto& revision = history[index];
|
|
if (revision.tick == 0 || revision.tick > tick || revision.successor == revision.previous ||
|
|
(index != 0 && (history[index - 1].tick > revision.tick ||
|
|
(history[index - 1].tick == revision.tick &&
|
|
history[index - 1].life >= revision.life))) ||
|
|
!successors.insert(revision.successor).second)
|
|
return false;
|
|
const auto actor = std::ranges::lower_bound(plans, revision.life, {}, &Plan::life);
|
|
const auto parent = archive.find(revision.previous);
|
|
const auto child = archive.find(revision.successor);
|
|
if (actor == plans.end() || actor->life != revision.life || !actor->selectable ||
|
|
actor->current != revision.previous || revision.tick <= actor->editable_after ||
|
|
(actor->died != 0 && revision.tick >= actor->died) || !parent || !child ||
|
|
child->parents().size() != 1 || child->parents().front() != revision.previous ||
|
|
child->origin_event() != revision.successor ||
|
|
child->schema_version() != parent->schema_version() ||
|
|
child->development_version() != parent->development_version())
|
|
return false;
|
|
actor->current = revision.successor;
|
|
// A plan selected here cannot have been expressed at an earlier birth.
|
|
const auto born = earliest_birth.find(revision.successor);
|
|
if (born != earliest_birth.end() && born->second < revision.tick)
|
|
return false;
|
|
}
|
|
for (const auto& plan : plans) {
|
|
const auto expressed = archive.find(plan.expressed);
|
|
const auto inherited = archive.find(plan.final);
|
|
if (plan.final == 0 || plan.current != plan.final || !expressed || !inherited ||
|
|
expressed->schema_version() != inherited->schema_version() ||
|
|
expressed->development_version() != inherited->development_version())
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::expected<accounting::Inventory, CellularLivesError>
|
|
validate_state(std::uint64_t world, std::uint64_t region, std::uint64_t frame,
|
|
const CellularLivesConfig& config, const NurseryConfig& nursery_config,
|
|
const biology::CellularHabitat& habitat, std::span<const CellularOwnedLife> lives,
|
|
std::span<const CellularOwnedCorpse> corpses, const biology::LineageArchive& archive,
|
|
accounting::Inventory nursery, accounting::Inventory heat,
|
|
accounting::Inventory opening_total, bool detritus_rules = false,
|
|
bool bud_rules = false, std::uint64_t next_bud_sequence = 1,
|
|
bool presence_rules = false, const CellularBoundaryLedger* boundary = nullptr,
|
|
const std::vector<CellularOffspringRevision>* plans = nullptr,
|
|
const accounting::Inventory& spent = {}, bool transfers = false) {
|
|
// A bud's identity lies in this region's namespace below the next sequence; anything
|
|
// else is an allocated identity, below the namespace (ADR-0125).
|
|
const auto bud_identity = [&](std::uint64_t identity) noexcept {
|
|
const auto first = cellular_bud_identity(region, 1);
|
|
return bud_rules && first != 0 && next_bud_sequence > 1 && identity >= first &&
|
|
identity - first < next_bud_sequence - 1;
|
|
};
|
|
const auto lineage_valid = [&](std::uint64_t life_id, std::uint64_t parent) noexcept {
|
|
if (parent == 0) // Rules 4 keep allocated identities below the bud namespace.
|
|
return !bud_rules || life_id < cellular_bud_namespace;
|
|
const auto origin = (life_id >> 32U) & cellular_bud_max_region;
|
|
const bool imported = boundary && life_id >= cellular_bud_namespace && origin != region &&
|
|
origin > 0 && origin <= cellular_bud_max_region &&
|
|
(life_id & 0xFFFF'FFFFULL) != 0;
|
|
return (bud_identity(life_id) || imported) && parent != life_id;
|
|
};
|
|
const auto& map = habitat.config();
|
|
if (world == 0 || region == 0 || frame == 0 || nursery_config.world != world ||
|
|
nursery_config.region != region || nursery_config.frame != frame ||
|
|
nursery_config.source == 0 || nursery_config.funding != nursery || map.world != world ||
|
|
map.region != region || map.frame != frame || config.area.width_um == 0 ||
|
|
config.area.height_um == 0 || map.width_um != config.area.width_um ||
|
|
map.height_um != config.area.height_um || config.ambient_temperature_millikelvin == 0 ||
|
|
nursery_config.sites.empty() || nursery_config.sites.size() > max_primitive_lives ||
|
|
!std::ranges::is_sorted(nursery_config.sites) ||
|
|
lives.size() > biology::max_cellular_tick_lives ||
|
|
corpses.size() > biology::max_archived_organisms ||
|
|
archive.recorded() !=
|
|
lives.size() + corpses.size() + (boundary ? boundary->nonresident_organisms.size() : 0))
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
if (std::ranges::any_of(heat.matter, [](const auto& value) { return value.value != 0; }))
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
|
|
const auto founder = biology::primitive_founder(1, 1);
|
|
if (!founder)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto founder_budget = biology::metabolic_budget(
|
|
*founder, {1000, 0}, {config.ambient_temperature_millikelvin, {}});
|
|
if (!founder_budget)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto spawn_extent = founder_budget->phenotype.extent;
|
|
for (std::size_t i = 0; i < nursery_config.sites.size(); ++i) {
|
|
const auto site = nursery_config.sites[i];
|
|
if (site.x_um < 0 || site.y_um < 0 || spawn_extent > config.area.width_um ||
|
|
spawn_extent > config.area.height_um ||
|
|
static_cast<std::uint64_t>(site.x_um) > config.area.width_um - spawn_extent ||
|
|
static_cast<std::uint64_t>(site.y_um) > config.area.height_um - spawn_extent)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
for (std::size_t j = 0; j < i; ++j) {
|
|
const auto delta_x = std::int64_t{site.x_um} - nursery_config.sites[j].x_um;
|
|
const auto delta_y = std::int64_t{site.y_um} - nursery_config.sites[j].y_um;
|
|
const auto dx = static_cast<std::uint64_t>(delta_x < 0 ? -delta_x : delta_x);
|
|
const auto dy = static_cast<std::uint64_t>(delta_y < 0 ? -delta_y : delta_y);
|
|
if (dx < spawn_extent && dy < spawn_extent)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
}
|
|
}
|
|
|
|
std::vector<std::uint64_t> live_organisms;
|
|
std::vector<std::uint64_t> life_ids;
|
|
live_organisms.reserve(lives.size());
|
|
life_ids.reserve(lives.size() + corpses.size() +
|
|
(boundary ? boundary->nonresident_organisms.size() : 0));
|
|
for (std::size_t i = 0; i < lives.size(); ++i) {
|
|
const auto& life = lives[i];
|
|
if (!plans && life.offspring_genome != 0)
|
|
return std::unexpected{CellularLivesError::version};
|
|
// Founders are owned; buds are unowned wildlife (rules 4) and never earn offers. Rules 13
|
|
// (ADR-0163 succession) moves control between parent and offspring, so ownership is the
|
|
// account's alone; bud identities still follow parentage.
|
|
const bool wildlife = life.parent_life != 0;
|
|
const bool owned = transfers ? life.account != LifeAccount{} : !wildlife;
|
|
// ADR-0128: only owned lives leave; a lingering life is within its linger time.
|
|
const bool presence_valid =
|
|
life.presence == CellularPresence::active
|
|
? life.frozen_since == 0
|
|
: presence_rules && owned && life.frozen_since != 0 &&
|
|
life.frozen_since <= config.tick &&
|
|
(life.presence == CellularPresence::suspended ||
|
|
(life.presence == CellularPresence::lingering &&
|
|
config.tick - life.frozen_since < cellular_linger_ticks));
|
|
if (!presence_valid)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if ((!transfers && (life.account == LifeAccount{}) != wildlife) ||
|
|
life.identity.life == 0 || life.identity.organism == 0 || life.identity.genome == 0 ||
|
|
life.identity.event == 0 || life.identity.born.value == 0 ||
|
|
life.identity.born.value > config.tick || life.source == 0 ||
|
|
(i != 0 && lives[i - 1].identity.life >= life.identity.life) ||
|
|
!lineage_valid(life.identity.life, life.parent_life) ||
|
|
(wildlife && (life.identity.organism != life.identity.life ||
|
|
life.identity.event != life.identity.life ||
|
|
life.mutation != CellularMutationProgress{})))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
for (std::size_t j = 0; j < i; ++j)
|
|
if ((owned && lives[j].account == life.account) ||
|
|
lives[j].identity.organism == life.identity.organism)
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
const auto record = archive.organism(life.identity.organism);
|
|
const auto current_genome = archive.current_genome(life.identity.organism);
|
|
if (!record || !record->alive || !current_genome ||
|
|
*current_genome != life.identity.genome || record->born != life.identity.born)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto budget = budget_for(archive, life, config.ambient_temperature_millikelvin);
|
|
if (!budget || budget->body != life.body || life.body.energy.value != 0 ||
|
|
budget->phenotype.extent == 0 || budget->phenotype.extent > config.area.width_um ||
|
|
budget->phenotype.extent > config.area.height_um ||
|
|
life.position.x_um > config.area.width_um - budget->phenotype.extent ||
|
|
life.position.y_um > config.area.height_um - budget->phenotype.extent)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
live_organisms.push_back(life.identity.organism);
|
|
life_ids.push_back(life.identity.life);
|
|
}
|
|
if (boundary) {
|
|
if (boundary->nonresident_organisms.size() > biology::max_archived_organisms ||
|
|
!std::ranges::is_sorted(boundary->nonresident_organisms) ||
|
|
std::ranges::adjacent_find(boundary->nonresident_organisms) !=
|
|
boundary->nonresident_organisms.end())
|
|
return std::unexpected(CellularLivesError::invalid_life);
|
|
for (const auto id : boundary->nonresident_organisms) {
|
|
if (id < cellular_bud_namespace || !lineage_valid(id, 1))
|
|
return std::unexpected(CellularLivesError::invalid_life);
|
|
const auto record = archive.organism(id);
|
|
if (!record || record->born.value > config.tick ||
|
|
(!record->alive && record->died.value > config.tick))
|
|
return std::unexpected(CellularLivesError::archive);
|
|
if (record->alive)
|
|
live_organisms.push_back(id);
|
|
life_ids.push_back(id);
|
|
}
|
|
}
|
|
std::ranges::sort(live_organisms);
|
|
if (archive.living_organisms() != live_organisms)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
|
|
for (std::size_t i = 0; i < corpses.size(); ++i) {
|
|
const auto& corpse = corpses[i];
|
|
if (!plans && corpse.offspring_genome != 0)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (corpse.life_id == 0 || corpse.organism == 0 || corpse.source == 0 ||
|
|
corpse.died_tick == 0 || corpse.died_tick > config.tick || corpse.extent_um == 0 ||
|
|
(i != 0 && corpses[i - 1].organism >= corpse.organism) ||
|
|
!lineage_valid(corpse.life_id, corpse.parent_life))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto record = archive.organism(corpse.organism);
|
|
if (!record || record->alive || record->died.value != corpse.died_tick)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto current_genome = archive.current_genome(corpse.organism);
|
|
if (!current_genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto genome = archive.find(*current_genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto budget = biology::metabolic_budget(*genome, corpse.growth,
|
|
{config.ambient_temperature_millikelvin, {}});
|
|
if (!budget || budget->phenotype.extent != corpse.extent_um ||
|
|
corpse.extent_um > config.area.width_um || corpse.extent_um > config.area.height_um ||
|
|
corpse.position.x_um > config.area.width_um - corpse.extent_um ||
|
|
corpse.position.y_um > config.area.height_um - corpse.extent_um)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (detritus_rules) {
|
|
// Rules 3 (ADR-0124): the inventory became detritus or the predator's.
|
|
if (corpse.inventory != accounting::Inventory{})
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
} else {
|
|
for (std::size_t channel = 0; channel < corpse.inventory.matter.size(); ++channel)
|
|
if (corpse.inventory.matter[channel].value < budget->body.matter[channel].value)
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
}
|
|
life_ids.push_back(corpse.life_id);
|
|
}
|
|
std::ranges::sort(life_ids);
|
|
if (std::ranges::adjacent_find(life_ids) != life_ids.end())
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
|
|
if (plans && !validate_plans(lives, corpses, archive, *plans, config.tick, transfers))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
auto current = sum_state(nursery, heat, habitat, lives, corpses);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
// Rules 13: the spent pool is region stock until it drips back.
|
|
if (!add_inventory(*current, spent))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
auto expected = opening_total;
|
|
if (boundary) {
|
|
accounting::Inventory credit{}, debit{};
|
|
const auto difference = [](std::uint64_t in, std::uint64_t out, std::uint64_t& plus,
|
|
std::uint64_t& minus) {
|
|
if (in >= out)
|
|
plus = in - out;
|
|
else
|
|
minus = out - in;
|
|
};
|
|
difference(boundary->incoming.energy.value, boundary->outgoing.energy.value,
|
|
credit.energy.value, debit.energy.value);
|
|
for (std::size_t channel = 0; channel < credit.matter.size(); ++channel)
|
|
difference(boundary->incoming.matter[channel].value,
|
|
boundary->outgoing.matter[channel].value, credit.matter[channel].value,
|
|
debit.matter[channel].value);
|
|
if (!add_inventory(expected, credit) || !subtract_inventory(expected, debit))
|
|
return std::unexpected(CellularLivesError::conservation);
|
|
}
|
|
if (*current != expected)
|
|
return std::unexpected{CellularLivesError::conservation};
|
|
return *current;
|
|
}
|
|
} // namespace
|
|
|
|
struct CellularLives::State {
|
|
std::uint64_t world{}, region{}, frame{};
|
|
std::uint32_t format_version{cellular_lives_format}, rules_version{cellular_lives_rules};
|
|
CellularLivesConfig config{};
|
|
NurseryConfig nursery_config{};
|
|
std::unique_ptr<biology::CellularHabitat> habitat;
|
|
std::vector<CellularOwnedLife> lives;
|
|
std::vector<CellularOwnedCorpse> corpses;
|
|
biology::LineageArchive archive;
|
|
accounting::Inventory nursery{};
|
|
accounting::Inventory heat{};
|
|
accounting::Inventory opening_total{};
|
|
accounting::Inventory current_total{};
|
|
std::uint64_t next_bud_sequence{1}; // Format 5: the next bud identity's sequence.
|
|
CellularBoundaryLedger boundary{};
|
|
std::vector<CellularOffspringRevision> offspring_revisions;
|
|
CellularLight light{}; // Format 9 (ADR-0175).
|
|
accounting::Picojoules captured{}; // Format 9: light credited to reserves so far.
|
|
CellularLiquidRules liquid{}; // Format 10 (rules 12).
|
|
CellularRevampRules revamp{}; // Format 11 (rules 13).
|
|
accounting::Inventory spent{}; // Format 11: matter and energy waiting to drip back.
|
|
std::shared_ptr<const biology::CellularFlowField> field; // Generated from `liquid`.
|
|
|
|
State(std::uint64_t world_id, std::uint64_t region_id, std::uint64_t frame_id,
|
|
CellularLivesConfig cfg, NurseryConfig nursery_definition,
|
|
std::unique_ptr<biology::CellularHabitat> map, std::vector<CellularOwnedLife> living,
|
|
std::vector<CellularOwnedCorpse> dead, const biology::LineageArchive& history,
|
|
accounting::Inventory source, accounting::Inventory accumulated_heat,
|
|
accounting::Inventory initial, accounting::Inventory current,
|
|
std::uint32_t format = cellular_lives_format, std::uint32_t rules = cellular_lives_rules,
|
|
CellularBoundaryLedger boundary_ledger = {})
|
|
: world{world_id}, region{region_id}, frame{frame_id}, format_version{format},
|
|
rules_version{rules}, config{cfg}, nursery_config{std::move(nursery_definition)},
|
|
habitat{std::move(map)}, lives{std::move(living)}, corpses{std::move(dead)},
|
|
archive{history}, nursery{source}, heat{accumulated_heat}, opening_total{initial},
|
|
current_total{current}, boundary{std::move(boundary_ledger)} {}
|
|
};
|
|
|
|
CellularLives::CellularLives(std::unique_ptr<State> state) : state_{std::move(state)} {}
|
|
CellularLives::~CellularLives() = default;
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::create(const PrimitiveLives& opening,
|
|
std::unique_ptr<biology::CellularHabitat> habitat, CellularLivesConfig config,
|
|
CellularLivesProfile profile) {
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto nursery_config = opening.config();
|
|
const auto& map = habitat->config();
|
|
if (nursery_config.world == 0 || nursery_config.region == 0 || nursery_config.frame == 0 ||
|
|
map.world != nursery_config.world || map.region != nursery_config.region ||
|
|
map.frame != nursery_config.frame || config.area.width_um == 0 ||
|
|
config.area.height_um == 0 || config.area.width_um != map.width_um ||
|
|
config.area.height_um != map.height_um || config.ambient_temperature_millikelvin == 0 ||
|
|
opening.lives().size() > biology::max_cellular_tick_lives ||
|
|
opening.balances().size() != 2 + 2 * nursery_config.sites.size())
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
|
|
std::vector<CellularOwnedLife> lives;
|
|
lives.reserve(opening.lives().size());
|
|
for (const auto& primitive : opening.lives()) {
|
|
if (primitive.identity.born.value == 0 || primitive.identity.born.value > config.tick ||
|
|
primitive.identity.life == 0 || primitive.identity.organism == 0 ||
|
|
primitive.identity.genome == 0 || primitive.source == 0 || primitive.site.x_um < 0 ||
|
|
primitive.site.y_um < 0)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (primitive.body.value == 0 || primitive.reserve.value == 0)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto body_index = static_cast<std::size_t>(primitive.body.value - 1);
|
|
const auto reserve_index = static_cast<std::size_t>(primitive.reserve.value - 1);
|
|
if (body_index >= opening.balances().size() || reserve_index >= opening.balances().size())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
lives.push_back({primitive.request.account,
|
|
primitive.identity,
|
|
primitive.source,
|
|
primitive.growth,
|
|
{static_cast<std::uint64_t>(primitive.site.x_um),
|
|
static_cast<std::uint64_t>(primitive.site.y_um)},
|
|
opening.balances()[body_index],
|
|
opening.balances()[reserve_index]});
|
|
}
|
|
auto archive = opening.archive();
|
|
std::ranges::sort(lives, {}, [](const auto& life) { return life.identity.life; });
|
|
for (std::size_t i = 0; i < lives.size(); ++i) {
|
|
const auto& life = lives[i];
|
|
if (i != 0 && lives[i - 1].identity.life == life.identity.life)
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
const auto budget = budget_for(archive, life, config.ambient_temperature_millikelvin);
|
|
if (!budget || budget->phenotype.extent == 0 ||
|
|
budget->phenotype.extent > config.area.width_um ||
|
|
budget->phenotype.extent > config.area.height_um || life.body.energy.value != 0 ||
|
|
budget->body != life.body ||
|
|
life.position.x_um > config.area.width_um - budget->phenotype.extent ||
|
|
life.position.y_um > config.area.height_um - budget->phenotype.extent)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
}
|
|
auto opening_total = opening.totals();
|
|
if (!add_inventory(opening_total, habitat->totals()))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
const auto nursery = opening.balances()[0];
|
|
nursery_config.funding = nursery;
|
|
const auto heat = opening.balances()[1];
|
|
const auto current =
|
|
validate_state(nursery_config.world, nursery_config.region, nursery_config.frame, config,
|
|
nursery_config, *habitat, lives, {}, archive, nursery, heat, opening_total);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
const auto world = nursery_config.world;
|
|
const auto region = nursery_config.region;
|
|
const auto frame = nursery_config.frame;
|
|
const bool foraging = profile == CellularLivesProfile::foraging; // Rules 8.
|
|
// A rules-8 opening needs a deposit habitat, and only it may have one.
|
|
if (foraging != (habitat->config().format == biology::cellular_habitat_deposit_format))
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const bool reproduction = profile == CellularLivesProfile::reproduction || foraging;
|
|
const bool balance = profile == CellularLivesProfile::balance || reproduction; // Rules 6+.
|
|
const bool presence = profile == CellularLivesProfile::presence || balance;
|
|
const bool budding = profile == CellularLivesProfile::budding || presence;
|
|
const bool engulf = profile == CellularLivesProfile::engulf || budding;
|
|
if (engulf)
|
|
archive.upgrade_to_revision_format(); // Rules 3+ regions carry genome revisions.
|
|
auto state = std::make_unique<State>(world, region, frame, config, std::move(nursery_config),
|
|
std::move(habitat), std::move(lives),
|
|
std::vector<CellularOwnedCorpse>{}, archive, nursery, heat,
|
|
opening_total, *current,
|
|
presence ? cellular_lives_presence_format
|
|
: budding ? cellular_lives_bud_format
|
|
: engulf ? cellular_lives_engulf_format
|
|
: cellular_lives_format,
|
|
foraging ? cellular_lives_foraging_rules
|
|
: reproduction ? cellular_lives_reproduction_rules
|
|
: balance ? cellular_lives_balance_rules
|
|
: presence ? cellular_lives_presence_rules
|
|
: budding ? cellular_lives_bud_rules
|
|
: engulf ? cellular_lives_engulf_rules
|
|
: cellular_lives_rules);
|
|
return std::unique_ptr<CellularLives>{new CellularLives{std::move(state)}};
|
|
}
|
|
|
|
std::expected<biology::Genome, CellularLivesError>
|
|
cellular_organism_genome(const biology::Genome& genome, std::uint32_t members) {
|
|
return organism_genome(genome, members);
|
|
}
|
|
|
|
bool cellular_can_emerge(const CellularOwnedLife& life, const CellularRevampRules& rules) noexcept {
|
|
std::uint64_t mass{};
|
|
for (std::size_t c = 0; c < life.body.matter.size(); ++c)
|
|
mass += life.body.matter[c].value + life.reserve.matter[c].value;
|
|
return life.account != LifeAccount{} && life.revamp.members >= rules.emerge_members &&
|
|
mass >= rules.emerge_mass_fg && life.reserve.energy.value >= rules.emerge_reserve_pj;
|
|
}
|
|
|
|
bool cellular_twin_bud(std::uint64_t world, std::uint64_t region, std::uint64_t parent_life,
|
|
std::uint64_t tick, std::uint32_t reproduction) noexcept {
|
|
// Its own stream: the parent and tick hashed with a twin-only salt ("twin").
|
|
constexpr std::uint64_t twin_stream = 0x7477696eULL;
|
|
const auto roll = mutation_seed(world, region, parent_life, tick ^ (twin_stream << 32U));
|
|
return roll % 1000 < std::min<std::uint32_t>(reproduction, 1000) / 2;
|
|
}
|
|
|
|
std::uint64_t CellularLives::world() const noexcept {
|
|
return state_->world;
|
|
}
|
|
std::uint64_t CellularLives::region() const noexcept {
|
|
return state_->region;
|
|
}
|
|
std::uint64_t CellularLives::frame() const noexcept {
|
|
return state_->frame;
|
|
}
|
|
std::uint64_t CellularLives::tick() const noexcept {
|
|
return state_->config.tick;
|
|
}
|
|
std::uint32_t CellularLives::format_version() const noexcept {
|
|
return state_->format_version;
|
|
}
|
|
std::uint32_t CellularLives::rules_version() const noexcept {
|
|
return state_->rules_version;
|
|
}
|
|
std::uint64_t CellularLives::next_bud_sequence() const noexcept {
|
|
return state_->next_bud_sequence;
|
|
}
|
|
std::uint32_t CellularLives::ambient_temperature_millikelvin() const noexcept {
|
|
return state_->config.ambient_temperature_millikelvin;
|
|
}
|
|
biology::CellularArea CellularLives::area() const noexcept {
|
|
return state_->config.area;
|
|
}
|
|
std::span<const CellularOwnedLife> CellularLives::lives() const noexcept {
|
|
return state_->lives;
|
|
}
|
|
std::span<const CellularOwnedCorpse> CellularLives::corpses() const noexcept {
|
|
return state_->corpses;
|
|
}
|
|
const biology::CellularHabitat& CellularLives::habitat() const noexcept {
|
|
return *state_->habitat;
|
|
}
|
|
const biology::LineageArchive& CellularLives::archive() const noexcept {
|
|
return state_->archive;
|
|
}
|
|
accounting::Inventory CellularLives::nursery() const noexcept {
|
|
return state_->nursery;
|
|
}
|
|
accounting::Inventory CellularLives::heat() const noexcept {
|
|
return state_->heat;
|
|
}
|
|
accounting::Inventory CellularLives::spent() const noexcept {
|
|
return state_->spent;
|
|
}
|
|
accounting::Inventory CellularLives::opening_total() const noexcept {
|
|
return state_->opening_total;
|
|
}
|
|
accounting::Inventory CellularLives::current_total() const noexcept {
|
|
return state_->current_total;
|
|
}
|
|
const CellularBoundaryLedger& CellularLives::boundary_ledger() const noexcept {
|
|
return state_->boundary;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migration_replacement(std::vector<CellularOwnedLife> living,
|
|
const biology::LineageArchive& archive,
|
|
CellularBoundaryLedger boundary) const {
|
|
if ((state_->rules_version != cellular_lives_foraging_rules &&
|
|
!(state_->rules_version == cellular_lives_maturation_rules &&
|
|
state_->format_version == cellular_lives_migration_format)) ||
|
|
(state_->format_version != cellular_lives_presence_format &&
|
|
state_->format_version != cellular_lives_migration_format))
|
|
return std::unexpected(CellularLivesError::version);
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected(CellularLivesError::habitat);
|
|
const auto total = validate_state(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
**habitat, living, state_->corpses, archive, state_->nursery, state_->heat,
|
|
state_->opening_total, true, true, state_->next_bud_sequence, true, &boundary, nullptr,
|
|
state_->spent, state_->rules_version >= cellular_lives_revamp_rules);
|
|
if (!total)
|
|
return std::unexpected(total.error());
|
|
auto replacement = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
std::move(*habitat), std::move(living), state_->corpses, archive, state_->nursery,
|
|
state_->heat, state_->opening_total, *total, cellular_lives_migration_format,
|
|
state_->rules_version, std::move(boundary))}};
|
|
replacement->state_->next_bud_sequence = state_->next_bud_sequence;
|
|
try {
|
|
[[maybe_unused]] const auto bytes = replacement->snapshot();
|
|
} catch (const std::length_error&) {
|
|
return std::unexpected(CellularLivesError::overflow);
|
|
}
|
|
return replacement;
|
|
}
|
|
|
|
std::expected<CellularLives::BoundarySavepoint, CellularLivesError>
|
|
CellularLives::exchange_boundary(std::span<const biology::CellularPatch> deposits,
|
|
accounting::Picojoules heat_export) {
|
|
if (state_->format_version < cellular_lives_migration_format)
|
|
return std::unexpected(CellularLivesError::version);
|
|
if (heat_export.value > state_->heat.energy.value)
|
|
return std::unexpected(CellularLivesError::conservation);
|
|
auto boundary = state_->boundary;
|
|
auto heat = state_->heat;
|
|
heat.energy.value -= heat_export.value;
|
|
if (heat_export.value >
|
|
std::numeric_limits<std::uint64_t>::max() - boundary.outgoing.energy.value)
|
|
return std::unexpected(CellularLivesError::overflow);
|
|
boundary.outgoing.energy.value += heat_export.value;
|
|
if (deposits.empty()) {
|
|
// Heat alone: the total falls by exactly the recorded export, so closure holds.
|
|
BoundarySavepoint savepoint{nullptr, state_->heat, state_->current_total, state_->boundary};
|
|
state_->heat = heat;
|
|
state_->current_total.energy.value -= heat_export.value;
|
|
state_->boundary = std::move(boundary);
|
|
return savepoint;
|
|
}
|
|
std::unique_ptr<biology::CellularHabitat> habitat;
|
|
{
|
|
auto config = state_->habitat->config();
|
|
if (config.format != biology::cellular_habitat_deposit_format)
|
|
return std::unexpected(CellularLivesError::version);
|
|
for (auto deposit : deposits) {
|
|
if (config.next_deposit == std::numeric_limits<std::uint32_t>::max() ||
|
|
deposit.stock == accounting::Inventory{} ||
|
|
!add_inventory(boundary.incoming, deposit.stock))
|
|
return std::unexpected(CellularLivesError::overflow);
|
|
deposit.id = config.next_deposit++;
|
|
const auto at = std::ranges::lower_bound(config.patches, deposit.address, {},
|
|
&biology::CellularPatch::address);
|
|
if (at != config.patches.end() && at->address == deposit.address)
|
|
return std::unexpected(CellularLivesError::habitat);
|
|
config.patches.insert(at, deposit);
|
|
}
|
|
auto created = biology::CellularHabitat::create(std::move(config));
|
|
if (!created)
|
|
return std::unexpected(CellularLivesError::habitat);
|
|
habitat = std::move(*created);
|
|
}
|
|
const auto rules = state_->rules_version;
|
|
const auto total =
|
|
validate_state(state_->world, state_->region, state_->frame, state_->config,
|
|
state_->nursery_config, *habitat, state_->lives, state_->corpses,
|
|
state_->archive, state_->nursery, heat, state_->opening_total,
|
|
rules >= cellular_lives_engulf_rules, rules >= cellular_lives_bud_rules,
|
|
state_->next_bud_sequence, rules >= cellular_lives_presence_rules, &boundary,
|
|
cellular_retained_plans(rules) ? &state_->offspring_revisions : nullptr,
|
|
state_->spent, state_->rules_version >= cellular_lives_revamp_rules);
|
|
if (!total)
|
|
return std::unexpected(total.error());
|
|
BoundarySavepoint savepoint{std::move(state_->habitat), state_->heat, state_->current_total,
|
|
state_->boundary};
|
|
state_->habitat = std::move(habitat);
|
|
state_->heat = heat;
|
|
state_->current_total = *total;
|
|
state_->boundary = std::move(boundary);
|
|
return savepoint;
|
|
}
|
|
void CellularLives::restore_boundary(BoundarySavepoint savepoint) noexcept {
|
|
if (savepoint.habitat)
|
|
state_->habitat = std::move(savepoint.habitat);
|
|
state_->heat = savepoint.heat;
|
|
state_->current_total = savepoint.current_total;
|
|
state_->boundary = std::move(savepoint.boundary);
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migration_upgrade_candidate() const {
|
|
if (state_->rules_version != cellular_lives_foraging_rules)
|
|
return std::unexpected(CellularLivesError::version);
|
|
return migration_replacement(state_->lives, state_->archive, state_->boundary);
|
|
}
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::maturation_upgrade_candidate() const {
|
|
if (state_->format_version != cellular_lives_migration_format ||
|
|
state_->rules_version != cellular_lives_foraging_rules)
|
|
return std::unexpected(CellularLivesError::version);
|
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
|
if (!candidate)
|
|
return std::unexpected(candidate.error());
|
|
(*candidate)->state_->rules_version = cellular_lives_maturation_rules;
|
|
return candidate;
|
|
}
|
|
std::span<const CellularLifeTickFeedback> CellularLives::last_tick_feedback() const noexcept {
|
|
return last_tick_feedback_;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::photosynthesis_upgrade_candidate(CellularLight light) const {
|
|
if (state_->format_version != cellular_lives_inheritance_format ||
|
|
state_->rules_version != cellular_lives_inheritance_rules)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (!cellular_light_valid(light))
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
|
if (!candidate)
|
|
return std::unexpected(candidate.error());
|
|
(*candidate)->state_->format_version = cellular_lives_light_format;
|
|
(*candidate)->state_->rules_version = cellular_lives_photosynthesis_rules;
|
|
(*candidate)->state_->light = light;
|
|
return candidate;
|
|
}
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::liquid_upgrade_candidate(const CellularLiquidRules& rules) const {
|
|
if (state_->format_version != cellular_lives_light_format ||
|
|
state_->rules_version != cellular_lives_photosynthesis_rules)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (!cellular_liquid_valid(rules, state_->config.area))
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto field = biology::CellularFlowField::shared(rules.currents);
|
|
if (!field)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto config = state_->habitat->config();
|
|
if (config.format != biology::cellular_habitat_deposit_format ||
|
|
config.patches.size() > biology::max_cellular_liquid_deposits)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
config.format = biology::cellular_habitat_liquid_format;
|
|
for (auto& patch : config.patches)
|
|
patch.merged = 1;
|
|
auto habitat = biology::CellularHabitat::create(std::move(config));
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
|
if (!candidate)
|
|
return std::unexpected(candidate.error());
|
|
auto& next = *(*candidate)->state_;
|
|
next.habitat = std::move(*habitat);
|
|
next.format_version = cellular_lives_liquid_format;
|
|
next.rules_version = cellular_lives_liquid_rules;
|
|
next.liquid = rules;
|
|
next.field = std::move(*field);
|
|
for (auto& life : next.lives)
|
|
life.motion = {};
|
|
return candidate;
|
|
}
|
|
const CellularLiquidRules& CellularLives::liquid_rules() const noexcept {
|
|
return state_->liquid;
|
|
}
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::revamp_upgrade_candidate(const CellularRevampRules& rules) const {
|
|
if (state_->format_version != cellular_lives_liquid_format ||
|
|
state_->rules_version != cellular_lives_liquid_rules)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (!cellular_revamp_valid(rules))
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
|
if (!candidate)
|
|
return std::unexpected(candidate.error());
|
|
auto& next = *(*candidate)->state_;
|
|
next.format_version = cellular_lives_revamp_format;
|
|
next.rules_version = cellular_lives_revamp_rules;
|
|
next.revamp = rules;
|
|
return candidate;
|
|
}
|
|
const CellularRevampRules& CellularLives::revamp_rules() const noexcept {
|
|
return state_->revamp;
|
|
}
|
|
const biology::CellularFlowField* CellularLives::flow_field() const noexcept {
|
|
return state_->field.get();
|
|
}
|
|
const CellularLight& CellularLives::light() const noexcept {
|
|
return state_->light;
|
|
}
|
|
accounting::Picojoules CellularLives::captured_light() const noexcept {
|
|
return state_->captured;
|
|
}
|
|
std::span<const CellularOffspringRevision> CellularLives::offspring_revisions() const noexcept {
|
|
return state_->offspring_revisions;
|
|
}
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::inheritance_upgrade_candidate() const {
|
|
if (state_->format_version != cellular_lives_migration_format ||
|
|
state_->rules_version != cellular_lives_maturation_rules)
|
|
return std::unexpected{CellularLivesError::version};
|
|
auto candidate = restore(snapshot(), world(), region(), frame(), tick());
|
|
if (!candidate)
|
|
return std::unexpected(candidate.error());
|
|
auto& next = *(*candidate)->state_;
|
|
next.format_version = cellular_lives_inheritance_format;
|
|
next.rules_version = cellular_lives_inheritance_rules;
|
|
for (auto& life : next.lives)
|
|
life.offspring_genome = life.identity.genome;
|
|
for (auto& corpse : next.corpses) {
|
|
const auto genome = next.archive.current_genome(corpse.organism);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
corpse.offspring_genome = *genome;
|
|
}
|
|
return restore((*candidate)->snapshot(), world(), region(), frame(), tick());
|
|
}
|
|
|
|
std::vector<std::uint8_t> CellularLives::snapshot() const {
|
|
const auto habitat = state_->habitat->snapshot();
|
|
const auto archive = state_->archive.encode();
|
|
const auto site_count = state_->nursery_config.sites.size();
|
|
const auto life_count = state_->lives.size();
|
|
const auto corpse_count = state_->corpses.size();
|
|
const bool parents = state_->format_version >= cellular_lives_bud_format;
|
|
const bool presence = state_->format_version >= cellular_lives_presence_format;
|
|
const bool inheritance = state_->format_version >= cellular_lives_inheritance_format;
|
|
const bool lit = state_->format_version >= cellular_lives_light_format;
|
|
// Format 11 is format 10 with the revamp rules.
|
|
const bool revamp = state_->format_version == cellular_lives_revamp_format;
|
|
const bool liquid = revamp || state_->format_version == cellular_lives_liquid_format;
|
|
const auto life_bytes =
|
|
revamp
|
|
? cellular_life_v6_bytes + 8 + cellular_life_motion_bytes + cellular_life_revamp_bytes
|
|
: liquid ? cellular_life_v6_bytes + 8 + cellular_life_motion_bytes
|
|
: inheritance ? cellular_life_v6_bytes + 8
|
|
: state_->format_version == cellular_lives_legacy_format ? cellular_life_v1_bytes
|
|
: presence ? cellular_life_v6_bytes
|
|
: parents ? cellular_life_v5_bytes
|
|
: cellular_life_v2_bytes;
|
|
const bool causes = state_->format_version >= cellular_lives_engulf_format;
|
|
const auto corpse_bytes = inheritance ? cellular_corpse_v5_bytes + 8
|
|
: parents ? cellular_corpse_v5_bytes
|
|
: causes ? cellular_corpse_v4_bytes
|
|
: cellular_corpse_bytes;
|
|
const bool migration = state_->format_version >= cellular_lives_migration_format;
|
|
const auto header_bytes = revamp ? cellular_lives_v11_header_bytes
|
|
: liquid ? cellular_lives_v10_header_bytes
|
|
: lit ? cellular_lives_v9_header_bytes
|
|
: inheritance ? cellular_lives_v8_header_bytes
|
|
: migration ? cellular_lives_v7_header_bytes
|
|
: parents ? cellular_lives_v5_header_bytes
|
|
: cellular_lives_header_bytes;
|
|
const auto external_count = migration ? state_->boundary.nonresident_organisms.size() : 0;
|
|
const auto total_bytes =
|
|
header_bytes + cellular_site_bytes * site_count + life_bytes * life_count +
|
|
corpse_bytes * corpse_count + habitat.size() + archive.size() + external_count * 8 +
|
|
state_->offspring_revisions.size() * cellular_offspring_revision_bytes + 8;
|
|
if (total_bytes > max_cellular_lives_bytes ||
|
|
habitat.size() > biology::max_cellular_habitat_bytes ||
|
|
archive.size() > biology::max_archive_bytes || site_count > max_primitive_lives ||
|
|
life_count > biology::max_cellular_tick_lives ||
|
|
corpse_count > biology::max_archived_organisms ||
|
|
external_count > biology::max_archived_organisms ||
|
|
state_->offspring_revisions.size() > biology::max_archived_genomes ||
|
|
(!inheritance && !state_->offspring_revisions.empty()))
|
|
throw std::length_error{"cellular lives checkpoint exceeds its format bounds"};
|
|
|
|
std::vector<std::uint8_t> bytes;
|
|
bytes.reserve(total_bytes);
|
|
Writer out{bytes};
|
|
const auto magic =
|
|
state_->format_version == cellular_lives_legacy_format ? cellular_lives_v1_magic
|
|
: state_->format_version == cellular_lives_revision_format ? cellular_lives_v3_magic
|
|
: state_->format_version == cellular_lives_engulf_format ? cellular_lives_v4_magic
|
|
: state_->format_version == cellular_lives_bud_format ? cellular_lives_v5_magic
|
|
: state_->format_version == cellular_lives_presence_format ? cellular_lives_v6_magic
|
|
: revamp ? cellular_lives_v11_magic
|
|
: liquid ? cellular_lives_v10_magic
|
|
: lit ? cellular_lives_v9_magic
|
|
: inheritance ? cellular_lives_v8_magic
|
|
: migration ? cellular_lives_v7_magic
|
|
: cellular_lives_v2_magic;
|
|
out.put(magic);
|
|
out.put(state_->format_version, 4);
|
|
out.put(state_->rules_version, 4);
|
|
out.put(state_->world);
|
|
out.put(state_->region);
|
|
out.put(state_->frame);
|
|
out.put(state_->config.tick);
|
|
out.put(state_->config.area.width_um, 4);
|
|
out.put(state_->config.area.height_um, 4);
|
|
out.put(state_->config.ambient_temperature_millikelvin, 4);
|
|
out.put(site_count, 4);
|
|
out.put(life_count, 4);
|
|
out.put(corpse_count, 4);
|
|
out.put(habitat.size(), 4);
|
|
out.put(archive.size(), 4);
|
|
out.put(0, 4);
|
|
out.put(state_->nursery_config.source);
|
|
out.inventory(state_->opening_total);
|
|
out.inventory(state_->nursery);
|
|
out.inventory(state_->heat);
|
|
if (parents)
|
|
out.put(state_->next_bud_sequence);
|
|
if (migration) {
|
|
out.inventory(state_->boundary.incoming);
|
|
out.inventory(state_->boundary.outgoing);
|
|
out.put(external_count, 4);
|
|
out.put(0, 4);
|
|
}
|
|
if (inheritance) {
|
|
out.put(state_->offspring_revisions.size(), 4);
|
|
out.put(0, 4);
|
|
}
|
|
if (lit) {
|
|
out.put(state_->light.numerator);
|
|
out.put(state_->light.denominator);
|
|
out.put(state_->light.entitlement.value);
|
|
out.put(state_->light.moving_per_thousand, 4);
|
|
out.put(0, 4);
|
|
out.put(state_->captured.value);
|
|
}
|
|
if (liquid) {
|
|
const auto& c = state_->liquid.currents;
|
|
const auto& f = state_->liquid.founder;
|
|
const auto& d = state_->liquid.deposits;
|
|
out.put(c.seed);
|
|
for (const auto value :
|
|
{c.width_um, c.height_um, c.pitch_um, c.min_count, c.max_count, c.min_route_width_um,
|
|
c.max_route_width_um, c.min_speed_um_per_s, c.max_speed_um_per_s})
|
|
out.put(value, 4);
|
|
for (const auto value : {f.thrust_q10, f.reverse_thrust_q10, f.forward_drag_ppm,
|
|
f.lateral_drag_ppm, static_cast<std::uint32_t>(f.turn)})
|
|
out.put(value, 4);
|
|
out.put(d.drift_radius_um, 4);
|
|
out.put(static_cast<std::uint32_t>(d.max_drift_q10), 4);
|
|
out.put(d.drift_decay_ppm, 4);
|
|
out.put(d.merged_cap, 4);
|
|
out.put(d.bubble_radius_um, 4);
|
|
// Thrust cost share; zero stands for the original 1,000 per mille.
|
|
const auto cost = state_->liquid.thrust_cost_per_mille;
|
|
out.put(cost == 1'000 ? 0 : cost, 4);
|
|
}
|
|
if (revamp) {
|
|
const auto& r = state_->revamp;
|
|
out.put(r.body.essential_upkeep_per_thousand, 4);
|
|
out.put(0, 4);
|
|
for (const auto rate : r.burn_pj_per_kfg)
|
|
out.put(rate);
|
|
out.put(r.step.membrane_collection_per_mille_per_point, 4);
|
|
out.put(r.step.engulf_ratio_milli, 4);
|
|
out.put(r.step.engulf_reserve_percent, 4);
|
|
out.put(r.step.kill_bubble_per_thousand, 4);
|
|
out.put(r.drip_interval_ticks, 4);
|
|
out.put(r.reserve_load_per_thousand, 4);
|
|
out.put(r.drip_bubble_pj);
|
|
out.put(r.drip_bubble_fg);
|
|
out.inventory(state_->spent);
|
|
write_revamp_offers(out, r);
|
|
}
|
|
for (const auto site : state_->nursery_config.sites)
|
|
out.site(site);
|
|
for (const auto& life : state_->lives) {
|
|
out.bytes(life.account);
|
|
out.put(life.identity.life);
|
|
out.put(life.identity.organism);
|
|
out.put(life.identity.genome);
|
|
out.put(life.identity.event);
|
|
out.put(life.identity.born.value);
|
|
out.put(life.source);
|
|
out.put(life.growth.realized_per_thousand, 4);
|
|
out.put(life.growth.damage_per_thousand, 4);
|
|
out.put(life.position.x_um);
|
|
out.put(life.position.y_um);
|
|
out.inventory(life.body);
|
|
out.inventory(life.reserve);
|
|
if (state_->format_version >= cellular_lives_format) {
|
|
const auto& mutation = life.mutation;
|
|
out.put(mutation.fed_energy_credit_pj);
|
|
out.put(mutation.event_index);
|
|
out.put(mutation.offer_tick);
|
|
out.put(mutation.offer ? mutation.offer->parent : 0);
|
|
out.put(mutation.offer ? mutation.offer->parent_digest : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.seed : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.stream : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.event_index : 0);
|
|
out.put(mutation.offer ? mutation.offer->context.candidate_count : 0, 2);
|
|
out.put(0, 2);
|
|
out.put(mutation.offer ? mutation.offer->context.growth.realized_per_thousand : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.growth.damage_per_thousand : 0, 4);
|
|
out.put(mutation.offer ? mutation.offer->context.environment.temperature_millikelvin
|
|
: 0,
|
|
4);
|
|
out.put(0, 4);
|
|
out.inventory(mutation.offer ? mutation.offer->context.environment.available
|
|
: accounting::Inventory{});
|
|
for (std::size_t index = 0; index < biology::max_candidates; ++index) {
|
|
if (mutation.offer && index < mutation.offer->candidates.size()) {
|
|
const auto& candidates = mutation.offer.value().candidates;
|
|
const auto& candidate = candidates[index];
|
|
out.put(candidate.operator_id, 2);
|
|
out.put(static_cast<std::uint8_t>(candidate.target), 1);
|
|
out.put(static_cast<std::uint8_t>(candidate.effect), 1);
|
|
out.put(candidate.parameter, 4);
|
|
out.put(candidate.maintenance);
|
|
out.put(candidate.total_mass);
|
|
} else {
|
|
out.zeros(24);
|
|
}
|
|
}
|
|
}
|
|
if (parents)
|
|
out.put(life.parent_life);
|
|
if (presence) {
|
|
out.put(static_cast<std::uint8_t>(life.presence), 1);
|
|
out.zeros(7);
|
|
out.put(life.frozen_since);
|
|
}
|
|
if (inheritance)
|
|
out.put(life.offspring_genome);
|
|
if (liquid) {
|
|
out.put(static_cast<std::uint32_t>(life.motion.velocity_x_q10), 4);
|
|
out.put(static_cast<std::uint32_t>(life.motion.velocity_y_q10), 4);
|
|
out.put(life.motion.heading, 2);
|
|
out.put(0, 2);
|
|
out.put(static_cast<std::uint64_t>(life.motion.remainder_x), 4);
|
|
out.put(static_cast<std::uint64_t>(life.motion.remainder_y), 4);
|
|
}
|
|
if (revamp)
|
|
write_revamp_life(out, life.revamp);
|
|
}
|
|
for (const auto& corpse : state_->corpses) {
|
|
out.put(corpse.life_id);
|
|
out.put(corpse.organism);
|
|
out.put(corpse.source);
|
|
out.put(corpse.died_tick);
|
|
out.put(corpse.position.x_um);
|
|
out.put(corpse.position.y_um);
|
|
out.put(corpse.growth.realized_per_thousand, 4);
|
|
out.put(corpse.growth.damage_per_thousand, 4);
|
|
out.put(corpse.extent_um, 4);
|
|
out.inventory(corpse.inventory);
|
|
if (causes) {
|
|
out.put(static_cast<std::uint8_t>(corpse.cause), 1);
|
|
out.zeros(7);
|
|
out.put(corpse.predator_life);
|
|
}
|
|
if (parents)
|
|
out.put(corpse.parent_life);
|
|
if (inheritance)
|
|
out.put(corpse.offspring_genome);
|
|
}
|
|
out.raw(habitat);
|
|
out.raw(archive);
|
|
if (migration)
|
|
for (const auto id : state_->boundary.nonresident_organisms)
|
|
out.put(id);
|
|
if (inheritance)
|
|
for (const auto& revision : state_->offspring_revisions) {
|
|
out.put(revision.life);
|
|
out.put(revision.previous);
|
|
out.put(revision.successor);
|
|
out.put(revision.tick);
|
|
}
|
|
if (bytes.size() + 8 != total_bytes)
|
|
throw std::logic_error{"cellular lives checkpoint size calculation mismatch"};
|
|
out.put(checksum(bytes));
|
|
return bytes;
|
|
}
|
|
|
|
std::expected<std::vector<biology::CellularPatchPerception>, CellularLivesError>
|
|
CellularLives::perceive(std::uint64_t life_id) const {
|
|
const auto life = std::ranges::find(state_->lives, life_id,
|
|
[](const auto& owned) { return owned.identity.life; });
|
|
if (life == state_->lives.end())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
const auto budget =
|
|
budget_for(state_->archive, *life, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
auto view = state_->habitat->perceive(life->position, budget->phenotype.extent);
|
|
if (!view)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
return std::move(*view);
|
|
}
|
|
|
|
std::expected<std::optional<biology::MutationOffer>, CellularLivesError>
|
|
CellularLives::mutation_offer(std::uint64_t life_id) const {
|
|
const auto life = std::ranges::find(state_->lives, life_id,
|
|
[](const auto& owned) { return owned.identity.life; });
|
|
if (life == state_->lives.end())
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
return life->mutation.offer;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migrate_to_v2() const {
|
|
if (state_->format_version != cellular_lives_legacy_format || state_->rules_version != 1)
|
|
return std::unexpected{CellularLivesError::version};
|
|
auto lives = state_->lives;
|
|
for (auto& life : lives)
|
|
life.mutation = {};
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
std::move(*habitat), std::move(lives), state_->corpses, state_->archive, state_->nursery,
|
|
state_->heat, state_->opening_total, state_->current_total, cellular_lives_format,
|
|
cellular_lives_rules)}};
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::migrate_to_v3() const {
|
|
if (state_->format_version != cellular_lives_format ||
|
|
state_->rules_version != cellular_lives_rules ||
|
|
state_->archive.format_version() != biology::lineage_archive_format)
|
|
return std::unexpected{CellularLivesError::version};
|
|
auto archive = state_->archive;
|
|
archive.upgrade_to_revision_format();
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto current =
|
|
validate_state(state_->world, state_->region, state_->frame, state_->config,
|
|
state_->nursery_config, **habitat, state_->lives, state_->corpses, archive,
|
|
state_->nursery, state_->heat, state_->opening_total);
|
|
if (!current || *current != state_->current_total)
|
|
return std::unexpected{current ? CellularLivesError::conservation : current.error()};
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, state_->nursery_config,
|
|
std::move(*habitat), state_->lives, state_->corpses, archive, state_->nursery, state_->heat,
|
|
state_->opening_total, state_->current_total, cellular_lives_revision_format,
|
|
cellular_lives_rules)}};
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) const {
|
|
if (request.action == 0 ||
|
|
std::ranges::all_of(request.account, [](std::uint8_t value) { return value == 0; }))
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
if (allocation.life == 0 || allocation.life != allocation.organism ||
|
|
allocation.life != allocation.genome || allocation.life != allocation.event)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
if (allocation.born.value == 0 || allocation.born.value != state_->config.tick)
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
if (state_->lives.size() >= biology::max_cellular_tick_lives)
|
|
return std::unexpected{CellularLivesError::no_placement};
|
|
if (std::ranges::any_of(state_->lives, [&](const CellularOwnedLife& life) {
|
|
return life.account == request.account;
|
|
}))
|
|
return std::unexpected{CellularLivesError::life_exists};
|
|
if (std::ranges::any_of(state_->lives,
|
|
[&](const CellularOwnedLife& life) {
|
|
return life.identity.life == allocation.life ||
|
|
life.identity.organism == allocation.organism ||
|
|
life.identity.genome == allocation.genome ||
|
|
life.identity.event == allocation.event;
|
|
}) ||
|
|
std::ranges::any_of(state_->corpses,
|
|
[&](const CellularOwnedCorpse& corpse) {
|
|
return corpse.life_id == allocation.life ||
|
|
corpse.organism == allocation.organism;
|
|
}) ||
|
|
state_->archive.find(allocation.genome) || state_->archive.organism(allocation.organism))
|
|
return std::unexpected{CellularLivesError::duplicate_life};
|
|
|
|
// Rules 6 found version-2 founders: lower construction energy, finer mutations.
|
|
const auto founder_version = cellular_founder_version(state_->rules_version);
|
|
const auto endowed = biology::primitive_endowment(founder_version);
|
|
const auto genome =
|
|
biology::primitive_founder(allocation.genome, allocation.event, founder_version);
|
|
if (!endowed || !genome)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto budget = biology::metabolic_budget(
|
|
*genome, endowed->growth, {state_->config.ambient_temperature_millikelvin, {}});
|
|
if (!budget || budget->body != endowed->body)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
|
|
// Rules 12: a new founder starts at a seeded random spot anywhere in the region (1 mm
|
|
// clear of its edges), so starts spread out; the provisioned sites remain the fallback.
|
|
// Seeded by world, region and the life's identity, so replay places it identically.
|
|
std::vector<biology::CellularPosition> candidates;
|
|
if (state_->rules_version >= cellular_lives_liquid_rules) {
|
|
constexpr std::uint64_t margin = 1'000;
|
|
const auto& area = state_->config.area;
|
|
if (area.width_um > 2 * margin + budget->phenotype.extent &&
|
|
area.height_um > 2 * margin + budget->phenotype.extent) {
|
|
Random random{
|
|
mutation_seed(state_->world, state_->region, allocation.life, 0x5350574EU)};
|
|
const auto span_x = area.width_um - 2 * margin - budget->phenotype.extent;
|
|
const auto span_y = area.height_um - 2 * margin - budget->phenotype.extent;
|
|
for (int attempt = 0; attempt < 16; ++attempt)
|
|
candidates.push_back(
|
|
{margin + random.next() % span_x, margin + random.next() % span_y});
|
|
}
|
|
}
|
|
for (const auto site : state_->nursery_config.sites) {
|
|
if (site.x_um < 0 || site.y_um < 0)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
candidates.push_back(
|
|
{static_cast<std::uint64_t>(site.x_um), static_cast<std::uint64_t>(site.y_um)});
|
|
}
|
|
std::optional<biology::CellularPosition> position;
|
|
for (const auto candidate : candidates) {
|
|
bool occupied = false;
|
|
for (const auto& living : state_->lives) {
|
|
if (living.presence == CellularPresence::suspended)
|
|
continue; // Out of the world (ADR-0128).
|
|
const auto living_budget =
|
|
budget_for(state_->archive, living, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!living_budget)
|
|
return std::unexpected{living_budget.error()};
|
|
const auto separated = [](std::uint64_t left, std::uint64_t right,
|
|
std::uint32_t left_extent,
|
|
std::uint32_t right_extent) noexcept {
|
|
return left < right ? right - left >= left_extent : left - right >= right_extent;
|
|
};
|
|
if (!separated(candidate.x_um, living.position.x_um, budget->phenotype.extent,
|
|
living_budget->phenotype.extent) &&
|
|
!separated(candidate.y_um, living.position.y_um, budget->phenotype.extent,
|
|
living_budget->phenotype.extent)) {
|
|
occupied = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!occupied) {
|
|
position = candidate;
|
|
break;
|
|
}
|
|
}
|
|
if (!position)
|
|
return std::unexpected{CellularLivesError::no_placement};
|
|
|
|
auto nursery = state_->nursery;
|
|
if (!subtract_inventory(nursery, endowed->body) ||
|
|
!subtract_inventory(nursery, endowed->reserve) ||
|
|
endowed->construction.value > nursery.energy.value)
|
|
return std::unexpected{CellularLivesError::insufficient_funding};
|
|
nursery.energy.value -= endowed->construction.value;
|
|
auto heat = state_->heat;
|
|
if (endowed->construction.value > std::numeric_limits<std::uint64_t>::max() - heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
heat.energy.value += endowed->construction.value;
|
|
|
|
auto archive = state_->archive;
|
|
if (!archive.admit(*genome) ||
|
|
!archive.record_birth(allocation.organism, allocation.genome, allocation.born))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
auto lives = state_->lives;
|
|
lives.push_back({request.account, allocation, state_->nursery_config.source, endowed->growth,
|
|
*position, endowed->body, endowed->reserve});
|
|
if (state_->format_version >= cellular_lives_inheritance_format)
|
|
lives.back().offspring_genome = allocation.genome;
|
|
std::ranges::sort(lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; });
|
|
|
|
auto nursery_config = state_->nursery_config;
|
|
nursery_config.funding = nursery;
|
|
auto habitat = biology::CellularHabitat::restore(state_->habitat->snapshot(), state_->world,
|
|
state_->region, state_->frame);
|
|
if (!habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto current = validate_state(
|
|
state_->world, state_->region, state_->frame, state_->config, nursery_config, **habitat,
|
|
lives, state_->corpses, archive, nursery, heat, state_->opening_total,
|
|
state_->rules_version >= cellular_lives_engulf_rules,
|
|
state_->rules_version >= cellular_lives_bud_rules, state_->next_bud_sequence,
|
|
state_->rules_version >= cellular_lives_presence_rules,
|
|
state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr,
|
|
state_->format_version >= cellular_lives_inheritance_format ? &state_->offspring_revisions
|
|
: nullptr,
|
|
state_->spent, state_->rules_version >= cellular_lives_revamp_rules);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
auto candidate = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame, state_->config, std::move(nursery_config),
|
|
std::move(*habitat), std::move(lives), state_->corpses, archive, nursery, heat,
|
|
state_->opening_total, *current, state_->format_version, state_->rules_version,
|
|
state_->boundary)}};
|
|
candidate->last_tick_feedback_ = last_tick_feedback_;
|
|
candidate->state_->next_bud_sequence = state_->next_bud_sequence;
|
|
candidate->state_->offspring_revisions = state_->offspring_revisions;
|
|
candidate->state_->light = state_->light;
|
|
candidate->state_->captured = state_->captured;
|
|
candidate->state_->liquid = state_->liquid;
|
|
candidate->state_->field = state_->field;
|
|
candidate->state_->revamp = state_->revamp;
|
|
candidate->state_->spent = state_->spent;
|
|
return candidate;
|
|
}
|
|
|
|
std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
|
|
CellularLives::restore(std::span<const std::uint8_t> bytes, std::uint64_t world,
|
|
std::uint64_t region, std::uint64_t frame, std::uint64_t tick) {
|
|
if (bytes.size() < cellular_lives_header_bytes + 8 || bytes.size() > max_cellular_lives_bytes)
|
|
return std::unexpected{CellularLivesError::format};
|
|
Reader tail{bytes.last(8)};
|
|
if (checksum(bytes.first(bytes.size() - 8)) != tail.get())
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
|
|
Reader in{bytes};
|
|
const auto magic = in.get();
|
|
const auto format_version = static_cast<std::uint32_t>(in.get(4));
|
|
const auto rules_version = static_cast<std::uint32_t>(in.get(4));
|
|
const bool legacy = magic == cellular_lives_v1_magic &&
|
|
format_version == cellular_lives_legacy_format && rules_version == 1;
|
|
const bool offer_version = magic == cellular_lives_v2_magic &&
|
|
format_version == cellular_lives_format &&
|
|
rules_version == cellular_lives_rules;
|
|
// Format 6 carries rules 5, 6 (founder 2) or 7 (founder 3, ADR-0137); no new state.
|
|
// Format 9 is exactly rules 11; format 8 exactly rules 10.
|
|
// Format 10 is exactly rules 12.
|
|
// Format 11 is exactly rules 13, and carries everything format 10 does.
|
|
const bool revamp_version = magic == cellular_lives_v11_magic &&
|
|
format_version == cellular_lives_revamp_format &&
|
|
rules_version == cellular_lives_revamp_rules;
|
|
const bool liquid_version = revamp_version || (magic == cellular_lives_v10_magic &&
|
|
format_version == cellular_lives_liquid_format &&
|
|
rules_version == cellular_lives_liquid_rules);
|
|
const bool light_version =
|
|
liquid_version ||
|
|
(magic == cellular_lives_v9_magic && format_version == cellular_lives_light_format &&
|
|
rules_version == cellular_lives_photosynthesis_rules);
|
|
const bool inheritance_version =
|
|
light_version ||
|
|
(magic == cellular_lives_v8_magic && format_version == cellular_lives_inheritance_format &&
|
|
rules_version == cellular_lives_inheritance_rules);
|
|
const bool migration_version =
|
|
inheritance_version ||
|
|
(magic == cellular_lives_v7_magic && format_version == cellular_lives_migration_format &&
|
|
(rules_version == cellular_lives_foraging_rules ||
|
|
rules_version == cellular_lives_maturation_rules));
|
|
const bool presence_version =
|
|
migration_version ||
|
|
(magic == cellular_lives_v6_magic && format_version == cellular_lives_presence_format &&
|
|
(rules_version == cellular_lives_presence_rules ||
|
|
rules_version == cellular_lives_balance_rules ||
|
|
rules_version == cellular_lives_reproduction_rules ||
|
|
rules_version == cellular_lives_foraging_rules));
|
|
// Formats 5 and 6 carry the bud sequence and parent lives (rules 4 and 5).
|
|
const bool bud_version = presence_version || (magic == cellular_lives_v5_magic &&
|
|
format_version == cellular_lives_bud_format &&
|
|
rules_version == cellular_lives_bud_rules);
|
|
// Formats 4 and 5 record death causes and leave detritus (rules 3 and 4).
|
|
const bool engulf_version = bud_version || (magic == cellular_lives_v4_magic &&
|
|
format_version == cellular_lives_engulf_format &&
|
|
rules_version == cellular_lives_engulf_rules);
|
|
const bool revision_version =
|
|
engulf_version ||
|
|
(magic == cellular_lives_v3_magic && format_version == cellular_lives_revision_format &&
|
|
rules_version == cellular_lives_rules);
|
|
const bool mutation_version = offer_version || revision_version;
|
|
if (!legacy && !mutation_version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (migration_version && bytes.size() < cellular_lives_v7_header_bytes + 8)
|
|
return std::unexpected(CellularLivesError::format);
|
|
if (inheritance_version && bytes.size() < cellular_lives_v8_header_bytes + 8)
|
|
return std::unexpected(CellularLivesError::format);
|
|
if (light_version && bytes.size() < cellular_lives_v9_header_bytes + 8)
|
|
return std::unexpected(CellularLivesError::format);
|
|
if (liquid_version && bytes.size() < cellular_lives_v10_header_bytes + 8)
|
|
return std::unexpected(CellularLivesError::format);
|
|
if (revamp_version && bytes.size() < cellular_lives_v11_header_bytes + 8)
|
|
return std::unexpected(CellularLivesError::format);
|
|
const auto saved_world = in.get();
|
|
const auto saved_region = in.get();
|
|
const auto saved_frame = in.get();
|
|
const auto saved_tick = in.get();
|
|
if (saved_world != world || saved_region != region || saved_frame != frame)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
if (saved_tick != tick)
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
|
|
CellularLivesConfig config;
|
|
config.area.width_um = static_cast<std::uint32_t>(in.get(4));
|
|
config.area.height_um = static_cast<std::uint32_t>(in.get(4));
|
|
config.tick = saved_tick;
|
|
config.ambient_temperature_millikelvin = static_cast<std::uint32_t>(in.get(4));
|
|
const auto site_count = in.get(4);
|
|
const auto life_count = in.get(4);
|
|
const auto corpse_count = in.get(4);
|
|
const auto habitat_size = in.get(4);
|
|
const auto archive_size = in.get(4);
|
|
if (in.get(4) != 0 || site_count == 0 || site_count > max_primitive_lives ||
|
|
life_count > biology::max_cellular_tick_lives ||
|
|
corpse_count > biology::max_archived_organisms ||
|
|
habitat_size > biology::max_cellular_habitat_bytes ||
|
|
archive_size > biology::max_archive_bytes)
|
|
return std::unexpected{CellularLivesError::format};
|
|
const auto source = in.get();
|
|
const auto opening_total = in.inventory();
|
|
const auto nursery = in.inventory();
|
|
const auto heat = in.inventory();
|
|
const auto next_bud_sequence = bud_version ? in.get() : std::uint64_t{1};
|
|
CellularBoundaryLedger boundary;
|
|
std::uint64_t nonresident_count = 0;
|
|
if (migration_version) {
|
|
boundary.incoming = in.inventory();
|
|
boundary.outgoing = in.inventory();
|
|
nonresident_count = in.get(4);
|
|
if (in.get(4) != 0 || nonresident_count > biology::max_archived_organisms)
|
|
return std::unexpected(CellularLivesError::format);
|
|
}
|
|
std::uint64_t plan_count = 0;
|
|
if (inheritance_version) {
|
|
plan_count = in.get(4);
|
|
if (in.get(4) != 0 || plan_count > biology::max_archived_genomes)
|
|
return std::unexpected{CellularLivesError::format};
|
|
}
|
|
CellularLight light{};
|
|
accounting::Picojoules captured{};
|
|
if (light_version) {
|
|
light.numerator = in.get();
|
|
light.denominator = in.get();
|
|
light.entitlement.value = in.get();
|
|
light.moving_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
const auto reserved = in.get(4);
|
|
captured.value = in.get();
|
|
if (reserved != 0 || !cellular_light_valid(light) ||
|
|
captured.value > light.entitlement.value)
|
|
return std::unexpected{CellularLivesError::format};
|
|
}
|
|
CellularLiquidRules liquid{};
|
|
std::shared_ptr<const biology::CellularFlowField> field;
|
|
if (liquid_version) {
|
|
auto& c = liquid.currents;
|
|
auto& f = liquid.founder;
|
|
auto& d = liquid.deposits;
|
|
const auto u32 = [&in] { return static_cast<std::uint32_t>(in.get(4)); };
|
|
c.seed = in.get();
|
|
c.width_um = u32();
|
|
c.height_um = u32();
|
|
c.pitch_um = u32();
|
|
c.min_count = u32();
|
|
c.max_count = u32();
|
|
c.min_route_width_um = u32();
|
|
c.max_route_width_um = u32();
|
|
c.min_speed_um_per_s = u32();
|
|
c.max_speed_um_per_s = u32();
|
|
f.thrust_q10 = u32();
|
|
f.reverse_thrust_q10 = u32();
|
|
f.forward_drag_ppm = u32();
|
|
f.lateral_drag_ppm = u32();
|
|
const auto turn = u32();
|
|
f.turn = static_cast<std::uint16_t>(turn);
|
|
d.drift_radius_um = u32();
|
|
d.max_drift_q10 = static_cast<std::int32_t>(u32());
|
|
d.drift_decay_ppm = u32();
|
|
const auto cap = u32();
|
|
d.merged_cap = static_cast<std::uint16_t>(cap);
|
|
d.bubble_radius_um = u32();
|
|
const auto cost = u32();
|
|
liquid.thrust_cost_per_mille = cost == 0 ? 1'000 : cost;
|
|
if (cost == 1'000 || turn > 0xFFFFU || cap > 0xFFFFU ||
|
|
!cellular_liquid_valid(liquid, config.area))
|
|
return std::unexpected{CellularLivesError::format};
|
|
auto generated = biology::CellularFlowField::shared(liquid.currents);
|
|
if (!generated)
|
|
return std::unexpected{CellularLivesError::format};
|
|
field = std::move(*generated);
|
|
}
|
|
CellularRevampRules revamp{};
|
|
accounting::Inventory spent{};
|
|
if (revamp_version) {
|
|
const auto u32 = [&in] { return static_cast<std::uint32_t>(in.get(4)); };
|
|
revamp.body.essential_upkeep_per_thousand = u32();
|
|
const auto reserved = in.get(4);
|
|
for (auto& rate : revamp.burn_pj_per_kfg)
|
|
rate = in.get();
|
|
revamp.step.membrane_collection_per_mille_per_point = u32();
|
|
revamp.step.engulf_ratio_milli = u32();
|
|
revamp.step.engulf_reserve_percent = u32();
|
|
revamp.step.kill_bubble_per_thousand = u32();
|
|
revamp.drip_interval_ticks = u32();
|
|
revamp.reserve_load_per_thousand = u32();
|
|
revamp.drip_bubble_pj = in.get();
|
|
revamp.drip_bubble_fg = in.get();
|
|
spent = in.inventory();
|
|
if (!read_revamp_offers(in, revamp) || reserved != 0 || !cellular_revamp_valid(revamp))
|
|
return std::unexpected{CellularLivesError::format};
|
|
}
|
|
const auto life_bytes =
|
|
revamp_version
|
|
? cellular_life_v6_bytes + 8 + cellular_life_motion_bytes + cellular_life_revamp_bytes
|
|
: liquid_version ? cellular_life_v6_bytes + 8 + cellular_life_motion_bytes
|
|
: inheritance_version ? cellular_life_v6_bytes + 8
|
|
: legacy ? cellular_life_v1_bytes
|
|
: presence_version ? cellular_life_v6_bytes
|
|
: bud_version ? cellular_life_v5_bytes
|
|
: cellular_life_v2_bytes;
|
|
const auto corpse_bytes = inheritance_version ? cellular_corpse_v5_bytes + 8
|
|
: bud_version ? cellular_corpse_v5_bytes
|
|
: engulf_version ? cellular_corpse_v4_bytes
|
|
: cellular_corpse_bytes;
|
|
const auto expected_size = (revamp_version ? cellular_lives_v11_header_bytes
|
|
: liquid_version ? cellular_lives_v10_header_bytes
|
|
: light_version ? cellular_lives_v9_header_bytes
|
|
: inheritance_version ? cellular_lives_v8_header_bytes
|
|
: migration_version ? cellular_lives_v7_header_bytes
|
|
: bud_version ? cellular_lives_v5_header_bytes
|
|
: cellular_lives_header_bytes) +
|
|
cellular_site_bytes * site_count + life_bytes * life_count +
|
|
corpse_bytes * corpse_count + habitat_size + archive_size +
|
|
nonresident_count * 8 +
|
|
plan_count * cellular_offspring_revision_bytes + 8;
|
|
if (source == 0 || next_bud_sequence == 0 || expected_size != bytes.size())
|
|
return std::unexpected{CellularLivesError::format};
|
|
|
|
NurseryConfig nursery_config{saved_world, saved_region, saved_frame, source, nursery, {}};
|
|
nursery_config.sites.reserve(static_cast<std::size_t>(site_count));
|
|
for (std::uint64_t i = 0; i < site_count; ++i)
|
|
nursery_config.sites.push_back(in.site());
|
|
|
|
std::vector<CellularOwnedLife> lives;
|
|
lives.reserve(static_cast<std::size_t>(life_count));
|
|
for (std::uint64_t i = 0; i < life_count; ++i) {
|
|
CellularOwnedLife life{};
|
|
life.account = in.bytes<16>();
|
|
life.identity.life = in.get();
|
|
life.identity.organism = in.get();
|
|
life.identity.genome = in.get();
|
|
life.identity.event = in.get();
|
|
life.identity.born.value = in.get();
|
|
life.source = in.get();
|
|
life.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
life.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
life.position = {in.get(), in.get()};
|
|
life.body = in.inventory();
|
|
life.reserve = in.inventory();
|
|
if (mutation_version) {
|
|
auto& mutation = life.mutation;
|
|
mutation.fed_energy_credit_pj = in.get();
|
|
mutation.event_index = in.get();
|
|
mutation.offer_tick = in.get();
|
|
biology::MutationOffer offer{};
|
|
offer.parent = in.get();
|
|
offer.parent_digest = in.get();
|
|
offer.context.seed = in.get();
|
|
offer.context.stream = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.event_index = in.get();
|
|
const auto offered_count = static_cast<std::uint16_t>(in.get(2));
|
|
if (offered_count != 0)
|
|
offer.context.candidate_count = cellular_mutation_candidate_count;
|
|
const auto reserved16 = in.get(2);
|
|
offer.context.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
offer.context.environment.temperature_millikelvin =
|
|
static_cast<std::uint32_t>(in.get(4));
|
|
const auto reserved32 = in.get(4);
|
|
offer.context.environment.available = in.inventory();
|
|
for (std::size_t slot = 0; slot < biology::max_candidates; ++slot) {
|
|
biology::MutationCandidate candidate{};
|
|
candidate.operator_id = static_cast<std::uint16_t>(in.get(2));
|
|
candidate.target = static_cast<biology::Capability>(in.get(1));
|
|
candidate.effect = static_cast<biology::MutationEffect>(in.get(1));
|
|
candidate.parameter = static_cast<std::uint32_t>(in.get(4));
|
|
candidate.maintenance = in.get();
|
|
candidate.total_mass = in.get();
|
|
if (slot < offered_count)
|
|
offer.candidates.push_back(candidate);
|
|
else if (candidate != biology::MutationCandidate{})
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
const bool has_offer = mutation.offer_tick != 0;
|
|
if (reserved16 != 0 || reserved32 != 0 ||
|
|
(has_offer &&
|
|
(offer.parent == 0 || offer.parent_digest == 0 || offer.context.seed == 0 ||
|
|
offer.context.stream == 0 || offer.context.event_index != mutation.event_index ||
|
|
offered_count == 0 || offered_count > cellular_mutation_candidate_count ||
|
|
offer.candidates.size() != offered_count)) ||
|
|
(!has_offer && (offer.parent != 0 || offer.parent_digest != 0 ||
|
|
offer.context != biology::MutationContext{})))
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
if (has_offer) {
|
|
mutation.offer = std::move(offer);
|
|
}
|
|
}
|
|
if (bud_version)
|
|
life.parent_life = in.get();
|
|
if (presence_version) {
|
|
const auto presence = in.get(1);
|
|
const auto padding = in.get(7);
|
|
life.frozen_since = in.get();
|
|
if (presence > static_cast<std::uint8_t>(CellularPresence::suspended) || padding != 0)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
life.presence = static_cast<CellularPresence>(presence);
|
|
}
|
|
if (inheritance_version)
|
|
life.offspring_genome = in.get();
|
|
if (liquid_version) {
|
|
life.motion.velocity_x_q10 =
|
|
static_cast<std::int32_t>(static_cast<std::uint32_t>(in.get(4)));
|
|
life.motion.velocity_y_q10 =
|
|
static_cast<std::int32_t>(static_cast<std::uint32_t>(in.get(4)));
|
|
life.motion.heading = static_cast<std::uint16_t>(in.get(2));
|
|
const auto padding = in.get(2);
|
|
life.motion.remainder_x = static_cast<std::int64_t>(in.get(4));
|
|
life.motion.remainder_y = static_cast<std::int64_t>(in.get(4));
|
|
if (padding != 0 || !valid_motion(life.motion))
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
if (revamp_version) {
|
|
const auto state = read_revamp_life(in);
|
|
if (!state)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
life.revamp = *state;
|
|
}
|
|
lives.push_back(life);
|
|
}
|
|
|
|
std::vector<CellularOwnedCorpse> corpses;
|
|
corpses.reserve(static_cast<std::size_t>(corpse_count));
|
|
for (std::uint64_t i = 0; i < corpse_count; ++i) {
|
|
CellularOwnedCorpse corpse{};
|
|
corpse.life_id = in.get();
|
|
corpse.organism = in.get();
|
|
corpse.source = in.get();
|
|
corpse.died_tick = in.get();
|
|
corpse.position = {in.get(), in.get()};
|
|
corpse.growth.realized_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.growth.damage_per_thousand = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.extent_um = static_cast<std::uint32_t>(in.get(4));
|
|
corpse.inventory = in.inventory();
|
|
if (engulf_version) {
|
|
// Rules 3: a known cause, a predator exactly when engulfed, and no inventory
|
|
// (it became detritus or the predator's).
|
|
const auto cause = in.get(1);
|
|
const auto padding = in.get(7);
|
|
corpse.predator_life = in.get();
|
|
corpse.cause = static_cast<biology::CellularDeathCause>(cause);
|
|
const bool engulfed = corpse.cause == biology::CellularDeathCause::engulfed;
|
|
const bool revamp_cause =
|
|
revamp_version && (corpse.cause == biology::CellularDeathCause::merged ||
|
|
corpse.cause == biology::CellularDeathCause::emerged);
|
|
if (padding != 0 ||
|
|
(corpse.cause != biology::CellularDeathCause::starved && !engulfed &&
|
|
!revamp_cause) ||
|
|
engulfed != (corpse.predator_life != 0) || corpse.predator_life == corpse.life_id ||
|
|
corpse.inventory != accounting::Inventory{})
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
if (bud_version)
|
|
corpse.parent_life = in.get();
|
|
if (inheritance_version)
|
|
corpse.offspring_genome = in.get();
|
|
corpses.push_back(corpse);
|
|
}
|
|
const auto habitat_payload = in.raw(static_cast<std::size_t>(habitat_size));
|
|
const auto archive_payload = in.raw(static_cast<std::size_t>(archive_size));
|
|
|
|
auto habitat =
|
|
biology::CellularHabitat::restore(habitat_payload, saved_world, saved_region, saved_frame);
|
|
if (!habitat) {
|
|
if (habitat.error() == biology::CellularHabitatError::version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (habitat.error() == biology::CellularHabitatError::checksum)
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
}
|
|
// Rules 8 to 11 run on a deposit habitat, rules 12 on a liquid one (ADR-0136, rules 12).
|
|
const auto habitat_format = (*habitat)->config().format;
|
|
if ((rules_version >= cellular_lives_liquid_rules)
|
|
? habitat_format != biology::cellular_habitat_liquid_format
|
|
: (rules_version >= cellular_lives_foraging_rules) !=
|
|
(habitat_format == biology::cellular_habitat_deposit_format))
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
auto archive = biology::LineageArchive::decode(archive_payload);
|
|
if (!archive) {
|
|
if (archive.error() == biology::ArchiveCodecError::version)
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (archive.error() == biology::ArchiveCodecError::checksum)
|
|
return std::unexpected{CellularLivesError::checksum};
|
|
if (archive.error() == biology::ArchiveCodecError::noncanonical)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
return std::unexpected{CellularLivesError::archive};
|
|
}
|
|
if (migration_version) {
|
|
boundary.nonresident_organisms.reserve(static_cast<std::size_t>(nonresident_count));
|
|
for (std::uint64_t index = 0; index < nonresident_count; ++index)
|
|
boundary.nonresident_organisms.push_back(in.get());
|
|
}
|
|
std::vector<CellularOffspringRevision> plan_history;
|
|
plan_history.reserve(static_cast<std::size_t>(plan_count));
|
|
for (std::uint64_t index = 0; index < plan_count; ++index)
|
|
plan_history.push_back({in.get(), in.get(), in.get(), in.get()});
|
|
if (archive->format_version() != (revision_version ? biology::lineage_archive_revision_format
|
|
: biology::lineage_archive_format))
|
|
return std::unexpected{CellularLivesError::version};
|
|
if (mutation_version) {
|
|
for (const auto& life : lives) {
|
|
if (!life.mutation.offer)
|
|
continue;
|
|
const auto genome = archive->find(cellular_offspring_genome(life));
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto& offer = *life.mutation.offer;
|
|
if (life.mutation.event_index == 0 || life.mutation.offer_tick == 0 ||
|
|
life.mutation.offer_tick > saved_tick ||
|
|
offer.parent != cellular_offspring_genome(life) ||
|
|
offer.context.seed != mutation_seed(saved_world, saved_region, life.identity.life,
|
|
life.mutation.event_index) ||
|
|
offer.context.stream != cellular_mutation_stream ||
|
|
offer.context.event_index != life.mutation.event_index ||
|
|
offer.context.environment.temperature_millikelvin !=
|
|
config.ambient_temperature_millikelvin)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
const auto generated = biology::mutation_candidates(*genome, offer.context);
|
|
if (!generated || *generated != offer)
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
}
|
|
}
|
|
const auto current = validate_state(
|
|
saved_world, saved_region, saved_frame, config, nursery_config, **habitat, lives, corpses,
|
|
*archive, nursery, heat, opening_total, engulf_version, bud_version, next_bud_sequence,
|
|
presence_version, migration_version ? &boundary : nullptr,
|
|
inheritance_version ? &plan_history : nullptr, spent, revamp_version);
|
|
if (!current)
|
|
return std::unexpected{current.error()};
|
|
|
|
auto restored = std::unique_ptr<CellularLives>{new CellularLives{std::make_unique<State>(
|
|
saved_world, saved_region, saved_frame, config, std::move(nursery_config),
|
|
std::move(*habitat), std::move(lives), std::move(corpses), *archive, nursery, heat,
|
|
opening_total, *current, format_version, rules_version, std::move(boundary))}};
|
|
restored->state_->next_bud_sequence = next_bud_sequence;
|
|
restored->state_->offspring_revisions = std::move(plan_history);
|
|
restored->state_->light = light;
|
|
restored->state_->captured = captured;
|
|
restored->state_->liquid = liquid;
|
|
restored->state_->field = std::move(field);
|
|
restored->state_->revamp = revamp;
|
|
restored->state_->spent = spent;
|
|
if (!std::ranges::equal(bytes, restored->snapshot()))
|
|
return std::unexpected{CellularLivesError::noncanonical};
|
|
return restored;
|
|
}
|
|
|
|
std::expected<biology::CellularRegionStepCandidate, CellularLivesError>
|
|
CellularLives::advance_tick(std::span<const CellularLifeIntent> intents) {
|
|
auto execution =
|
|
advance_tick_with_mutations(intents, std::span<const CellularMutationSelection>{});
|
|
if (!execution)
|
|
return std::unexpected{execution.error()};
|
|
return std::move(execution->step);
|
|
}
|
|
|
|
std::expected<CellularTickExecution, CellularLivesError>
|
|
CellularLives::advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
|
|
std::span<const CellularMutationSelection> selections) {
|
|
if (state_->config.tick == std::numeric_limits<std::uint64_t>::max())
|
|
return std::unexpected{CellularLivesError::invalid_tick};
|
|
if (intents.size() != state_->lives.size())
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
std::vector<CellularLifeIntent> ordered{intents.begin(), intents.end()};
|
|
std::ranges::sort(ordered, {}, &CellularLifeIntent::life_id);
|
|
for (std::size_t i = 0; i < ordered.size(); ++i)
|
|
if ((i != 0 && ordered[i - 1].life_id == ordered[i].life_id) ||
|
|
ordered[i].life_id != state_->lives[i].identity.life)
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
|
|
if (!selections.empty() && state_->format_version < cellular_lives_revision_format)
|
|
return std::unexpected{CellularLivesError::version};
|
|
// Rules 4 keep rules 3 (engulfment, detritus) and add budding (ADR-0125).
|
|
const bool engulf_rules = state_->rules_version >= cellular_lives_engulf_rules;
|
|
const bool contact_rules = state_->rules_version >= cellular_lives_foraging_rules;
|
|
const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules;
|
|
const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules;
|
|
const bool inheritance_rules = cellular_retained_plans(state_->rules_version);
|
|
const bool liquid_rules = state_->rules_version >= cellular_lives_liquid_rules;
|
|
const bool revamp_rules = state_->rules_version >= cellular_lives_revamp_rules;
|
|
if (liquid_rules && !state_->field)
|
|
return std::unexpected{CellularLivesError::invalid_config};
|
|
for (std::size_t i = 0; i < ordered.size(); ++i) {
|
|
const auto& intent = ordered[i].intent;
|
|
// Below rules 4 a bud is ignored, as engulfment is below rules 3 (ADR-0124/0125).
|
|
if (intent.bud && (intent.intake_target || intent.engulf))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
// ADR-0128: only an owned life of a rules-5 region freezes, and a frozen intent
|
|
// carries nothing else.
|
|
if (intent.frozen && (!presence_rules || state_->lives[i].account == LifeAccount{} ||
|
|
intent.movement != biology::CellularIntent{} ||
|
|
intent.intake_target || intent.engulf || intent.bud || intent.brake))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
if (intent.brake && !liquid_rules)
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
if (intent.become &&
|
|
(!revamp_rules || !intent.bud || state_->lives[i].account == LifeAccount{} ||
|
|
state_->lives[i].revamp.members > 1))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
if (intent.emerge && (!revamp_rules || state_->lives[i].account == LifeAccount{} ||
|
|
intent.frozen || intent.bud || intent.engulf || intent.intake_target))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
// Rules 13: exclusions are an owned life's setting, never wildlife's or a frozen cell's.
|
|
if (intent.exclude != 0 && (!revamp_rules || intent.exclude > 0x0F || intent.frozen ||
|
|
state_->lives[i].account == LifeAccount{}))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
}
|
|
for (std::size_t i = 0; i < selections.size(); ++i) {
|
|
const auto& selection = selections[i];
|
|
if (selection.life_id == 0 || selection.event_index == 0 || selection.offer_tick == 0 ||
|
|
selection.successor_id == 0 || // Operator 0 declines (ADR-0120 amendment).
|
|
(selection.become && !revamp_rules) || // Rules 13 only (ADR-0179).
|
|
(i != 0 && selections[i - 1].life_id >= selection.life_id))
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
const auto life = std::ranges::lower_bound(
|
|
state_->lives, selection.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
// ADR-0121 amendment (schema 59): a queued choice can outlive its life; it binds
|
|
// with the life_died result and changes nothing.
|
|
if (life == state_->lives.end() || life->identity.life != selection.life_id) {
|
|
if (state_->archive.find(selection.successor_id))
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
continue;
|
|
}
|
|
if (revamp_rules) {
|
|
// Rules 13: a choice names the life's own pending offer and one of its mutations.
|
|
const auto& pending = life->revamp.offer;
|
|
const auto ids = std::span{pending.ids}.first(pending.count);
|
|
if (pending.count == 0 || pending.event_index != selection.event_index ||
|
|
pending.offer_tick != selection.offer_tick ||
|
|
(selection.operator_id != 0 &&
|
|
std::ranges::find(ids, selection.operator_id) == ids.end()) ||
|
|
state_->archive.find(selection.successor_id))
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
for (std::size_t j = 0; j < i; ++j)
|
|
if (selections[j].successor_id == selection.successor_id)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
continue;
|
|
}
|
|
if (life->mutation.event_index != selection.event_index ||
|
|
life->mutation.offer_tick != selection.offer_tick)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (!life->mutation.offer.has_value())
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto offer = life->mutation.offer.value_or(biology::MutationOffer{});
|
|
if (offer.parent != cellular_offspring_genome(*life) ||
|
|
offer.context.event_index != selection.event_index ||
|
|
(selection.operator_id != 0 && !std::ranges::any_of(offer.candidates,
|
|
[&](const auto& candidate) {
|
|
return candidate.operator_id ==
|
|
selection.operator_id;
|
|
})) ||
|
|
state_->archive.find(selection.successor_id))
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
for (std::size_t j = 0; j < i; ++j)
|
|
if (selections[j].successor_id == selection.successor_id)
|
|
return std::unexpected{CellularLivesError::identity};
|
|
}
|
|
|
|
std::vector<biology::CellularLifeStepInput> inputs;
|
|
inputs.reserve(state_->lives.size());
|
|
for (std::size_t i = 0; i < state_->lives.size(); ++i) {
|
|
const auto& life = state_->lives[i];
|
|
if (life.presence == CellularPresence::suspended)
|
|
continue; // Out of the world: no step, no contact (ADR-0128).
|
|
const auto budget =
|
|
budget_for(state_->archive, life, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
const auto genome = state_->archive.find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto membrane = genome->parameter(biology::Capability::membrane);
|
|
if (!membrane)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
inputs.push_back({life.identity.life,
|
|
life.position,
|
|
budget->phenotype.extent,
|
|
ordered[i].intent,
|
|
life.body,
|
|
life.reserve,
|
|
{},
|
|
*budget,
|
|
*membrane,
|
|
life.source});
|
|
if (liquid_rules) {
|
|
auto handling = cellular_liquid_handling(*genome, *budget, state_->liquid);
|
|
if (!handling)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
if (revamp_rules) {
|
|
// Rules 13: reserve matter is carried as load.
|
|
std::uint64_t carried{};
|
|
for (const auto& channel : life.reserve.matter)
|
|
carried += channel.value;
|
|
const auto members = std::uint64_t{life.revamp.members};
|
|
const auto extra = budget->phenotype.total_mass / members * (members - 1) / 1'000 *
|
|
state_->revamp.organism_load_per_thousand;
|
|
*handling = cellular_loaded_handling(*handling, budget->phenotype.total_mass,
|
|
carried, state_->revamp, extra);
|
|
}
|
|
inputs.back().liquid = biology::CellularLiquidInput{
|
|
life.motion, *handling,
|
|
state_->field->at_footprint(life.position, budget->phenotype.extent),
|
|
ordered[i].intent.brake};
|
|
}
|
|
if (revamp_rules) {
|
|
// Rules 13: the genome's traits; a life from before the upgrade (no traits, the
|
|
// membrane in micrometres) feeds and burns as a founder and keeps all bubble energy.
|
|
biology::CellularRevampLifeInput revamp{};
|
|
const auto& traits = genome->cellular_traits();
|
|
const auto kept = genome->parameter(biology::Capability::energy_conversion);
|
|
if (traits) {
|
|
revamp.burn = biology::cellular_burn(state_->revamp.burn_pj_per_kfg, traits->burn,
|
|
ordered[i].intent.exclude);
|
|
revamp.collection = traits->collection;
|
|
revamp.energy_kept_per_thousand = kept ? *kept : 1'000;
|
|
revamp.membrane_nm = *membrane;
|
|
revamp.engulf_capacity = traits->engulf_capacity;
|
|
revamp.kill_absorption = traits->kill_absorption;
|
|
} else {
|
|
revamp.burn =
|
|
biology::cellular_burn(state_->revamp.burn_pj_per_kfg, {100, 100, 100, 100},
|
|
ordered[i].intent.exclude);
|
|
revamp.membrane_nm = *membrane * 1'000;
|
|
}
|
|
inputs.back().revamp = revamp;
|
|
}
|
|
}
|
|
biology::CellularRegionRules region_rules{engulf_rules, contact_rules};
|
|
if (revamp_rules)
|
|
region_rules.revamp = state_->revamp.step;
|
|
auto proposal = biology::propose_cellular_region_step(state_->config.tick, state_->config.area,
|
|
inputs, *state_->habitat, region_rules);
|
|
if (!proposal)
|
|
return std::unexpected{CellularLivesError::region_step};
|
|
|
|
auto next_lives = state_->lives;
|
|
auto next_corpses = state_->corpses;
|
|
auto next_archive = state_->archive;
|
|
auto next_offspring_revisions = state_->offspring_revisions;
|
|
auto next_heat = state_->heat;
|
|
auto next_spent = state_->spent;
|
|
if (!add_inventory(next_spent, proposal->spent))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
auto habitat_config = state_->habitat->config();
|
|
// Rules 13: each owned life's activity this tick, gathered from every phase below and
|
|
// applied to its affinity at the end. Paid mutation costs wait to be reclaimed.
|
|
std::vector<std::pair<std::uint64_t, biology::CellularActivity>> activity;
|
|
const auto activity_of = [&activity](std::uint64_t life_id) -> biology::CellularActivity& {
|
|
const auto found = std::ranges::find(
|
|
activity, life_id, &std::pair<std::uint64_t, biology::CellularActivity>::first);
|
|
if (found != activity.end())
|
|
return found->second;
|
|
return activity.emplace_back(life_id, biology::CellularActivity{}).second;
|
|
};
|
|
std::vector<std::pair<accounting::Inventory, biology::CellularPosition>> reclaims;
|
|
for (const auto& result : proposal->lives) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, result.life_id, {}, [](const auto& life) { return life.identity.life; });
|
|
if (found == next_lives.end() || found->identity.life != result.life_id)
|
|
return std::unexpected{CellularLivesError::invalid_life};
|
|
found->position = result.candidate.position;
|
|
found->reserve = result.candidate.reserve_after;
|
|
if (liquid_rules)
|
|
found->motion = result.candidate.motion;
|
|
if (!add_inventory(next_heat, result.candidate.heat_after))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
if (revamp_rules && found->account != LifeAccount{}) {
|
|
using S = biology::CellularSignal;
|
|
const auto& c = result.candidate;
|
|
auto& a = activity_of(result.life_id);
|
|
const bool thrust = c.movement_status == biology::CellularMovementStatus::moved ||
|
|
c.movement_status == biology::CellularMovementStatus::blocked;
|
|
a[S::thrust] = thrust ? 1 : 0;
|
|
a[S::drifting] = thrust ? 0 : 1;
|
|
const auto request =
|
|
std::ranges::lower_bound(ordered, result.life_id, {}, &CellularLifeIntent::life_id);
|
|
const bool brake = request != ordered.end() && request->life_id == result.life_id &&
|
|
request->intent.brake;
|
|
a[S::brake_press] = brake && found->revamp.last_brake == 0 ? 1 : 0;
|
|
found->revamp.last_brake = brake ? 1 : 0;
|
|
const auto acquired = c.intake ? c.intake->transfer.acquired : accounting::Inventory{};
|
|
std::uint64_t collected{}, burned{};
|
|
for (const auto& channel : acquired.matter)
|
|
collected += channel.value;
|
|
for (const auto& channel : c.spent.matter)
|
|
burned += channel.value;
|
|
a[S::fed] = collected != 0 || acquired.energy.value != 0 ? 1 : 0;
|
|
a[S::intake_limited] = c.matter_limited ? 1 : 0;
|
|
a[S::energy_limited] = c.energy_limited ? 1 : 0;
|
|
a[S::energy_collected] = acquired.energy.value;
|
|
a[S::collected_carbon] = acquired.matter[0].value;
|
|
a[S::collected_nitrogen] = acquired.matter[1].value;
|
|
a[S::collected_phosphorus] = acquired.matter[2].value;
|
|
a[S::collected_other] = acquired.matter[3].value;
|
|
a[S::collected_matter] = collected;
|
|
a[S::burned_carbon] = c.spent.matter[0].value;
|
|
a[S::burned_nitrogen] = c.spent.matter[1].value;
|
|
a[S::burned_phosphorus] = c.spent.matter[2].value;
|
|
a[S::burned_other] = c.spent.matter[3].value;
|
|
a[S::burned_matter] = burned;
|
|
a[S::burned_not_carbon] = burned - c.spent.matter[0].value;
|
|
a[S::energy_upkeep] = c.maintenance_cost.value;
|
|
a[S::energy_movement] = c.movement_cost.value;
|
|
a[S::energy_spent] = c.maintenance_cost.value + c.movement_cost.value;
|
|
const bool asked = request != ordered.end() && request->life_id == result.life_id &&
|
|
request->intent.engulf;
|
|
a[S::engulf_attempt] = asked ? 1 : 0;
|
|
a[S::engulf_success] = result.engulf == biology::CellularEngulfStatus::engulfed ? 1 : 0;
|
|
const bool too_large = result.engulf == biology::CellularEngulfStatus::prey_too_large;
|
|
a[S::engulf_too_large] = too_large ? 1 : 0;
|
|
a[S::engulf_too_large_or_membrane] =
|
|
too_large || result.engulf == biology::CellularEngulfStatus::membrane_too_thick ? 1
|
|
: 0;
|
|
a.heading = c.motion.heading;
|
|
found->revamp.progress.carbon_burned += c.spent.matter[0].value;
|
|
// Touching a cell over 1.5 times its own mass.
|
|
const auto own = std::ranges::lower_bound(inputs, result.life_id, {},
|
|
&biology::CellularLifeStepInput::life_id);
|
|
if (own != inputs.end() && own->life_id == result.life_id)
|
|
for (const auto& other : proposal->lives) {
|
|
if (other.life_id == result.life_id)
|
|
continue;
|
|
const auto input = std::ranges::lower_bound(
|
|
inputs, other.life_id, {}, &biology::CellularLifeStepInput::life_id);
|
|
if (input == inputs.end() || input->life_id != other.life_id ||
|
|
input->budget.phenotype.total_mass * 2 <=
|
|
own->budget.phenotype.total_mass * 3)
|
|
continue;
|
|
if (biology::cellular_footprints_contact(c.position, own->extent_um,
|
|
other.candidate.position,
|
|
input->extent_um)) {
|
|
a[S::larger_contact] = 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// Only owned lives earn mutation offers; wildlife never mutates in M11 (ADR-0098).
|
|
// Rules 13 earn them from active play instead (below).
|
|
if (state_->format_version >= cellular_lives_format && result.candidate.intake &&
|
|
found->account != LifeAccount{} && !revamp_rules) {
|
|
const auto acquired = result.candidate.intake->transfer.acquired.energy.value;
|
|
if (acquired >
|
|
std::numeric_limits<std::uint64_t>::max() - found->mutation.fed_energy_credit_pj)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
found->mutation.fed_energy_credit_pj += acquired;
|
|
if (!found->mutation.offer) {
|
|
const auto budget =
|
|
budget_for(next_archive, *found, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!budget ||
|
|
budget->maintenance.value > std::numeric_limits<std::uint64_t>::max() /
|
|
cellular_mutation_surplus_seconds)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto threshold =
|
|
budget->maintenance.value * cellular_mutation_surplus_seconds;
|
|
if (threshold == 0)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (found->mutation.fed_energy_credit_pj >= threshold) {
|
|
if (found->mutation.event_index == std::numeric_limits<std::uint64_t>::max())
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
const auto genome = next_archive.find(cellular_offspring_genome(*found));
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto next_event = found->mutation.event_index + 1;
|
|
biology::MutationContext context{
|
|
mutation_seed(state_->world, state_->region, result.life_id, next_event),
|
|
cellular_mutation_stream,
|
|
next_event,
|
|
cellular_mutation_candidate_count,
|
|
found->growth,
|
|
{state_->config.ambient_temperature_millikelvin,
|
|
result.candidate.intake->transfer.patch_after}};
|
|
const auto offer = biology::mutation_candidates(*genome, context);
|
|
if (offer) {
|
|
found->mutation.fed_energy_credit_pj -= threshold;
|
|
found->mutation.event_index = next_event;
|
|
found->mutation.offer_tick = proposal->end_tick;
|
|
found->mutation.offer = *offer;
|
|
} else if (offer.error() != biology::MutationError::no_candidates) {
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (const auto& dead : proposal->starved) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, dead.life_id, {}, [](const auto& life) { return life.identity.life; });
|
|
if (found == next_lives.end() || found->identity.life != dead.life_id ||
|
|
!next_archive.record_death(found->identity.organism, {proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
auto single = *found;
|
|
single.revamp.members = 1; // A corpse records the single-cell extent.
|
|
const auto corpse_budget =
|
|
budget_for(next_archive, single, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!corpse_budget)
|
|
return std::unexpected{corpse_budget.error()};
|
|
if (revamp_rules && dead.cause == biology::CellularDeathCause::engulfed &&
|
|
found->parent_life != 0 &&
|
|
proposal->end_tick - found->identity.born.value <= cellular_bud_early_ticks)
|
|
activity_of(found->parent_life)[biology::CellularSignal::bud_lost_early] += 1;
|
|
next_corpses.push_back(
|
|
{found->identity.life, found->identity.organism, found->source, proposal->end_tick,
|
|
dead.position, found->growth, corpse_budget->phenotype.extent, dead.inventory,
|
|
engulf_rules ? dead.cause : biology::CellularDeathCause::unrecorded,
|
|
engulf_rules ? dead.predator_id : 0, found->parent_life, found->offspring_genome});
|
|
next_lives.erase(found);
|
|
}
|
|
std::vector<CellularMutationExecution> mutation_results;
|
|
// Bud identities: rules-13 splits draw from the same sequence as buds.
|
|
auto next_bud_sequence = state_->next_bud_sequence;
|
|
mutation_results.reserve(selections.size());
|
|
for (const auto& selection : selections) {
|
|
const auto found = std::ranges::lower_bound(
|
|
next_lives, selection.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (found == next_lives.end() || found->identity.life != selection.life_id) {
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::life_died});
|
|
continue;
|
|
}
|
|
if (revamp_rules) {
|
|
auto& pending = found->revamp.offer;
|
|
const auto plan = next_archive.find(cellular_offspring_genome(*found));
|
|
const auto expressed = next_archive.find(found->identity.genome);
|
|
if (pending.count == 0 || !plan || !expressed)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto* spec = biology::cellular_mutation(selection.operator_id);
|
|
const auto draft = spec == nullptr
|
|
? std::nullopt
|
|
: biology::apply_cellular_mutation(
|
|
*plan, *spec, state_->revamp.mutations.at(spec->id - 1u),
|
|
state_->revamp.bounds, found->revamp.progress,
|
|
selection.successor_id, selection.successor_id);
|
|
if (selection.operator_id == 0 || !draft) {
|
|
// A decline, or a mutation no longer available, consumes the offer.
|
|
pending = {};
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::declined});
|
|
continue;
|
|
}
|
|
// The cost comes from the reserve: matter channels directly, energy with matter
|
|
// standing in (except excluded channels). Unaffordable: the offer stays.
|
|
const auto cost = cellular_mutation_cost(state_->revamp.mutations.at(spec->id - 1u));
|
|
auto reserve = found->reserve;
|
|
bool affordable = true;
|
|
for (std::size_t c = 0; c < reserve.matter.size(); ++c) {
|
|
if (reserve.matter[c].value < cost.matter[c].value)
|
|
affordable = false;
|
|
else
|
|
reserve.matter[c].value -= cost.matter[c].value;
|
|
}
|
|
const auto request = std::ranges::lower_bound(ordered, selection.life_id, {},
|
|
&CellularLifeIntent::life_id);
|
|
const auto exclude = request != ordered.end() && request->life_id == selection.life_id
|
|
? request->intent.exclude
|
|
: std::uint8_t{0};
|
|
const auto& traits = expressed->cellular_traits();
|
|
const auto burn = biology::cellular_burn(
|
|
state_->revamp.burn_pj_per_kfg,
|
|
traits ? traits->burn : std::array<std::uint16_t, 4>{100, 100, 100, 100}, exclude);
|
|
const auto payment =
|
|
affordable ? biology::cellular_pay(reserve, cost.energy.value, burn, false)
|
|
: std::nullopt;
|
|
if (!payment) {
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::insufficient_funding});
|
|
continue;
|
|
}
|
|
const auto successor = biology::Genome::create(*draft);
|
|
if (!successor)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
const auto price = [&]() -> std::uint64_t {
|
|
const auto rules = biology::rules_for(successor->development_version());
|
|
return rules ? rules->construction_per_kilogram : 0;
|
|
}();
|
|
if (found->revamp.members > 1) {
|
|
// A multicellular organism expresses the mutation as a whole (ADR-0179), its
|
|
// changed tissue funded from the shared reserve; "not now" when it cannot be.
|
|
const auto scaled = organism_genome(*successor, found->revamp.members);
|
|
const auto target = scaled
|
|
? biology::metabolic_budget(
|
|
*scaled, found->growth,
|
|
{state_->config.ambient_temperature_millikelvin, {}},
|
|
1000, state_->revamp.body)
|
|
: std::unexpected{biology::DevelopmentError::overflow};
|
|
auto body = found->body;
|
|
auto heat = accounting::Inventory{};
|
|
if (!target)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
if (!rebody(body, reserve, heat, target->body, price)) {
|
|
// The offer stays, as for any unaffordable cost.
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::insufficient_funding});
|
|
continue;
|
|
}
|
|
if (!next_archive.record_mutation(found->identity.organism, *successor,
|
|
{proposal->end_tick}) ||
|
|
!add_inventory(next_heat, heat) || !add_inventory(next_spent, payment->spent))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
auto returned = cost;
|
|
returned.energy.value = payment->energy;
|
|
reclaims.emplace_back(returned, found->position);
|
|
found->identity.genome = successor->id();
|
|
found->offspring_genome = successor->id();
|
|
found->body = body;
|
|
found->reserve = reserve;
|
|
pending = {};
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::applied});
|
|
continue;
|
|
}
|
|
if (spec->effect == biology::CellularEffect::acquire_adhesion) {
|
|
// Adhesion: the split's offspring attaches at once, so the cell becomes a
|
|
// two-member organism holding its whole body and reserve under the new plan. The
|
|
// single cell's life ends as merged; the player continues as the organism.
|
|
const auto temperature = state_->config.ambient_temperature_millikelvin;
|
|
const auto organism = organism_genome(*successor, 2);
|
|
if (!organism)
|
|
return std::unexpected{organism.error()};
|
|
const auto fit = biology::largest_growth_within(*organism, found->body, temperature,
|
|
state_->revamp.body);
|
|
if (!fit)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto identity = cellular_bud_identity(state_->region, next_bud_sequence);
|
|
const auto& formed = *fit;
|
|
if (!formed || identity == 0 || next_archive.organism(identity)) {
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::split_refused});
|
|
continue;
|
|
}
|
|
const auto grown = biology::metabolic_budget(
|
|
*organism, formed->first, {temperature, {}}, 1000, state_->revamp.body);
|
|
if (!grown)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto single_budget =
|
|
budget_for(next_archive, *found, temperature, state_->revamp.body);
|
|
if (!single_budget)
|
|
return std::unexpected{single_budget.error()};
|
|
if (!next_archive.admit(*successor) ||
|
|
!next_archive.record_birth(identity, successor->id(), {proposal->end_tick}) ||
|
|
!next_archive.record_death(found->identity.organism, {proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
if (!add_inventory(next_spent, payment->spent))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
auto returned = cost;
|
|
returned.energy.value = payment->energy;
|
|
reclaims.emplace_back(returned, found->position);
|
|
CellularOwnedLife whole{};
|
|
whole.account = found->account;
|
|
whole.identity = {
|
|
identity, identity, successor->id(), identity, {proposal->end_tick}};
|
|
whole.source = found->source;
|
|
whole.growth = formed->first;
|
|
whole.body = formed->second;
|
|
whole.reserve = reserve;
|
|
for (std::size_t c = 0; c < whole.body.matter.size(); ++c)
|
|
whole.reserve.matter[c].value +=
|
|
found->body.matter[c].value - formed->second.matter[c].value;
|
|
// Keep the larger body inside the region.
|
|
const auto extent = grown->phenotype.extent;
|
|
whole.position = found->position;
|
|
whole.position.x_um = std::min<std::uint64_t>(
|
|
whole.position.x_um, state_->config.area.width_um - extent);
|
|
whole.position.y_um = std::min<std::uint64_t>(
|
|
whole.position.y_um, state_->config.area.height_um - extent);
|
|
whole.motion = found->motion;
|
|
whole.parent_life = found->identity.life;
|
|
whole.offspring_genome = successor->id();
|
|
whole.revamp.affinity.score = found->revamp.affinity.score;
|
|
whole.revamp.progress = found->revamp.progress;
|
|
whole.revamp.members = 2;
|
|
next_corpses.push_back({found->identity.life,
|
|
found->identity.organism,
|
|
found->source,
|
|
proposal->end_tick,
|
|
found->position,
|
|
found->growth,
|
|
single_budget->phenotype.extent,
|
|
{},
|
|
biology::CellularDeathCause::merged,
|
|
0,
|
|
found->parent_life,
|
|
found->offspring_genome});
|
|
next_lives.erase(found);
|
|
++next_bud_sequence;
|
|
next_lives.insert(std::ranges::lower_bound(next_lives, identity, {},
|
|
[](const CellularOwnedLife& life) {
|
|
return life.identity.life;
|
|
}),
|
|
whole);
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::split_applied});
|
|
continue;
|
|
}
|
|
// The split (Cellular_reproduction_plan.md section 4): body and reserve divide, the
|
|
// offspring expresses the mutation, both plans carry it. Refused, spending nothing,
|
|
// when the cell is too small, has no room beside it, or the region is full.
|
|
const auto temperature = state_->config.ambient_temperature_millikelvin;
|
|
const auto split =
|
|
biology::split_cell(*expressed, *successor, found->growth, found->body, reserve,
|
|
temperature, state_->revamp.split_share_per_thousand,
|
|
state_->revamp.split_min_growth, state_->revamp.body);
|
|
if (!split && split.error() == biology::BuddingError::development)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto identity = cellular_bud_identity(state_->region, next_bud_sequence);
|
|
std::optional<biology::CellularPosition> spot;
|
|
if (split) {
|
|
const auto shrunk = biology::metabolic_budget(
|
|
*expressed, split->parent_growth, {temperature, {}}, 1000, state_->revamp.body);
|
|
const auto born = biology::metabolic_budget(
|
|
*successor, split->child_growth, {temperature, {}}, 1000, state_->revamp.body);
|
|
if (!shrunk || !born)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto position =
|
|
bud_position(*found, shrunk->phenotype.extent, born->phenotype.extent,
|
|
next_lives, next_archive, state_->config);
|
|
if (!position)
|
|
return std::unexpected{position.error()};
|
|
spot = *position;
|
|
}
|
|
if (!split || !spot || identity == 0 ||
|
|
next_lives.size() >= state_->revamp.organism_cap ||
|
|
next_archive.organism(identity)) {
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::split_refused});
|
|
continue;
|
|
}
|
|
if (next_offspring_revisions.size() >= biology::max_archived_genomes ||
|
|
!next_archive.admit(*successor) ||
|
|
!next_archive.record_birth(identity, successor->id(), {proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
next_offspring_revisions.push_back({selection.life_id, found->offspring_genome,
|
|
selection.successor_id, proposal->end_tick});
|
|
if (!add_inventory(next_spent, payment->spent))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
auto returned = cost;
|
|
returned.energy.value = payment->energy;
|
|
reclaims.emplace_back(returned, found->position);
|
|
CellularOwnedLife child{};
|
|
child.identity = {identity, identity, successor->id(), identity, {proposal->end_tick}};
|
|
child.source = found->source;
|
|
child.growth = split->child_growth;
|
|
child.position = *spot;
|
|
child.body = split->child_body;
|
|
child.reserve = split->child_reserve;
|
|
child.parent_life = found->identity.life;
|
|
child.offspring_genome = successor->id();
|
|
child.revamp.affinity.score = found->revamp.affinity.score;
|
|
child.revamp.progress = found->revamp.progress;
|
|
found->growth = split->parent_growth;
|
|
found->body = split->parent_body;
|
|
found->reserve = split->parent_reserve;
|
|
found->offspring_genome = successor->id();
|
|
pending = {};
|
|
if (selection.become) {
|
|
// One-way: the player continues as the offspring; the founder is wildlife.
|
|
child.account = found->account;
|
|
found->account = {};
|
|
found->revamp.active_ticks = 0;
|
|
}
|
|
++next_bud_sequence;
|
|
next_lives.insert(std::ranges::lower_bound(
|
|
next_lives, identity, {},
|
|
[](const CellularOwnedLife& life) { return life.identity.life; }),
|
|
child);
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::split_applied});
|
|
continue;
|
|
}
|
|
const auto parent = next_archive.find(cellular_offspring_genome(*found));
|
|
if (!parent || !found->mutation.offer.has_value())
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (selection.operator_id == 0) {
|
|
// ADR-0120 amendment: a decline consumes the offer and changes nothing else; its
|
|
// reserved successor identity stays unused. Banked credit may earn the next offer.
|
|
found->mutation.offer.reset();
|
|
found->mutation.offer_tick = 0;
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::declined});
|
|
continue;
|
|
}
|
|
const auto offer = found->mutation.offer.value_or(biology::MutationOffer{});
|
|
if (inheritance_rules) {
|
|
const auto selected =
|
|
biology::select_mutation(*parent, offer.context, offer, selection.operator_id,
|
|
selection.successor_id, selection.successor_id);
|
|
if (!selected)
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
if (next_offspring_revisions.size() >= biology::max_archived_genomes ||
|
|
!next_archive.admit(*selected))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
next_offspring_revisions.push_back({selection.life_id, found->offspring_genome,
|
|
selection.successor_id, proposal->end_tick});
|
|
found->offspring_genome = selection.successor_id;
|
|
found->mutation.offer.reset();
|
|
found->mutation.offer_tick = 0;
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::offspring_plan_applied});
|
|
continue;
|
|
}
|
|
auto transition = biology::fund_mutation_at_growth(
|
|
*parent, offer.context, offer, selection.operator_id, selection.successor_id,
|
|
selection.successor_id, found->reserve,
|
|
state_->rules_version >= cellular_lives_maturation_rules ? found->growth
|
|
: offer.context.growth);
|
|
if (!transition) {
|
|
if (transition.error() == biology::MutationError::insufficient_funding) {
|
|
mutation_results.push_back({selection.life_id, selection.successor_id,
|
|
CellularMutationResult::insufficient_funding});
|
|
continue;
|
|
}
|
|
return std::unexpected{CellularLivesError::mutation};
|
|
}
|
|
if (!next_archive.record_mutation(found->identity.organism, transition->successor,
|
|
{proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
if (transition->intake.energy.value >
|
|
std::numeric_limits<std::uint64_t>::max() - next_heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
next_heat.energy.value += transition->intake.energy.value;
|
|
found->identity.genome = selection.successor_id;
|
|
found->body = transition->body;
|
|
found->reserve = transition->reserve;
|
|
found->mutation.offer.reset();
|
|
found->mutation.offer_tick = 0;
|
|
mutation_results.push_back(
|
|
{selection.life_id, selection.successor_id, CellularMutationResult::applied});
|
|
}
|
|
// Rules 4 budding (ADR-0125), after mutations and in parent life order: a parent that
|
|
// died this tick cannot bud, and a bud born this tick asked for nothing.
|
|
std::vector<CellularBudExecution> bud_results;
|
|
for (const auto& request : ordered) {
|
|
if (!bud_rules || !request.intent.bud)
|
|
continue;
|
|
auto parent = std::ranges::lower_bound(
|
|
next_lives, request.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (parent == next_lives.end() || parent->identity.life != request.life_id) {
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::life_died});
|
|
continue;
|
|
}
|
|
if (parent->presence == CellularPresence::suspended) {
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::not_able});
|
|
continue; // Out of the world (ADR-0128).
|
|
}
|
|
if (revamp_rules && parent->revamp.members > 1) {
|
|
// An organism's bud is an internal cell (reproduction plan section 6): litter adds
|
|
// members, funded from the shared reserve. Wildlife organisms stop one short of
|
|
// the emergence threshold.
|
|
const auto expressed_genome = next_archive.find(parent->identity.genome);
|
|
if (!expressed_genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto& traits = expressed_genome->cellular_traits();
|
|
Random roll{state_->world * 0x9e3779b97f4a7c15ULL ^ request.life_id ^
|
|
proposal->end_tick * 0xbf58476d1ce4e5b9ULL};
|
|
const auto added = cellular_litter_count(traits ? traits->litter : 0U, roll.next(),
|
|
state_->revamp.bounds.max_litter);
|
|
auto members = std::uint32_t{parent->revamp.members} + added;
|
|
if (parent->account == LifeAccount{})
|
|
members = std::min(members, state_->revamp.emerge_members - 1);
|
|
const auto grown = members > parent->revamp.members
|
|
? organism_genome(*expressed_genome, members)
|
|
: std::unexpected{CellularLivesError::biology};
|
|
const auto target = grown ? biology::metabolic_budget(
|
|
*grown, parent->growth,
|
|
{state_->config.ambient_temperature_millikelvin, {}},
|
|
1000, state_->revamp.body)
|
|
: std::unexpected{biology::DevelopmentError::overflow};
|
|
const auto rules = biology::rules_for(expressed_genome->development_version());
|
|
// The same fee per bud action as a single cell's, then the new tissue.
|
|
const auto fee = cellular_mutation_cost(
|
|
{.cost = state_->revamp.bud_fee,
|
|
.cost_scale_percent = state_->revamp.bud_fee_scale_percent});
|
|
auto body = parent->body;
|
|
auto reserve = parent->reserve;
|
|
bool funded = reserve.energy.value >= fee.energy.value;
|
|
for (std::size_t c = 0; c < fee.matter.size(); ++c)
|
|
funded = funded && reserve.matter[c].value >= fee.matter[c].value;
|
|
if (funded) {
|
|
reserve.energy.value -= fee.energy.value;
|
|
for (std::size_t c = 0; c < fee.matter.size(); ++c)
|
|
reserve.matter[c].value -= fee.matter[c].value;
|
|
}
|
|
auto heat = accounting::Inventory{};
|
|
if (!target || !rules || !funded ||
|
|
!rebody(body, reserve, heat, target->body, rules->construction_per_kilogram)) {
|
|
bud_results.push_back({request.life_id, 0,
|
|
target ? CellularBudResult::insufficient_funding
|
|
: CellularBudResult::not_able});
|
|
if (target && parent->account != LifeAccount{})
|
|
activity_of(request.life_id)[biology::CellularSignal::bud_refused] += 1;
|
|
continue;
|
|
}
|
|
if (!add_inventory(next_heat, heat))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
reclaims.emplace_back(fee, parent->position);
|
|
parent->body = body;
|
|
parent->reserve = reserve;
|
|
parent->revamp.members = static_cast<std::uint16_t>(members);
|
|
if (parent->account != LifeAccount{}) {
|
|
activity_of(request.life_id)[biology::CellularSignal::bud_done] += 1;
|
|
parent->revamp.progress.buds += 1;
|
|
}
|
|
// The bud is internal: the organism reports itself as the bud.
|
|
bud_results.push_back({request.life_id, request.life_id, CellularBudResult::budded});
|
|
continue;
|
|
}
|
|
// ADR-0137 (rules 7): on a twin roll the bud investment is split between two buds
|
|
// (each a quarter of the parent's body). The parent's reported result is the
|
|
// first bud's; a twin that finds no room is simply not made.
|
|
// Rules 13 (mutation plan section 9): litter gives extra offspring sharing one investment,
|
|
// whole hundreds guaranteed and the rest a chance, up to the declared maximum.
|
|
std::uint32_t litter_count = 1;
|
|
accounting::Inventory fee{};
|
|
if (revamp_rules) {
|
|
const auto expressed_genome = next_archive.find(parent->identity.genome);
|
|
const auto& traits =
|
|
expressed_genome ? expressed_genome->cellular_traits() : std::nullopt;
|
|
const auto litter = traits ? std::uint32_t{traits->litter} : 0U;
|
|
Random roll{state_->world * 0x9e3779b97f4a7c15ULL ^ request.life_id ^
|
|
proposal->end_tick * 0xbf58476d1ce4e5b9ULL};
|
|
litter_count =
|
|
cellular_litter_count(litter, roll.next(), state_->revamp.bounds.max_litter);
|
|
fee = cellular_mutation_cost(
|
|
{.cost = state_->revamp.bud_fee,
|
|
.cost_scale_percent = state_->revamp.bud_fee_scale_percent});
|
|
bool affordable = parent->reserve.energy.value >= fee.energy.value;
|
|
for (std::size_t c = 0; c < fee.matter.size(); ++c)
|
|
affordable = affordable && parent->reserve.matter[c].value >= fee.matter[c].value;
|
|
if (!affordable) {
|
|
bud_results.push_back(
|
|
{request.life_id, 0, CellularBudResult::insufficient_funding});
|
|
if (parent->account != LifeAccount{})
|
|
activity_of(request.life_id)[biology::CellularSignal::bud_refused] += 1;
|
|
continue;
|
|
}
|
|
}
|
|
const bool twins = [&] {
|
|
if (state_->rules_version < cellular_lives_reproduction_rules || revamp_rules)
|
|
return false;
|
|
const auto parent_genome = next_archive.find(parent->identity.genome);
|
|
const auto offspring_genome = next_archive.find(cellular_offspring_genome(*parent));
|
|
if (!parent_genome || !offspring_genome)
|
|
return false;
|
|
const auto skill = parent_genome->parameter(biology::Capability::reproduction);
|
|
// Twins split one whole bud: the parent must afford that whole bud first.
|
|
return skill &&
|
|
cellular_twin_bud(state_->world, state_->region, request.life_id,
|
|
proposal->end_tick, *skill) &&
|
|
biology::fund_offspring(*parent_genome, *offspring_genome, parent->growth,
|
|
parent->reserve,
|
|
state_->config.ambient_temperature_millikelvin)
|
|
.has_value();
|
|
}();
|
|
const auto copies = revamp_rules ? litter_count : (twins ? 2U : 1U);
|
|
for (std::uint32_t copy = 0; copy < copies; ++copy) {
|
|
if (copy == 1)
|
|
// Inserting the first bud may have moved the parent; find it again.
|
|
parent = std::ranges::lower_bound(
|
|
next_lives, request.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
const bool twin = copy == 1;
|
|
const auto temperature = state_->config.ambient_temperature_millikelvin;
|
|
const auto genome = next_archive.find(cellular_offspring_genome(*parent));
|
|
const auto expressed = next_archive.find(parent->identity.genome);
|
|
const auto parent_budget =
|
|
budget_for(next_archive, *parent, temperature, state_->revamp.body);
|
|
if (!genome || !expressed || !parent_budget)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
// Rules 13: a bud made with the reserve covering twice its cost.
|
|
bool surplus = false;
|
|
if (revamp_rules && !twin) {
|
|
const auto cost = biology::offspring_cost(*expressed, *genome, temperature);
|
|
surplus =
|
|
cost.has_value() && parent->reserve.energy.value / 2 >= cost->energy.value;
|
|
for (std::size_t c = 0; surplus && c < cost->matter.size(); ++c)
|
|
surplus = parent->reserve.matter[c].value / 2 >= cost->matter[c].value;
|
|
}
|
|
const auto transition = biology::fund_offspring(*expressed, *genome, parent->growth,
|
|
parent->reserve, temperature, copies);
|
|
if (revamp_rules && !twin && parent->account != LifeAccount{}) {
|
|
using S = biology::CellularSignal;
|
|
auto& a = activity_of(request.life_id);
|
|
if (transition) {
|
|
a[S::bud_done] += 1;
|
|
a[S::bud_with_surplus] += surplus ? 1 : 0;
|
|
parent->revamp.progress.buds += 1;
|
|
} else if (transition.error() == biology::BuddingError::insufficient_funding) {
|
|
a[S::bud_refused] += 1;
|
|
}
|
|
}
|
|
if (!transition) {
|
|
if (transition.error() == biology::BuddingError::development)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
if (!twin)
|
|
bud_results.push_back(
|
|
{request.life_id, 0,
|
|
transition.error() == biology::BuddingError::insufficient_funding
|
|
? CellularBudResult::insufficient_funding
|
|
: CellularBudResult::not_able});
|
|
break;
|
|
}
|
|
const auto bud_budget =
|
|
biology::metabolic_budget(*genome, transition->growth, {temperature, {}});
|
|
if (!bud_budget || bud_budget->body.matter != transition->body.matter)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto identity = cellular_bud_identity(state_->region, next_bud_sequence);
|
|
const auto position =
|
|
bud_position(*parent, parent_budget->phenotype.extent, bud_budget->phenotype.extent,
|
|
next_lives, next_archive, state_->config);
|
|
if (!position)
|
|
return std::unexpected{position.error()};
|
|
if (identity == 0 || !*position ||
|
|
next_lives.size() >= biology::max_cellular_tick_lives ||
|
|
(revamp_rules && next_lives.size() >= state_->revamp.organism_cap) ||
|
|
next_archive.organism(identity)) {
|
|
if (!twin)
|
|
bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement});
|
|
break;
|
|
}
|
|
if (!add_inventory(next_heat, accounting::Inventory{transition->heat, {}}) ||
|
|
!next_archive.record_birth(identity, genome->id(), {proposal->end_tick}))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
parent->reserve = transition->parent_reserve;
|
|
if (revamp_rules && !twin) {
|
|
// The fee, once per bud action, returns to the region; then control, if asked.
|
|
for (std::size_t c = 0; c < fee.matter.size(); ++c)
|
|
parent->reserve.matter[c].value -=
|
|
std::min(parent->reserve.matter[c].value, fee.matter[c].value);
|
|
parent->reserve.energy.value -=
|
|
std::min(parent->reserve.energy.value, fee.energy.value);
|
|
reclaims.emplace_back(fee, parent->position);
|
|
}
|
|
CellularOwnedLife bud{};
|
|
bud.identity = {identity, identity, genome->id(), identity, {proposal->end_tick}};
|
|
bud.source = parent->source;
|
|
bud.growth = transition->growth;
|
|
bud.position = **position;
|
|
bud.body = transition->body;
|
|
bud.reserve = transition->reserve;
|
|
bud.parent_life = parent->identity.life;
|
|
if (inheritance_rules)
|
|
bud.offspring_genome = genome->id();
|
|
if (revamp_rules) {
|
|
// Offspring start with the parent's scores and lineage progress.
|
|
bud.revamp.affinity.score = parent->revamp.affinity.score;
|
|
bud.revamp.progress = parent->revamp.progress;
|
|
const auto asked = std::ranges::lower_bound(ordered, request.life_id, {},
|
|
&CellularLifeIntent::life_id);
|
|
if (!twin && asked != ordered.end() && asked->life_id == request.life_id &&
|
|
asked->intent.become) {
|
|
// One-way: the player continues as the first bud; the parent is wildlife.
|
|
bud.account = parent->account;
|
|
parent->account = {};
|
|
parent->revamp.offer = {};
|
|
parent->revamp.active_ticks = 0;
|
|
}
|
|
}
|
|
// Foreign residents can have a higher origin-region namespace. Keep
|
|
// the sequence sorted even before the next parent's lookup/twin.
|
|
const auto slot = std::ranges::lower_bound(
|
|
next_lives, identity, {},
|
|
[](const CellularOwnedLife& life) { return life.identity.life; });
|
|
next_lives.insert(slot, bud);
|
|
++next_bud_sequence;
|
|
if (!twin)
|
|
bud_results.push_back({request.life_id, identity, CellularBudResult::budded});
|
|
}
|
|
}
|
|
std::ranges::sort(next_lives, {},
|
|
[](const CellularOwnedLife& life) { return life.identity.life; });
|
|
// Rules 13 (reproduction plan section 7): an owned organism at the emergence threshold that
|
|
// asks leaves for the world. Its matter is a recorded export; its life ends as emerged.
|
|
auto next_boundary = state_->boundary;
|
|
if (revamp_rules) {
|
|
for (const auto& request : ordered) {
|
|
if (!request.intent.emerge)
|
|
continue;
|
|
const auto life = std::ranges::lower_bound(
|
|
next_lives, request.life_id, {},
|
|
[](const CellularOwnedLife& value) { return value.identity.life; });
|
|
if (life == next_lives.end() || life->identity.life != request.life_id ||
|
|
!cellular_can_emerge(*life, state_->revamp))
|
|
continue;
|
|
auto single = *life;
|
|
single.revamp.members = 1;
|
|
const auto budget =
|
|
budget_for(next_archive, single, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!budget ||
|
|
!next_archive.record_death(life->identity.organism, {proposal->end_tick}) ||
|
|
!add_inventory(next_boundary.outgoing, life->body) ||
|
|
!add_inventory(next_boundary.outgoing, life->reserve))
|
|
return std::unexpected{CellularLivesError::archive};
|
|
next_corpses.push_back({life->identity.life,
|
|
life->identity.organism,
|
|
life->source,
|
|
proposal->end_tick,
|
|
life->position,
|
|
life->growth,
|
|
budget->phenotype.extent,
|
|
{},
|
|
biology::CellularDeathCause::emerged,
|
|
0,
|
|
life->parent_life,
|
|
life->offspring_genome});
|
|
next_lives.erase(life);
|
|
}
|
|
}
|
|
// Rules 5 presence (ADR-0128), after deaths, mutations and buds: a death in this tick
|
|
// is final before any presence change.
|
|
std::vector<std::uint64_t> resume_blocked;
|
|
if (presence_rules) {
|
|
for (auto& life : next_lives) {
|
|
const auto request = std::ranges::lower_bound(ordered, life.identity.life, {},
|
|
&CellularLifeIntent::life_id);
|
|
if (request == ordered.end() || request->life_id != life.identity.life)
|
|
continue; // Born this tick: active.
|
|
const bool frozen = request->intent.frozen;
|
|
if (life.presence == CellularPresence::active && frozen) {
|
|
life.presence = CellularPresence::lingering;
|
|
life.frozen_since = proposal->end_tick;
|
|
} else if (life.presence == CellularPresence::lingering && !frozen) {
|
|
life.presence = CellularPresence::active;
|
|
life.frozen_since = 0;
|
|
} else if (life.presence == CellularPresence::lingering &&
|
|
proposal->end_tick - life.frozen_since >= cellular_linger_ticks) {
|
|
life.presence = CellularPresence::suspended;
|
|
} else if (life.presence == CellularPresence::suspended && !frozen) {
|
|
const auto budget =
|
|
budget_for(next_archive, life, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!budget)
|
|
return std::unexpected{budget.error()};
|
|
const auto spot = resume_position(life, budget->phenotype.extent, next_lives,
|
|
next_archive, state_->config);
|
|
if (!spot)
|
|
return std::unexpected{spot.error()};
|
|
if (*spot) {
|
|
life.position = **spot;
|
|
life.presence = CellularPresence::active;
|
|
life.frozen_since = 0;
|
|
} else {
|
|
resume_blocked.push_back(life.identity.life);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// ADR-0157: old-size actions finish first. A newborn, frozen life or a life
|
|
// resuming from suspension did not take an active step and cannot grow here.
|
|
// Expansion holds the existing lower corner fixed; earlier IDs claim space first.
|
|
std::vector<CellularGrowthExecution> growth_results;
|
|
if (state_->rules_version >= cellular_lives_maturation_rules) {
|
|
for (auto& life : next_lives) {
|
|
const auto input = std::ranges::lower_bound(ordered, life.identity.life, {},
|
|
&CellularLifeIntent::life_id);
|
|
const auto previous =
|
|
std::ranges::lower_bound(state_->lives, life.identity.life, {},
|
|
[](const auto& old) { return old.identity.life; });
|
|
if (input == ordered.end() || input->life_id != life.identity.life ||
|
|
input->intent.frozen || life.presence != CellularPresence::active ||
|
|
previous == state_->lives.end() || previous->identity.life != life.identity.life ||
|
|
previous->presence == CellularPresence::suspended ||
|
|
life.growth.realized_per_thousand == 1000)
|
|
continue;
|
|
const auto genome = life_genome(next_archive, life);
|
|
if (!genome)
|
|
return std::unexpected(genome.error());
|
|
// Rules 13: growth speed scales the per-tick step; the fraction carries over.
|
|
auto step = cellular_growth_per_tick;
|
|
const auto& traits = genome->cellular_traits();
|
|
if (revamp_rules && traits) {
|
|
const auto centi =
|
|
life.revamp.growth_carry +
|
|
state_->revamp.growth_per_tick_centi_mille * traits->growth_speed / 100;
|
|
step = centi / 100;
|
|
life.revamp.growth_carry = centi % 100;
|
|
if (step == 0)
|
|
continue;
|
|
}
|
|
const auto budget = biology::metabolic_budget(
|
|
*genome, life.growth,
|
|
{state_->config.ambient_temperature_millikelvin, life.reserve}, step,
|
|
state_->revamp.body);
|
|
if (!budget || budget->body != life.body)
|
|
return std::unexpected(CellularLivesError::biology);
|
|
const auto& move = budget->construction;
|
|
if (move.after == life.growth) {
|
|
if (revamp_rules && life.account != LifeAccount{}) {
|
|
// Which channels held the step back: what an ample reserve's step needs.
|
|
accounting::Inventory ample{{1ULL << 50U}, {}};
|
|
for (auto& channel : ample.matter)
|
|
channel.value = 1ULL << 50U;
|
|
const auto full = biology::metabolic_budget(
|
|
*genome, life.growth,
|
|
{state_->config.ambient_temperature_millikelvin, ample}, step,
|
|
state_->revamp.body);
|
|
if (full) {
|
|
using S = biology::CellularSignal;
|
|
constexpr std::array blocked{S::blocked_carbon, S::blocked_nitrogen,
|
|
S::blocked_phosphorus, S::blocked_other};
|
|
auto& a = activity_of(life.identity.life);
|
|
for (std::size_t c = 0; c < blocked.size(); ++c)
|
|
if (full->construction.intake.matter[c].value >
|
|
life.reserve.matter[c].value)
|
|
a[blocked.at(c)] = 1;
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
const auto grown = biology::metabolic_budget(
|
|
*genome, move.after, {state_->config.ambient_temperature_millikelvin, {}});
|
|
if (!grown)
|
|
return std::unexpected(CellularLivesError::biology);
|
|
const auto extent = grown->phenotype.extent;
|
|
bool clear = extent <= state_->config.area.width_um &&
|
|
extent <= state_->config.area.height_um &&
|
|
life.position.x_um <= state_->config.area.width_um - extent &&
|
|
life.position.y_um <= state_->config.area.height_um - extent;
|
|
for (const auto& other : next_lives) {
|
|
if (!clear || other.identity.life == life.identity.life ||
|
|
other.presence == CellularPresence::suspended)
|
|
continue;
|
|
const auto obstacle =
|
|
budget_for(next_archive, other, state_->config.ambient_temperature_millikelvin,
|
|
state_->revamp.body);
|
|
if (!obstacle)
|
|
return std::unexpected(obstacle.error());
|
|
clear = separated(life.position.x_um, other.position.x_um, extent,
|
|
obstacle->phenotype.extent) ||
|
|
separated(life.position.y_um, other.position.y_um, extent,
|
|
obstacle->phenotype.extent);
|
|
}
|
|
if (!clear)
|
|
continue; // No partial spatial retry, relocation or spending.
|
|
if (!subtract_inventory(life.reserve, move.intake) ||
|
|
!add_inventory(life.reserve, move.release) ||
|
|
!add_inventory(next_heat, accounting::Inventory{move.intake.energy, {}}))
|
|
return std::unexpected(CellularLivesError::overflow);
|
|
growth_results.push_back(
|
|
{life.identity.life, life.growth, move.after, move.intake, move.release});
|
|
life.growth = move.after;
|
|
life.body = grown->body;
|
|
}
|
|
}
|
|
// Rules 13: each owned, active life's activity moves its affinity; active play earns offers.
|
|
if (revamp_rules) {
|
|
using S = biology::CellularSignal;
|
|
for (auto& life : next_lives) {
|
|
const auto request = std::ranges::lower_bound(ordered, life.identity.life, {},
|
|
&CellularLifeIntent::life_id);
|
|
if (life.account == LifeAccount{} || request == ordered.end() ||
|
|
request->life_id != life.identity.life || request->intent.frozen ||
|
|
life.presence != CellularPresence::active)
|
|
continue; // Wildlife, newborns, and frozen or absent cells.
|
|
auto a = activity_of(life.identity.life);
|
|
std::uint64_t reserve{}, body{};
|
|
for (std::size_t c = 0; c < life.body.matter.size(); ++c) {
|
|
reserve += life.reserve.matter[c].value;
|
|
body += life.body.matter[c].value;
|
|
}
|
|
a[S::reserve_over_body] = reserve > body ? 1 : 0;
|
|
a[S::regrowing] = life.growth.realized_per_thousand < 1000 ? 1 : 0;
|
|
a[S::fully_grown] = life.growth.realized_per_thousand == 1000 ? 1 : 0;
|
|
biology::cellular_affinity_tick(
|
|
life.revamp.affinity, a, state_->revamp.mutations,
|
|
{state_->revamp.offers.score_min, state_->revamp.offers.score_max});
|
|
if (life.revamp.offer.count != 0 ||
|
|
++life.revamp.active_ticks < state_->revamp.offer_interval_ticks)
|
|
continue;
|
|
life.revamp.active_ticks = 0;
|
|
const auto plan = next_archive.find(cellular_offspring_genome(life));
|
|
if (!plan)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
const auto offer =
|
|
cellular_draw_offer(*plan, life.revamp, state_->revamp, state_->world,
|
|
state_->region, life.identity.life, proposal->end_tick);
|
|
if (offer) {
|
|
life.revamp.offer = *offer;
|
|
life.revamp.events = offer->event_index;
|
|
}
|
|
}
|
|
}
|
|
std::ranges::sort(next_corpses, {}, &CellularOwnedCorpse::organism);
|
|
if (proposal->heat_released.value >
|
|
std::numeric_limits<std::uint64_t>::max() - next_heat.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
next_heat.energy.value += proposal->heat_released.value;
|
|
for (const auto& update : proposal->patches) {
|
|
const auto found =
|
|
std::ranges::lower_bound(habitat_config.patches, update.address, {},
|
|
[](const auto& patch) { return patch.address; });
|
|
if (found == habitat_config.patches.end() || found->address != update.address)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
found->stock = update.stock;
|
|
}
|
|
// Rules 3 detritus at empty cells becomes new patches; create() revalidates the map.
|
|
// Format 2 (ADR-0136): new bubbles take the next deposit ids, and a deposit emptied this
|
|
// tick is gone.
|
|
const bool deposits = habitat_config.format == biology::cellular_habitat_deposit_format ||
|
|
habitat_config.format == biology::cellular_habitat_liquid_format;
|
|
for (auto made : proposal->new_patches) {
|
|
const auto at = std::ranges::lower_bound(habitat_config.patches, made.address, {},
|
|
[](const auto& patch) { return patch.address; });
|
|
if (at != habitat_config.patches.end() && at->address == made.address)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
if (deposits) {
|
|
if (habitat_config.next_deposit == std::numeric_limits<std::uint32_t>::max())
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
made.id = habitat_config.next_deposit++;
|
|
}
|
|
habitat_config.patches.insert(at, made);
|
|
}
|
|
// Rules 13: the spent pool drips back as bubbles at seeded random spots.
|
|
if (revamp_rules &&
|
|
!cellular_drip_spent(habitat_config, next_spent, state_->revamp, state_->world,
|
|
state_->region, proposal->end_tick, state_->nursery_config.source))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
// Rules 13: paid mutation costs return as bubbles at seeded random spots.
|
|
for (std::size_t k = 0; k < reclaims.size(); ++k)
|
|
if (!cellular_reclaim(habitat_config, reclaims[k].first,
|
|
state_->world * 0x9e3779b97f4a7c15ULL ^
|
|
proposal->end_tick * 0x94d049bbULL ^ k,
|
|
reclaims[k].second, state_->nursery_config.source))
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
if (deposits)
|
|
std::erase_if(habitat_config.patches, [](const biology::CellularPatch& patch) {
|
|
return patch.stock == accounting::Inventory{};
|
|
});
|
|
// Rules 12: after every life fed where the food was, bubbles move with the current and
|
|
// the drift that this tick's moving cells induce, then touching bubbles merge.
|
|
if (liquid_rules) {
|
|
std::vector<biology::CellularWake> wakes;
|
|
wakes.reserve(proposal->lives.size());
|
|
for (const auto& result : proposal->lives) {
|
|
const auto input = std::ranges::lower_bound(
|
|
inputs, result.life_id, {},
|
|
[](const biology::CellularLifeStepInput& value) { return value.life_id; });
|
|
if (input == inputs.end() || input->life_id != result.life_id || input->intent.frozen)
|
|
continue;
|
|
const auto flow =
|
|
state_->field->at_footprint(result.candidate.position, input->extent_um);
|
|
wakes.push_back({result.candidate.position, input->extent_um,
|
|
result.candidate.motion.velocity_x_q10 + flow.x_q10,
|
|
result.candidate.motion.velocity_y_q10 + flow.y_q10});
|
|
}
|
|
auto moved = biology::advect_cellular_deposits(habitat_config, *state_->field, wakes,
|
|
state_->liquid.deposits);
|
|
if (!moved)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
habitat_config = std::move(moved->config);
|
|
}
|
|
auto next_habitat = biology::CellularHabitat::create(std::move(habitat_config));
|
|
if (!next_habitat)
|
|
return std::unexpected{CellularLivesError::habitat};
|
|
const auto total = validate_state(
|
|
state_->world, state_->region, state_->frame,
|
|
CellularLivesConfig{state_->config.area, proposal->end_tick,
|
|
state_->config.ambient_temperature_millikelvin},
|
|
state_->nursery_config, **next_habitat, next_lives, next_corpses, next_archive,
|
|
state_->nursery, next_heat, state_->opening_total, engulf_rules, bud_rules,
|
|
next_bud_sequence, presence_rules,
|
|
state_->format_version >= cellular_lives_migration_format ? &next_boundary : nullptr,
|
|
inheritance_rules ? &next_offspring_revisions : nullptr, next_spent, revamp_rules);
|
|
if (!total)
|
|
return std::unexpected{total.error()};
|
|
|
|
auto next = std::make_unique<State>(
|
|
state_->world, state_->region, state_->frame,
|
|
CellularLivesConfig{state_->config.area, proposal->end_tick,
|
|
state_->config.ambient_temperature_millikelvin},
|
|
state_->nursery_config, std::move(*next_habitat), std::move(next_lives),
|
|
std::move(next_corpses), next_archive, state_->nursery, next_heat, state_->opening_total,
|
|
*total, state_->format_version, state_->rules_version, next_boundary);
|
|
next->next_bud_sequence = next_bud_sequence;
|
|
next->offspring_revisions = std::move(next_offspring_revisions);
|
|
next->light = state_->light;
|
|
next->captured = state_->captured;
|
|
next->liquid = state_->liquid;
|
|
next->field = state_->field;
|
|
next->revamp = state_->revamp;
|
|
next->spent = next_spent;
|
|
// ADR-0175: light, from this tick's own intentions, credited to every active,
|
|
// unfrozen photosynthetic survivor's reserve and to the boundary inflow together.
|
|
std::vector<std::pair<std::uint64_t, std::uint64_t>> lit_lives;
|
|
if (next->light.numerator != 0) {
|
|
for (auto& life : next->lives) {
|
|
const auto left = next->light.entitlement.value - next->captured.value;
|
|
if (left == 0)
|
|
break;
|
|
if (life.presence != CellularPresence::active)
|
|
continue;
|
|
const auto genome = next->archive.find(life.identity.genome);
|
|
if (!genome)
|
|
return std::unexpected{CellularLivesError::archive};
|
|
if (!genome->carries(biology::Capability::photosynthesis))
|
|
continue;
|
|
const auto input = std::ranges::lower_bound(
|
|
ordered, life.identity.life, {},
|
|
[](const CellularLifeIntent& value) { return value.life_id; });
|
|
// Newborn buds had no intention this tick and capture from the next one.
|
|
if (input == ordered.end() || input->life_id != life.identity.life ||
|
|
input->intent.frozen)
|
|
continue;
|
|
const auto budget =
|
|
budget_for(next->archive, life, next->config.ambient_temperature_millikelvin,
|
|
next->revamp.body);
|
|
if (!budget)
|
|
return std::unexpected{CellularLivesError::biology};
|
|
const auto energy =
|
|
cellular_light_capture(*genome, budget->phenotype.extent, next->light,
|
|
input->intent.movement != biology::CellularIntent{});
|
|
if (!energy)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
const auto granted = std::min(*energy, left);
|
|
constexpr auto most = std::numeric_limits<std::uint64_t>::max();
|
|
if (granted > most - life.reserve.energy.value ||
|
|
granted > most - next->boundary.incoming.energy.value ||
|
|
granted > most - next->current_total.energy.value)
|
|
return std::unexpected{CellularLivesError::overflow};
|
|
life.reserve.energy.value += granted;
|
|
next->boundary.incoming.energy.value += granted;
|
|
next->current_total.energy.value += granted;
|
|
next->captured.value += granted;
|
|
if (granted != 0)
|
|
lit_lives.emplace_back(life.identity.life, granted);
|
|
}
|
|
}
|
|
std::vector<CellularLifeTickFeedback> feedback;
|
|
feedback.reserve(proposal->lives.size());
|
|
for (const auto& result : proposal->lives) {
|
|
const auto input =
|
|
std::ranges::lower_bound(ordered, result.life_id, {},
|
|
[](const CellularLifeIntent& value) { return value.life_id; });
|
|
feedback.push_back({result.life_id, proposal->end_tick, result.candidate.reserve_after,
|
|
result.candidate.maintenance_cost, result.candidate.movement_cost,
|
|
result.candidate.movement_status, result.candidate.intake_status,
|
|
result.engulf, result.prey_id, std::nullopt, 0,
|
|
CellularPresence::active, false});
|
|
if (const auto bud =
|
|
std::ranges::find(bud_results, result.life_id, &CellularBudExecution::parent_life);
|
|
bud != bud_results.end()) {
|
|
feedback.back().bud = bud->result;
|
|
feedback.back().bud_life = bud->bud_life;
|
|
}
|
|
if (input == ordered.end() || input->life_id != result.life_id)
|
|
return std::unexpected{CellularLivesError::invalid_intents};
|
|
feedback.back().exclude = input->intent.exclude;
|
|
}
|
|
// ADR-0128: each surviving life reports its presence after the tick; a suspended life,
|
|
// which took no step, reports its unchanged reserve and any blocked resume.
|
|
for (const auto& life : next->lives) {
|
|
auto entry =
|
|
std::ranges::find(feedback, life.identity.life, &CellularLifeTickFeedback::life_id);
|
|
if (entry == feedback.end()) {
|
|
feedback.push_back({life.identity.life,
|
|
proposal->end_tick,
|
|
life.reserve,
|
|
{},
|
|
{},
|
|
biology::CellularMovementStatus::not_requested,
|
|
biology::CellularIntakeStatus::not_requested,
|
|
biology::CellularEngulfStatus::not_requested,
|
|
0,
|
|
std::nullopt,
|
|
0,
|
|
life.presence,
|
|
false});
|
|
entry = std::prev(feedback.end());
|
|
}
|
|
entry->presence = life.presence;
|
|
if (state_->rules_version >= cellular_lives_maturation_rules)
|
|
entry->reserve = life.reserve; // Includes funded growth/mutation/budding.
|
|
entry->resume_blocked =
|
|
std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end();
|
|
}
|
|
for (const auto& [life, energy] : lit_lives) {
|
|
const auto entry = std::ranges::find(feedback, life, &CellularLifeTickFeedback::life_id);
|
|
if (entry != feedback.end())
|
|
entry->light = {energy};
|
|
}
|
|
std::ranges::sort(feedback, {}, &CellularLifeTickFeedback::life_id);
|
|
state_.swap(next);
|
|
last_tick_feedback_ = std::move(feedback);
|
|
return CellularTickExecution{std::move(*proposal), std::move(mutation_results),
|
|
std::move(bud_results), std::move(growth_results)};
|
|
}
|
|
} // namespace evo::server
|