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>
623 lines
35 KiB
C++
623 lines
35 KiB
C++
#pragma once
|
|
|
|
#include "evo/biology/budding.hpp"
|
|
#include "evo/client/organism_view.hpp"
|
|
#include "evo/network/session_grant.hpp"
|
|
#include "evo/server/cellular_region_host.hpp"
|
|
#include "evo/server/pg_slot.hpp"
|
|
#include "evo/server/postgres_action_ledger.hpp"
|
|
#include "evo/server/postgres_control_ledger.hpp"
|
|
#include "evo/server/region_sessions.hpp"
|
|
#include "evo/server/session_window.hpp"
|
|
#include "m10_bridge.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <cstdio>
|
|
#include <fstream>
|
|
#include <iterator>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace evo::server_app {
|
|
// Rules 12: moving bubbles listed per perception, nearest first (the tuning file's trial
|
|
// food.visible_moving_bubbles). Pools are always listed.
|
|
inline constexpr std::size_t cellular_visible_moving_bubbles = 256;
|
|
// Profile-4 network boundary. Biology and persistence remain owned by the cellular host;
|
|
// this bridge handles admission, v7-v9 action receipts, public cell replication and
|
|
// owner-filtered v8/v9 perception.
|
|
class CellularBridge {
|
|
public:
|
|
static std::optional<CellularBridge> open(const M10Options& options,
|
|
server::CellularRegionHost& host,
|
|
persistence::RegionKey key, std::uint64_t frame,
|
|
const persistence::PgOptions& pg) {
|
|
if (!options.complete())
|
|
return fail("error cellular-session-config");
|
|
CellularBridge bridge;
|
|
const auto window = server::SessionWindow::open(options.session_window, wall_seconds());
|
|
if (!window)
|
|
return fail("error cellular-session-window");
|
|
const auto colon = options.listen.rfind(':');
|
|
std::uint16_t port{};
|
|
if (colon == std::string::npos ||
|
|
std::from_chars(options.listen.data() + colon + 1,
|
|
options.listen.data() + options.listen.size(), port)
|
|
.ec != std::errc{})
|
|
return fail("error cellular-session-listen");
|
|
const auto issuer = read(options.issuer);
|
|
if (issuer.size() != network::grant_public_key_bytes)
|
|
return fail("error cellular-session-issuer");
|
|
|
|
server::RegionSessionsConfig config;
|
|
config.transport.listen_address = options.listen.substr(0, colon);
|
|
config.transport.port = port;
|
|
config.transport.certificate_pem_file = options.certificate;
|
|
config.transport.key_pem_file = options.key;
|
|
config.control.environment =
|
|
options.environment == "dev" ? network::DeploymentEnvironment::dev
|
|
: options.environment == "stage" ? network::DeploymentEnvironment::stage
|
|
: network::DeploymentEnvironment::world0;
|
|
config.control.world = {key.world, frame};
|
|
config.control.region = key.region;
|
|
config.control.epoch = 1;
|
|
config.control.max_sessions = 512;
|
|
config.transport.limits.max_connections = 576;
|
|
if (options.max_grant_lifetime != 0) {
|
|
// As for lineage (M10.5c): a longer DEV ceiling lets a playtest outlive the 300 s
|
|
// default; never outside dev.
|
|
if (config.control.environment != network::DeploymentEnvironment::dev)
|
|
return fail("error m10-grant-lifetime");
|
|
config.control.max_grant_lifetime = options.max_grant_lifetime;
|
|
}
|
|
const auto life_routes = parse_life_owner_routes(options);
|
|
if (!life_routes || life_routes->empty())
|
|
return fail("error cellular-life-routes");
|
|
config.life_owner_routes = *life_routes;
|
|
network::GrantPublicKey public_key{};
|
|
std::copy(issuer.begin(), issuer.end(), public_key.begin());
|
|
config.issuer_keys.push_back({1, public_key});
|
|
|
|
bridge.window_ = *window;
|
|
bridge.slot_ = std::make_unique<server::PgSlot>(pg, std::chrono::seconds{2});
|
|
const auto lease = [&host] { return host.authority(); };
|
|
bridge.control_ =
|
|
std::make_unique<server::PostgresControlLedger>(*bridge.slot_, key, lease);
|
|
bridge.actions_ = std::make_unique<server::PostgresActionLedger>(*bridge.slot_, key, lease);
|
|
config.ledger = bridge.control_.get();
|
|
config.actions = bridge.actions_.get();
|
|
config.accept_cellular_actions = true;
|
|
// A cellular action carries one tick's movement and intake; a tick without one is
|
|
// idle, so a steering or feeding player sends one every tick. The probe default
|
|
// (4 per 8-tick window) refused every other one; allow one per tick with headroom
|
|
// for arrival jitter across window edges.
|
|
config.intents.max_actions_per_window = 2 * config.intents.window_ticks;
|
|
config.create_primitive_life = [&host](const network::AccountId& account,
|
|
std::uint64_t generation, std::uint64_t request) {
|
|
return host.create_primitive_life(account.bytes, generation, request);
|
|
};
|
|
config.query_primitive_life = [&host](const network::AccountId& account,
|
|
std::uint64_t generation, std::uint64_t request) {
|
|
return host.query_primitive_life(account.bytes, generation, request);
|
|
};
|
|
config.select_cellular_mutation = [&host](const network::AccountId& account,
|
|
std::uint64_t generation,
|
|
const network::CellularMutationAction& m) {
|
|
const auto reply = host.select_mutation(
|
|
account.bytes, generation, m.action_id,
|
|
{m.life_identity, m.event_index, m.offer_tick, m.operator_id, m.become});
|
|
server::CellularMutationAnswer answer{
|
|
server::admit_status(reply.status), reply.tick, {}};
|
|
if (reply.outcome)
|
|
answer.outcome = server::action_outcome(*reply.outcome);
|
|
return answer;
|
|
};
|
|
auto sessions = server::RegionSessions::create(std::move(config));
|
|
if (!sessions)
|
|
return fail(sessions.error() == server::RegionSessionsError::transport
|
|
? "error cellular-session-listen"
|
|
: "error cellular-session-config");
|
|
bridge.sessions_ = std::move(*sessions);
|
|
bridge.sessions_->set_default_interest({0, 0, 0, 7});
|
|
std::printf("cellular listening %u\n", static_cast<unsigned>(bridge.sessions_->port()));
|
|
return std::optional<CellularBridge>{std::move(bridge)};
|
|
}
|
|
|
|
[[nodiscard]] bool accepting(std::uint64_t now_seconds) {
|
|
const bool open = window_ && window_->accepting(now_seconds);
|
|
if (!open && !shutdown_) {
|
|
sessions_->shutdown(std::chrono::steady_clock::now());
|
|
shutdown_ = true;
|
|
}
|
|
return open;
|
|
}
|
|
[[nodiscard]] server::RegionSessions& sessions() noexcept {
|
|
return *sessions_;
|
|
}
|
|
[[nodiscard]] std::vector<network::CarriedAction> carry(std::uint64_t tick) {
|
|
return sessions_->carry(tick);
|
|
}
|
|
void committed(std::span<const network::CarriedAction> actions, std::uint64_t sequence) {
|
|
sessions_->committed(actions, sequence);
|
|
}
|
|
void dropped(std::span<const network::CarriedAction> actions, bool final) {
|
|
sessions_->dropped(actions, final);
|
|
}
|
|
void poll(const server::HostStatus& status, std::uint64_t now_seconds) {
|
|
sessions_->poll({status.ready, status.epoch, status.simulated_tick}, now_seconds,
|
|
std::chrono::steady_clock::now());
|
|
for (const auto& event : sessions_->take_events())
|
|
std::printf("cellular %s session=%llu account=%s reason=%u\n",
|
|
event.kind == server::RegionSessionEvent::Kind::opened ? "opened"
|
|
: event.kind == server::RegionSessionEvent::Kind::closed ? "closed"
|
|
: "refused",
|
|
static_cast<unsigned long long>(event.session), event.account.c_str(),
|
|
static_cast<unsigned>(event.reason));
|
|
}
|
|
// `state` is what players see (the session batch's working state between commits);
|
|
// mutation offers and life endings come only from `committed`, so a player can act on
|
|
// them durably. Without `committed`, both are the same state.
|
|
void replicate(const server::CellularLives& state,
|
|
const server::CellularLives* committed = nullptr) {
|
|
const auto& authority = committed ? *committed : state;
|
|
const auto tick = state.tick();
|
|
if (replicated_tick_ == tick)
|
|
return;
|
|
const auto source = [&](const network::SessionInterest& interest) {
|
|
network::ReplicationSource result;
|
|
result.identity = {state.world(), state.frame()};
|
|
result.organism_revision = tick;
|
|
for (const auto& life : state.lives()) {
|
|
if (life.presence == server::CellularPresence::suspended)
|
|
continue; // Out of the world (ADR-0128).
|
|
const auto voxel_x = life.position.x_um / 1'000'000;
|
|
const auto voxel_y = life.position.y_um / 1'000'000;
|
|
if (voxel_x >
|
|
static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) ||
|
|
voxel_y > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
|
|
continue;
|
|
const world::VoxelAddress voxel{static_cast<std::int64_t>(voxel_x),
|
|
static_cast<std::int64_t>(voxel_y), 0};
|
|
if (voxel.x < interest.x - interest.radius ||
|
|
voxel.x > interest.x + interest.radius ||
|
|
voxel.y < interest.y - interest.radius ||
|
|
voxel.y > interest.y + interest.radius)
|
|
continue;
|
|
const auto genome = state.archive().find(life.identity.genome);
|
|
if (!genome)
|
|
continue;
|
|
const biology::EnvironmentState environment{state.ambient_temperature_millikelvin(),
|
|
life.reserve};
|
|
auto cell = client::present_organism(
|
|
life.identity.organism, voxel, {life.position.x_um % 1'000'000},
|
|
{life.position.y_um % 1'000'000}, *genome, life.growth, environment,
|
|
client::OrganismState::alive);
|
|
if (cell)
|
|
result.organisms.push_back(*cell);
|
|
}
|
|
std::ranges::sort(result.organisms, {}, &client::OrganismCell::id);
|
|
return result;
|
|
};
|
|
sessions_->replicate(tick, source);
|
|
for (const auto& life : state.lives()) {
|
|
if (life.presence == server::CellularPresence::suspended)
|
|
continue;
|
|
const auto perceived = state.perceive(life.identity.life);
|
|
if (!perceived)
|
|
continue;
|
|
network::CellularPerception view;
|
|
view.tick = tick;
|
|
view.life_identity = life.identity.life;
|
|
network::CellularLifeDiagnostics diagnostics;
|
|
diagnostics.reserve_energy_pj = life.reserve.energy.value;
|
|
for (std::size_t i = 0; i < diagnostics.reserve_matter_fg.size(); ++i)
|
|
diagnostics.reserve_matter_fg[i] = life.reserve.matter[i].value;
|
|
if (const auto cost = bud_cost_for(state, life.identity.genome)) {
|
|
diagnostics.bud_cost_energy_pj = cost->energy.value;
|
|
for (std::size_t i = 0; i < diagnostics.bud_cost_matter_fg.size(); ++i)
|
|
diagnostics.bud_cost_matter_fg[i] = cost->matter[i].value;
|
|
}
|
|
const auto feedback =
|
|
std::ranges::lower_bound(state.last_tick_feedback(), life.identity.life, {},
|
|
&server::CellularLifeTickFeedback::life_id);
|
|
if (feedback != state.last_tick_feedback().end() &&
|
|
feedback->life_id == life.identity.life && feedback->tick == tick) {
|
|
diagnostics.has_tick_effects = true;
|
|
diagnostics.maintenance_cost_pj = feedback->maintenance_cost.value;
|
|
diagnostics.movement_cost_pj = feedback->movement_cost.value;
|
|
switch (feedback->movement) {
|
|
case biology::CellularMovementStatus::not_requested:
|
|
diagnostics.movement = network::CellularMovementResult::no_movement;
|
|
break;
|
|
case biology::CellularMovementStatus::moved:
|
|
diagnostics.movement = network::CellularMovementResult::moved;
|
|
break;
|
|
case biology::CellularMovementStatus::blocked:
|
|
diagnostics.movement = network::CellularMovementResult::blocked;
|
|
break;
|
|
case biology::CellularMovementStatus::insufficient_reserve:
|
|
diagnostics.movement = network::CellularMovementResult::insufficient_energy;
|
|
break;
|
|
}
|
|
switch (feedback->intake) {
|
|
case biology::CellularIntakeStatus::not_requested:
|
|
diagnostics.intake = network::CellularIntakeResult::not_requested;
|
|
break;
|
|
case biology::CellularIntakeStatus::acquired:
|
|
diagnostics.intake = network::CellularIntakeResult::acquired;
|
|
break;
|
|
case biology::CellularIntakeStatus::missing:
|
|
diagnostics.intake = network::CellularIntakeResult::missing_patch;
|
|
break;
|
|
case biology::CellularIntakeStatus::out_of_contact:
|
|
diagnostics.intake = network::CellularIntakeResult::out_of_contact;
|
|
break;
|
|
}
|
|
// ADR-0129 (v10): what an engulf or bud intention did this tick.
|
|
diagnostics.engulf = engulf_result(feedback->engulf);
|
|
diagnostics.bud = feedback->bud ? bud_outcome(*feedback->bud)
|
|
: network::CellularBudOutcome::not_requested;
|
|
}
|
|
// Rules 12 (v13): the authoritative motion state and the region's currents, from
|
|
// which the client regenerates the identical flow field.
|
|
const auto* field = state.flow_field();
|
|
if (field) {
|
|
diagnostics.velocity_x_q10 = life.motion.velocity_x_q10;
|
|
diagnostics.velocity_y_q10 = life.motion.velocity_y_q10;
|
|
diagnostics.heading = life.motion.heading;
|
|
const auto& c = state.liquid_rules().currents;
|
|
view.currents = network::CellularCurrentsView{c.seed,
|
|
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};
|
|
}
|
|
// Rules 13 (v14): the body block. Older sessions never see it.
|
|
diagnostics.members = life.revamp.members;
|
|
if (const auto genome = state.archive().find(life.identity.genome)) {
|
|
const auto& traits = genome->cellular_traits();
|
|
const auto t = traits.value_or(biology::CellularTraits{});
|
|
const std::array<std::uint16_t, 20> fields{
|
|
t.density, t.upkeep_efficiency, t.growth_speed, t.collection[0],
|
|
t.collection[1], t.collection[2], t.collection[3], t.collection[4],
|
|
t.burn[0], t.burn[1], t.burn[2], t.burn[3],
|
|
t.engulf_capacity, t.kill_absorption, t.litter, t.recipe[0],
|
|
t.recipe[1], t.recipe[2], t.recipe[3], t.adhesion};
|
|
if (traits)
|
|
diagnostics.traits = fields;
|
|
if (state.rules_version() >= server::cellular_lives_revamp_rules) {
|
|
const auto& rules = state.revamp_rules();
|
|
diagnostics.emerge_members = static_cast<std::uint16_t>(
|
|
std::min<std::uint32_t>(rules.emerge_members, 0xFFFF));
|
|
diagnostics.can_emerge = server::cellular_can_emerge(life, rules);
|
|
if (feedback != state.last_tick_feedback().end() &&
|
|
feedback->life_id == life.identity.life && feedback->tick == tick)
|
|
diagnostics.exclude = feedback->exclude;
|
|
const auto burn = biology::cellular_burn(
|
|
rules.burn_pj_per_kfg,
|
|
traits ? t.burn : std::array<std::uint16_t, 4>{100, 100, 100, 100},
|
|
diagnostics.exclude);
|
|
diagnostics.payable_energy_pj =
|
|
biology::cellular_payable_energy(life.reserve, burn, false);
|
|
} else {
|
|
diagnostics.payable_energy_pj = life.reserve.energy.value;
|
|
}
|
|
}
|
|
for (std::size_t c = 0; c < life.body.matter.size(); ++c)
|
|
diagnostics.total_mass_fg +=
|
|
life.body.matter[c].value + life.reserve.matter[c].value;
|
|
view.diagnostics = diagnostics;
|
|
view.patches.reserve(perceived->size());
|
|
// ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to
|
|
// the cell, by ascending id; `drained` marks a stock that fell since last tick.
|
|
std::vector<std::pair<std::uint64_t, network::CellularPerceivedDeposit>> near;
|
|
const auto centre_x = static_cast<std::int64_t>(life.position.x_um);
|
|
const auto centre_y = static_cast<std::int64_t>(life.position.y_um);
|
|
for (const auto& patch : *perceived) {
|
|
if (patch.kind == biology::CellularDepositKind::patch)
|
|
continue;
|
|
network::CellularPerceivedDeposit deposit;
|
|
deposit.id = patch.id;
|
|
deposit.x_um = patch.address.x_um;
|
|
deposit.y_um = patch.address.y_um;
|
|
deposit.radius_um =
|
|
static_cast<std::uint16_t>(std::min<std::uint32_t>(patch.radius_um, 65'535));
|
|
deposit.shape = patch.kind == biology::CellularDepositKind::pool
|
|
? network::CellularDepositShape::pool
|
|
: network::CellularDepositShape::bubble;
|
|
deposit.amount_codes[0] =
|
|
network::deposit_amount_code(patch.available.energy.value);
|
|
for (std::size_t c = 0; c < patch.available.matter.size(); ++c)
|
|
deposit.amount_codes.at(c + 1) =
|
|
network::deposit_amount_code(patch.available.matter[c].value);
|
|
const auto before = deposit_stock_.find(patch.id);
|
|
deposit.drained = before != deposit_stock_.end() &&
|
|
(patch.available.energy.value < before->second.energy.value ||
|
|
std::ranges::any_of(
|
|
std::array{0, 1, 2, 3},
|
|
[&](int c) {
|
|
const auto i = static_cast<std::size_t>(c);
|
|
return patch.available.matter.at(i).value <
|
|
before->second.matter.at(i).value;
|
|
}));
|
|
seen_stock_[patch.id] = patch.available;
|
|
// Rules 12 (v13): a bubble's world velocity, current plus induced drift, so the
|
|
// client can carry it between perceptions.
|
|
if (field && patch.kind == biology::CellularDepositKind::mote) {
|
|
const auto flow = field->sample(patch.address.x_um, patch.address.y_um);
|
|
std::int64_t drift_x{}, drift_y{};
|
|
if (const auto index = state.habitat().find(patch.address)) {
|
|
drift_x = state.habitat().patches()[*index].drift_x_q10;
|
|
drift_y = state.habitat().patches()[*index].drift_y_q10;
|
|
}
|
|
const auto um_s = [](std::int64_t q10) {
|
|
return static_cast<std::int16_t>(std::clamp<std::int64_t>(
|
|
q10 / biology::cellular_velocity_q10_per_um_s, -32'767, 32'767));
|
|
};
|
|
deposit.velocity_x_um_s = um_s(flow.x_q10 + drift_x);
|
|
deposit.velocity_y_um_s = um_s(flow.y_q10 + drift_y);
|
|
}
|
|
const auto dx = std::int64_t{patch.address.x_um} - centre_x;
|
|
const auto dy = std::int64_t{patch.address.y_um} - centre_y;
|
|
near.emplace_back(static_cast<std::uint64_t>(dx * dx + dy * dy), deposit);
|
|
}
|
|
// Rules 12: every pool, but only the nearest moving bubbles (the tuning file's
|
|
// trial 256); the client carries the rest with the current.
|
|
if (field) {
|
|
const auto bubbles = std::ranges::partition(near, [](const auto& entry) {
|
|
return entry.second.shape == network::CellularDepositShape::pool;
|
|
});
|
|
const auto keep = std::min<std::size_t>(cellular_visible_moving_bubbles,
|
|
static_cast<std::size_t>(bubbles.size()));
|
|
std::ranges::nth_element(
|
|
bubbles, bubbles.begin() + static_cast<std::ptrdiff_t>(keep),
|
|
[](const auto& a, const auto& b) {
|
|
return std::pair{a.first, a.second.id} < std::pair{b.first, b.second.id};
|
|
});
|
|
near.erase(bubbles.begin() + static_cast<std::ptrdiff_t>(keep), near.end());
|
|
}
|
|
if (near.size() > network::max_cellular_perceived_deposits) {
|
|
std::ranges::nth_element(
|
|
near,
|
|
near.begin() +
|
|
static_cast<std::ptrdiff_t>(network::max_cellular_perceived_deposits),
|
|
[](const auto& a, const auto& b) {
|
|
return std::pair{a.first, a.second.id} < std::pair{b.first, b.second.id};
|
|
});
|
|
near.resize(network::max_cellular_perceived_deposits);
|
|
}
|
|
for (const auto& [distance, deposit] : near)
|
|
view.deposits.push_back(deposit);
|
|
std::ranges::sort(view.deposits, {}, &network::CellularPerceivedDeposit::id);
|
|
for (const auto& patch : *perceived) {
|
|
if (patch.kind != biology::CellularDepositKind::patch)
|
|
continue;
|
|
network::CellularPerceivedPatch visible;
|
|
visible.x_um = patch.address.x_um;
|
|
visible.y_um = patch.address.y_um;
|
|
visible.energy_pj = patch.available.energy.value;
|
|
for (std::size_t i = 0; i < visible.matter_fg.size(); ++i)
|
|
visible.matter_fg[i] = patch.available.matter[i].value;
|
|
view.patches.push_back(visible);
|
|
}
|
|
// ADR-0176 (v12): light this cell captured, and the photosynthetic cells it can
|
|
// see within its perception radius (nearest 256), by ascending organism.
|
|
if (view.diagnostics && feedback != state.last_tick_feedback().end() &&
|
|
feedback->life_id == life.identity.life)
|
|
view.diagnostics->light_pj = feedback->light.value;
|
|
if (life.account != server::LifeAccount{}) {
|
|
std::vector<std::pair<std::uint64_t, network::CellularPerceivedProducer>> seen;
|
|
for (const auto& other : state.lives()) {
|
|
if (other.presence == server::CellularPresence::suspended)
|
|
continue;
|
|
const auto genome = state.archive().find(other.identity.genome);
|
|
if (!genome || !genome->carries(biology::Capability::photosynthesis))
|
|
continue;
|
|
const auto dx = static_cast<std::int64_t>(other.position.x_um) - centre_x;
|
|
const auto dy = static_cast<std::int64_t>(other.position.y_um) - centre_y;
|
|
const auto distance = static_cast<std::uint64_t>(dx * dx + dy * dy);
|
|
constexpr auto radius =
|
|
std::uint64_t{biology::cellular_trial_perception_radius_um};
|
|
if (distance > radius * radius)
|
|
continue;
|
|
const auto efficiency =
|
|
genome->parameter(biology::Capability::photosynthesis).value_or(0);
|
|
if (efficiency == 0 || efficiency > 1000)
|
|
continue;
|
|
seen.emplace_back(distance, network::CellularPerceivedProducer{
|
|
other.identity.organism,
|
|
static_cast<std::uint16_t>(efficiency)});
|
|
}
|
|
if (seen.size() > network::max_cellular_perceived_producers) {
|
|
std::ranges::nth_element(
|
|
seen,
|
|
seen.begin() +
|
|
static_cast<std::ptrdiff_t>(network::max_cellular_perceived_producers),
|
|
[](const auto& a, const auto& b) {
|
|
return std::pair{a.first, a.second.organism} <
|
|
std::pair{b.first, b.second.organism};
|
|
});
|
|
seen.resize(network::max_cellular_perceived_producers);
|
|
}
|
|
for (const auto& [distance, producer] : seen)
|
|
view.producers.push_back(producer);
|
|
std::ranges::sort(view.producers, {},
|
|
&network::CellularPerceivedProducer::organism);
|
|
}
|
|
(void)sessions_->send_cellular_perception(network::AccountId{life.account}, view);
|
|
const auto owned = std::ranges::find(
|
|
authority.lives(), life.identity.life,
|
|
[](const server::CellularOwnedLife& value) { return value.identity.life; });
|
|
if (owned != authority.lives().end())
|
|
send_offer(authority, *owned, authority.tick());
|
|
}
|
|
// After every owner's view: clear only the sessions that got none this tick.
|
|
sessions_->clear_cellular_perceptions(tick);
|
|
std::erase_if(offers_, [&](const SentOffer& sent) {
|
|
return std::ranges::find(authority.lives(), sent.account,
|
|
&server::CellularOwnedLife::account) ==
|
|
authority.lives().end();
|
|
});
|
|
announce_endings(authority);
|
|
// What each deposit held when last seen, for next tick's `drained` flags.
|
|
deposit_stock_ = std::move(seen_stock_);
|
|
seen_stock_.clear();
|
|
replicated_tick_ = tick;
|
|
}
|
|
// ADR-0129: an owned life seen at the last replication and now a corpse is announced to
|
|
// its owner once, with its recorded cause.
|
|
void announce_endings(const server::CellularLives& state) {
|
|
for (const auto& [account, life_id] : owned_) {
|
|
if (std::ranges::find(state.lives(), life_id, [](const server::CellularOwnedLife& l) {
|
|
return l.identity.life;
|
|
}) != state.lives().end())
|
|
continue;
|
|
// Rules 13: control moved to another life (succession, or a merge into an organism).
|
|
if (std::ranges::find(state.lives(), account, &server::CellularOwnedLife::account) !=
|
|
state.lives().end())
|
|
continue;
|
|
const auto corpse =
|
|
std::ranges::find(state.corpses(), life_id, &server::CellularOwnedCorpse::life_id);
|
|
if (corpse == state.corpses().end())
|
|
continue;
|
|
const auto cause = corpse->cause == biology::CellularDeathCause::starved
|
|
? network::CellularDeathReason::starved
|
|
: corpse->cause == biology::CellularDeathCause::engulfed
|
|
? network::CellularDeathReason::engulfed
|
|
: corpse->cause == biology::CellularDeathCause::emerged
|
|
? network::CellularDeathReason::emerged
|
|
: network::CellularDeathReason::unrecorded;
|
|
static_cast<void>(sessions_->send_life_ended(network::AccountId{account},
|
|
{corpse->died_tick, life_id, cause}));
|
|
}
|
|
owned_.clear();
|
|
for (const auto& life : state.lives())
|
|
if (life.account != server::LifeAccount{})
|
|
owned_.emplace_back(life.account, life.identity.life);
|
|
}
|
|
static network::CellularEngulfResult engulf_result(biology::CellularEngulfStatus status) {
|
|
switch (status) {
|
|
case biology::CellularEngulfStatus::not_requested:
|
|
return network::CellularEngulfResult::not_requested;
|
|
case biology::CellularEngulfStatus::engulfed:
|
|
return network::CellularEngulfResult::engulfed;
|
|
case biology::CellularEngulfStatus::no_eligible_prey:
|
|
return network::CellularEngulfResult::no_eligible_prey;
|
|
case biology::CellularEngulfStatus::unsupported:
|
|
return network::CellularEngulfResult::unsupported;
|
|
case biology::CellularEngulfStatus::no_contact:
|
|
return network::CellularEngulfResult::no_contact;
|
|
case biology::CellularEngulfStatus::prey_too_large:
|
|
return network::CellularEngulfResult::prey_too_large;
|
|
case biology::CellularEngulfStatus::membrane_too_thick:
|
|
return network::CellularEngulfResult::membrane_too_thick;
|
|
}
|
|
return network::CellularEngulfResult::not_reported;
|
|
}
|
|
static network::CellularBudOutcome bud_outcome(server::CellularBudResult result) {
|
|
switch (result) {
|
|
case server::CellularBudResult::budded:
|
|
return network::CellularBudOutcome::budded;
|
|
case server::CellularBudResult::life_died:
|
|
case server::CellularBudResult::not_able:
|
|
return network::CellularBudOutcome::not_able;
|
|
case server::CellularBudResult::insufficient_funding:
|
|
return network::CellularBudOutcome::insufficient_funding;
|
|
case server::CellularBudResult::no_placement:
|
|
return network::CellularBudOutcome::no_placement;
|
|
}
|
|
return network::CellularBudOutcome::not_reported;
|
|
}
|
|
// 11.4d: the owner's outstanding offer is sent reliably when it changes or the owner's
|
|
// session changes; an empty view clears an offer that was consumed.
|
|
void send_offer(const server::CellularLives& state, const server::CellularOwnedLife& life,
|
|
std::uint64_t tick) {
|
|
const network::AccountId account{life.account};
|
|
const auto session = sessions_->holder(account);
|
|
// Rules 13 offers are catalog offers (v14 only); earlier rules use the operator offer.
|
|
const bool named = state.rules_version() >= server::cellular_lives_revamp_rules;
|
|
const bool pending = named ? life.revamp.offer.count != 0 : life.mutation.offer.has_value();
|
|
const SentOffer current{life.account, session.value_or(0), life.identity.life,
|
|
!pending ? 0
|
|
: named ? life.revamp.offer.event_index
|
|
: life.mutation.event_index,
|
|
!pending ? 0
|
|
: named ? life.revamp.offer.offer_tick
|
|
: life.mutation.offer_tick};
|
|
auto sent = std::ranges::find(offers_, life.account, &SentOffer::account);
|
|
if (sent != offers_.end() && *sent == current)
|
|
return;
|
|
if (!session || (!pending && sent == offers_.end()))
|
|
return; // Nothing to show, or no one to show it to.
|
|
if (!sessions_->send_mutation_offer(account, server::offer_view(state, life, tick), named))
|
|
return; // Not a v10 (v14) owner (or the stream refused): retried on a later tick.
|
|
if (sent != offers_.end())
|
|
*sent = current;
|
|
else
|
|
offers_.push_back(current);
|
|
}
|
|
void shutdown() {
|
|
sessions_->shutdown(std::chrono::steady_clock::now());
|
|
}
|
|
|
|
private:
|
|
// ADR-0129 amendment: a genome's bud cost is pure for this region's temperature, and
|
|
// deriving it scans up to a thousand bodies, so it is computed once per genome.
|
|
std::optional<accounting::Inventory> bud_cost_for(const server::CellularLives& state,
|
|
std::uint64_t genome_id) {
|
|
if (const auto known = bud_costs_.find(genome_id); known != bud_costs_.end())
|
|
return known->second;
|
|
const auto genome = state.archive().find(genome_id);
|
|
if (!genome)
|
|
return std::nullopt;
|
|
if (bud_costs_.size() >= 4096)
|
|
bud_costs_.clear(); // Bounded: recomputing is only slower.
|
|
return bud_costs_[genome_id] =
|
|
biology::bud_cost(*genome, state.ambient_temperature_millikelvin());
|
|
}
|
|
static std::uint64_t wall_seconds() {
|
|
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::system_clock::now().time_since_epoch())
|
|
.count());
|
|
}
|
|
static std::string read(const std::string& path) {
|
|
std::ifstream file{path, std::ios::binary};
|
|
return {std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
|
|
}
|
|
static std::optional<CellularBridge> fail(const char* message) {
|
|
std::puts(message);
|
|
return std::nullopt;
|
|
}
|
|
|
|
std::unique_ptr<server::PgSlot> slot_;
|
|
std::unique_ptr<server::PostgresControlLedger> control_;
|
|
std::unique_ptr<server::PostgresActionLedger> actions_;
|
|
std::unique_ptr<server::RegionSessions> sessions_;
|
|
std::optional<server::SessionWindow> window_;
|
|
std::optional<std::uint64_t> replicated_tick_;
|
|
struct SentOffer {
|
|
server::LifeAccount account{};
|
|
std::uint64_t session{}, life{}, event_index{}, offer_tick{};
|
|
friend bool operator==(const SentOffer&, const SentOffer&) = default;
|
|
};
|
|
std::vector<SentOffer> offers_; // Last offer view sent to each owner.
|
|
std::map<std::uint64_t, std::optional<accounting::Inventory>> bud_costs_; // By genome.
|
|
// ADR-0136: deposit stocks seen at the last replicated tick, and this tick's.
|
|
std::map<std::uint32_t, accounting::Inventory> deposit_stock_, seen_stock_;
|
|
std::vector<std::pair<server::LifeAccount, std::uint64_t>> owned_; // At last replication.
|
|
bool shutdown_{};
|
|
};
|
|
} // namespace evo::server_app
|