Files
aevolution/apps/evo-client/main.cpp
T
dingoandClaude Opus 5.5 521372607a
Foundation / checks (checks) (push) Successful in 45m19s
Foundation / checks (deploy) (push) Successful in 3m45s
Foundation / checks (ecs) (push) Successful in 2m16s
Foundation / checks (network) (push) Successful in 19m17s
Foundation / checks (postgres) (push) Successful in 43m23s
Foundation / checks (tsan) (push) Successful in 11m39s
Foundation / checks (client) (push) Successful in 17m3s
Foundation / postgres-tools (push) Successful in 29s
Foundation / server-image (push) Successful in 3m8s
Foundation / image (push) Successful in 3m25s
Cells face where they move; a click outside closes the evolution window
The microscope view orients each cell along its last movement of at least 20 um, with
the flagella trailing, easing into turns. The heading is projected with the current
camera, so panning never turns a cell; a cell that has not moved keeps its seeded
orientation. A left click outside the evolution window closes it (the offer stays;
E or the callout reopens it), except on the frame it opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:35:52 -04:00

862 lines
44 KiB
C++

#include "cellular_scene.hpp"
#include "controls_flow.hpp"
#include "evo/client/application.hpp"
#include "evo/client/auth.hpp"
#include "evo/client/launcher.hpp"
#include "evo/client/selection.hpp"
#include "evo/client/session_host.hpp"
#include "evo/client/ui_state.hpp"
#include "evo/render/environment.hpp"
#include "evo/render/organism.hpp"
#include "panels.hpp"
#include "remote_session.hpp"
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <exception>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace {
using evo::world::Field;
constexpr evo::world::WorldIdentity fixture_identity{1, 1};
constexpr std::int64_t fixture_z = -16000;
// Water, nitrogen (never opened: missing), phosphorus (present zero), organic and
// incident energy (never opened: missing). Unrequested fields draw hollow outlines.
constexpr std::uint32_t fixture_mask = (1U << 0) | (1U << 1) | (1U << 2) | (1U << 7) | (1U << 8);
constexpr unsigned frames_per_authority_tick = 60;
// Frame composition: environment bound + organisms + 6 host rectangles (capture bar,
// intention dot, 4-sided selection highlight). Text and panels are the toolkit overlay.
constexpr std::size_t host_rectangles =
6 + evo::client_app::patch_rectangles * evo::network::max_cellular_perceived_patches;
// M11.3: the cellular arena is millimetres across, far below the metre-scale default
// camera; the first view frames this much of it around the own cell.
constexpr double cellular_view_mm = 6;
constexpr std::size_t organism_budget =
evo::render::max_rectangles - evo::render::max_environment_rectangles - host_rectangles;
// Local in-memory stand-in for authoritative region views until M9.7. It is never
// persisted or published; the client presentation only copies its read-only views.
struct FixtureAuthority {
std::unique_ptr<evo::world::FieldStore> fields;
std::unique_ptr<evo::world::ChunkStore> terrain;
std::vector<evo::world::VoxelAddress> footprint;
// Static presentation population: phenotypes derive from real genomes, but no
// ecology runs here. Two remnants show the dead encoding.
std::vector<evo::client::OrganismCell> organisms;
std::uint64_t tick{1};
};
bool add_organism(FixtureAuthority& authority, std::uint64_t id, evo::world::VoxelAddress voxel,
std::uint64_t x_um, std::uint64_t y_um) {
using evo::biology::Capability;
const auto k = static_cast<std::uint32_t>(id);
evo::biology::GenomeDraft draft{
id,
1,
1,
{},
{{Capability::energy_conversion, 200 + 100 * (k % 7), 0}, {Capability::membrane, 10, 0}}};
if (k % 3 == 0)
draft.capabilities.push_back({Capability::movement, 50, 0});
if (k % 2 == 0)
draft.capabilities.push_back({Capability::ingestion, 2000, 0});
draft.capabilities.push_back({Capability::target_size, 8'000'000, 0});
const auto genome = evo::biology::Genome::create(draft);
if (!genome)
return false;
constexpr evo::biology::EnvironmentState temperate{
293'150, {{1'000'000'000}, {evo::accounting::Femtograms{1'000'000'000}, {}, {}, {}}}};
const auto cell = evo::client::present_organism(
id, voxel, {x_um}, {y_um}, *genome, {400 + 100 * (k % 7), k % 5 == 0 ? 300U : 0U},
temperate,
k == 5 || k == 23 ? evo::client::OrganismState::dead : evo::client::OrganismState::alive);
if (!cell)
return false;
authority.organisms.push_back(*cell);
return true;
}
std::optional<FixtureAuthority> make_authority() {
FixtureAuthority authority;
std::vector<evo::world::FieldSite> sites;
std::vector<std::uint64_t> water, energy;
for (std::int64_t x = -8; x < 8; ++x)
for (std::int64_t y = -4; y < 4; ++y) {
const auto ux = static_cast<std::uint64_t>(x + 8);
const auto uy = static_cast<std::uint64_t>(y + 4);
authority.footprint.push_back({x, y, fixture_z});
// Habitat boxes vary to show their boundaries inside each 1 m voxel.
const evo::world::HabitatBox box{{50000 * (ux % 4)}, {40000 * uy}, {0},
{800000 - 30000 * uy}, {500000 + 10000 * ux}, {100}};
sites.push_back({authority.footprint.back(), box, {1}});
const auto volume = box.width.value * box.height.value * box.depth.value;
water.push_back(volume >> (2 * ux / 3 + uy));
energy.push_back((ux + 1) * (uy + 1) * (volume >> 4));
}
const std::uint64_t zero = 0;
const evo::world::FieldOpening opening[]{
{Field::water, water}, {Field::phosphorus, {&zero, 1}}, {Field::organic_energy, energy}};
const evo::world::FieldDefaults defaults{{evo::accounting::Femtograms{0},
evo::accounting::Femtograms{1ULL << 50},
evo::accounting::Femtograms{0}}};
constexpr std::size_t budget = 4'000'000;
auto fields =
evo::world::FieldStore::create(fixture_identity, 1, defaults, sites, opening, budget);
auto terrain = evo::world::ChunkStore::create({}, 32, budget);
if (!fields || !terrain)
return std::nullopt;
authority.fields = std::move(*fields);
authority.terrain = std::move(*terrain);
for (const auto voxel : authority.footprint)
if (!authority.terrain->load(evo::world::split(voxel, evo::world::base_chunk_edge)->chunk))
return std::nullopt;
// A 4x4 cluster 60 um apart in voxel (0, 0) for zoomed inspection, then one
// organism in every other voxel of the fixture.
std::uint64_t id = 1;
for (std::uint64_t i = 0; i < 16; ++i)
if (!add_organism(authority, id++, {0, 0, fixture_z}, 410000 + 60 * (i % 4),
480000 + 60 * (i / 4)))
return std::nullopt;
for (std::int64_t x = -8; x < 8; x += 2)
for (std::int64_t y = -4; y < 4; y += 2)
if (!add_organism(authority, id++, {x, y, fixture_z}, 500000, 500000))
return std::nullopt;
return authority;
}
// One conserved same-channel water move per authority tick (finite fixture stock).
bool advance(FixtureAuthority& authority) {
const auto sites = authority.fields->sites().size();
const auto from = static_cast<std::size_t>(authority.tick * 7 % sites);
const auto amount = authority.fields->read(from, Field::water);
if (!amount)
return false;
++authority.tick;
if (*amount < 8)
return true;
const auto moved = authority.fields->transfer(authority.tick, Field::water, from,
(from + 1) % sites, *amount / 8);
return moved || moved.error() == evo::world::FieldError::capacity;
}
std::optional<evo::client::EnvironmentPresentation> query(const FixtureAuthority& authority) {
const auto view = evo::world::query_environment(
*authority.fields, *authority.terrain, authority.tick, authority.footprint, fixture_mask);
if (!view)
return std::nullopt;
auto presentation = evo::client::present_environment(*view, fixture_z);
if (!presentation)
return std::nullopt;
return std::move(*presentation);
}
std::optional<evo::client::OrganismPresentation> organisms(const FixtureAuthority& authority) {
auto presentation = evo::client::OrganismPresentation::create(
{fixture_identity, authority.tick, 1}, fixture_z, authority.organisms);
if (!presentation)
return std::nullopt;
return std::move(*presentation);
}
std::optional<evo::render::EnvironmentDisplay> parse_layer(std::string_view name) {
using Mode = evo::render::EnvironmentDisplay::Mode;
constexpr std::array<std::string_view, evo::world::field_count> names{"water",
"nitrogen",
"phosphorus",
"organic-carbon",
"organic-nitrogen",
"organic-phosphorus",
"organic-other",
"organic-energy",
"incident-energy",
"heat"};
if (name == "moisture")
return evo::render::EnvironmentDisplay{Mode::moisture};
for (std::size_t i = 0; i < names.size(); ++i)
if (name == names.at(i))
return evo::render::EnvironmentDisplay{Mode::field, static_cast<Field>(i)};
return std::nullopt;
}
bool parse_count(std::string_view value, unsigned limit, unsigned& out) {
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), out);
return error == std::errc{} && end == value.data() + value.size() && out != 0 && out <= limit;
}
std::optional<evo::client::ScreenPoint> parse_point(std::string_view value) {
const auto comma = value.find(',');
unsigned x = 0, y = 0;
if (comma == std::string_view::npos || !parse_count(value.substr(0, comma), 32768, x) ||
!parse_count(value.substr(comma + 1), 32768, y))
return std::nullopt;
return evo::client::ScreenPoint{static_cast<double>(x), static_cast<double>(y)};
}
// A probe marker (ADR-0094): the own one larger and amber, others smaller and blue; stale
// ones (no current authority, ADR-0095) grey; ghosts (arriving, ADR-0096) violet. Clipped
// to the viewport.
void marker_box(std::vector<evo::render::Rectangle>& out, double x, double y, bool own, bool stale,
bool ghost, double width, double height) {
const double half = own ? 7 : 4;
const double x0 = std::max(x - half, 0.0), y0 = std::max(y - half, 0.0);
const double x1 = std::min(x + half, width), y1 = std::min(y + half, height);
if (x1 > x0 && y1 > y0)
out.push_back({static_cast<float>(x0), static_cast<float>(y0), static_cast<float>(x1 - x0),
static_cast<float>(y1 - y0),
stale ? evo::render::Color{120, 120, 120, 255}
: ghost ? evo::render::Color{190, 120, 230, 255}
: own ? evo::render::Color{250, 190, 40, 255}
: evo::render::Color{90, 170, 250, 255}});
}
void outline(std::vector<evo::render::Rectangle>& out, double l, double t, double r, double b,
double width, double height) {
const auto rect = [&](double x0, double y0, double x1, double y1) {
x0 = std::max(x0, 0.0);
y0 = std::max(y0, 0.0);
x1 = std::min(x1, width);
y1 = std::min(y1, height);
if (x1 > x0 && y1 > y0)
out.push_back({static_cast<float>(x0),
static_cast<float>(y0),
static_cast<float>(x1 - x0),
static_cast<float>(y1 - y0),
{255, 255, 255, 255}});
};
rect(l, t, r, t + 2);
rect(l, b - 2, r, b);
rect(l, t + 2, l + 2, b - 2);
rect(r - 2, t + 2, r, b - 2);
}
std::uint64_t milliseconds(std::chrono::steady_clock::time_point t) {
return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()).count());
}
// Wall-clock seconds: grant expiry is UTC (the session compares the server's welcome).
std::uint64_t utc_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
} // namespace
int main(int argc, char** argv) try {
using evo::client_app::Mode;
evo::client::Config config;
unsigned frames = 0, refresh_every = 1;
bool start_fixture = false;
std::optional<evo::client::ScreenPoint> scripted_pick;
std::string screenshot;
std::filesystem::path controls_path; // Empty: per-user settings directory.
bool show_controls = false;
evo::render::EnvironmentDisplay display;
evo::client::ConnectForm form;
bool connect_now = false;
bool cellular_trial = false;
std::string auth_profile; // ADR-0131: one saved login per --profile.
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (arg == "--version") { // Build identity for tester reports (ADR-0086).
std::printf("evo-client %s (Aeternalis Evolution engineering client; remote "
"sessions %s)\n",
EVO_BUILD_IDENTITY,
evo::client_app::remote_available ? "available" : "unavailable");
return 0;
}
if (arg == "--hidden")
config.hidden = true;
else if (arg == "--fixture")
start_fixture = true;
else if (arg == "--cellular")
cellular_trial = true;
else if (arg == "--profile" && i + 1 < argc) {
auth_profile = argv[++i];
if (auth_profile.empty() || !evo::client::auth_profile_valid(auth_profile))
return 2;
} else if (arg == "--connect" && i + 1 < argc) {
form.endpoint = argv[++i];
connect_now = true;
} else if (arg == "--server-name" && i + 1 < argc)
form.server_name = argv[++i];
else if (arg == "--ca" && i + 1 < argc)
form.authority_path = argv[++i];
else if (arg == "--grants" && i + 1 < argc)
form.grants_path = argv[++i];
else if (arg == "--renderer" && i + 1 < argc)
config.renderer = argv[++i];
else if (arg == "--frames" && i + 1 < argc) {
if (!parse_count(argv[++i], 100000, frames))
return 2;
} else if (arg == "--refresh-every" && i + 1 < argc) {
if (!parse_count(argv[++i], 1000, refresh_every))
return 2;
} else if (arg == "--layer" && i + 1 < argc) {
const auto layer = parse_layer(argv[++i]);
if (!layer)
return 2;
display = *layer;
} else if (arg == "--pick" && i + 1 < argc) { // Engineering automation only.
scripted_pick = parse_point(argv[++i]);
if (!scripted_pick)
return 2;
} else if (arg == "--size" && i + 1 < argc) { // Initial window size, WIDTH,HEIGHT.
const auto size = parse_point(argv[++i]);
if (!size || size->x < 320 || size->y < 240)
return 2;
config.width = static_cast<int>(size->x);
config.height = static_cast<int>(size->y);
} else if (arg == "--screenshot" && i + 1 < argc) { // Last frame, as BMP.
screenshot = argv[++i];
} else if (arg == "--controls" && i + 1 < argc) {
controls_path = argv[++i];
if (controls_path.empty())
return 2;
} else if (arg == "--show-controls") { // Engineering review: open the panel.
show_controls = true;
} else {
std::fputs("usage: evo-client [--version] [--renderer NAME] [--hidden] "
"[--frames 1..100000] [--size W,H]\n"
" [--fixture | --connect HOST:PORT --server-name NAME "
"--ca FILE --grants FILE [--cellular]]\n"
" [--layer water|nitrogen|...|heat|moisture]\n"
" [--refresh-every 1..1000] [--pick X,Y] "
"[--screenshot FILE.bmp --frames N]\n"
" [--controls FILE] [--show-controls] [--profile NAME]\n"
"Without --fixture or --connect the launcher opens.\n",
stderr);
return 2;
}
}
if ((start_fixture && connect_now) || (start_fixture && cellular_trial) ||
(!screenshot.empty() && frames == 0))
return 2;
// Launcher phase and remote session change together (fixture/live distinction).
evo::client::SessionHost<evo::client_app::RemoteSession> host;
const auto& launcher = host.launcher();
evo::client::UiState ui;
evo::client::Selection selection;
evo::client_app::FormBuffers buffers;
buffers.load(form);
std::optional<evo::client::LaunchError> form_error;
std::optional<FixtureAuthority> authority;
evo::client::EnvironmentLayer environment;
evo::client::OrganismLayer population;
std::optional<std::uint64_t> disconnect_dialog;
std::optional<std::pair<std::uint32_t, std::uint32_t>> cellular_feed_target;
bool cellular_framed = false; // The camera has been zoomed to the cellular arena.
// Validates the form and opens a fresh session; errors stay in the launcher.
const auto connect = [&](const evo::client::ConnectForm& f) {
form_error.reset();
if constexpr (!evo::client_app::remote_available) {
form_error = evo::client::LaunchError::no_session;
return false;
} else {
const auto material = evo::client::load_connect(f);
if (!material) {
form_error = material.error();
return false;
}
auto opened = evo::client_app::RemoteSession::open(*material, cellular_trial);
if (!opened) {
form_error = evo::client::LaunchError::endpoint;
return false;
}
cellular_framed = false;
return host.connect(std::move(opened));
}
};
// ADR-0131: a broker grant names its region route; only the region CA comes from the
// form. The grant stays in memory and the session asks for the next one itself.
const auto grant_material = [&](const evo::client::AuthGrant& grant) {
auto f = buffers.form();
f.endpoint = grant.endpoint;
f.server_name = grant.server_name;
return evo::client::load_connect(f, std::span{&grant.bytes, 1});
};
const auto connect_signed_in = [&](const evo::client::AuthGrant& grant) {
form_error.reset();
if constexpr (!evo::client_app::remote_available) {
form_error = evo::client::LaunchError::no_session;
return false;
} else {
const auto material = grant_material(grant);
if (!material) {
form_error = material.error();
return false;
}
cellular_trial = true; // The DEV broker world is the cellular trial (ADR-0131).
auto opened = evo::client_app::RemoteSession::open(*material, cellular_trial);
if (!opened) {
form_error = evo::client::LaunchError::endpoint;
return false;
}
opened->manage_grants();
cellular_framed = false;
return host.connect(std::move(opened));
}
};
const auto enter_fixture = [&] {
if (!authority) {
authority = make_authority();
if (!authority)
return false;
}
environment.reset();
population.reset();
selection.clear();
cellular_feed_target.reset();
host.enter_fixture(); // Ends any remote attempt: nothing runs behind the banner.
return true;
};
if (start_fixture && !enter_fixture()) {
std::fputs("client environment fixture error\n", stderr);
return 1;
}
if (connect_now && !connect(form)) {
std::fprintf(stderr, "client session configuration error: %s\n",
std::string{evo::client::launch_error_text(
form_error.value_or(evo::client::LaunchError::no_session))}
.c_str());
return 1;
}
auto app = evo::client::Application::open(config);
if (!app) {
std::fprintf(stderr, "client initialization error=%d\n", static_cast<int>(app.error()));
return 1;
}
// Controls (ADR-0085): per-user file unless --controls names one.
if (controls_path.empty())
if (const auto dir = evo::client::Application::settings_directory())
controls_path = *dir / "controls-v1.txt";
// Notices expire on the same monotonic clock the loop uses.
static_cast<void>(ui.advance(milliseconds(std::chrono::steady_clock::now())).has_value());
evo::client_app::ControlsFlow controls{controls_path};
controls.load(**app, ui);
if (show_controls)
controls.show(**app);
// A minimized native window may start with no drawable area. Adopt the
// native viewport before projecting; until then use the requested size.
auto camera = evo::client::Camera::create(
{config.width, config.height, config.width, config.height}, {}, 0.05);
if (!camera)
return 1;
const auto mode = [&] {
const auto phase = launcher.phase();
if (phase == evo::client::LaunchPhase::fixture)
return Mode::fixture;
if (phase == evo::client::LaunchPhase::connected ||
(phase == evo::client::LaunchPhase::connecting && launcher.ever_connected()))
return Mode::remote;
return Mode::launcher; // Choosing, failed, or the first connection attempt.
};
const auto shown_environment = [&]() -> const evo::client::EnvironmentLayer* {
if (mode() == Mode::fixture)
return &environment;
if (const auto* remote = host.session(); remote && mode() == Mode::remote)
return &remote->environment();
return nullptr;
};
const auto shown_organisms = [&]() -> const evo::client::OrganismLayer* {
if (mode() == Mode::fixture)
return &population;
if (const auto* remote = host.session(); remote && mode() == Mode::remote)
return &remote->organisms();
return nullptr;
};
// ADR-0131 browser sign-in (Windows); elsewhere the panel offers manual grants only.
evo::client::AuthClient auth{evo::client::native_auth_platform(auth_profile)};
bool auth_connect = false; // Connect when the requested grant arrives.
auto grant_requested = std::chrono::steady_clock::time_point{};
int drawn_organisms = -1;
evo::client_app::CellularScene scene; // Rebuilt each frame in cellular play.
evo::client_app::CellHeadings headings; // Where each drawn cell last moved.
bool scene_active = false;
evo::client_app::PanelActions actions;
(*app)->set_overlay([&] {
evo::client_app::PanelView view;
view.mode = mode();
view.launcher = &launcher;
view.form_error = form_error;
view.remote_available = evo::client_app::remote_available;
view.cellular_trial = cellular_trial;
view.auth = auth.status();
view.environment = shown_environment();
view.organisms = shown_organisms();
view.selection = &selection;
view.ui = &ui;
if (const auto* remote = host.session(); remote && view.mode == Mode::remote) {
view.remote = remote->status();
view.outcomes = &remote->outcomes();
view.cellular_perception = remote->cellular_perception();
view.cellular_play = &remote->cellular_play();
view.cellular_feed_target = cellular_feed_target;
}
view.visible_organisms = drawn_organisms;
view.cellular_scene = scene_active ? &scene : nullptr;
view.bindings = &(*app)->bindings();
controls.fill(view);
actions = evo::client_app::draw_panels(view, buffers, display);
});
std::vector<evo::render::Rectangle> boxes;
std::uint64_t count = 0;
auto previous = std::chrono::steady_clock::now();
while (frames == 0 || count < frames) {
if (auto result = (*app)->poll_events(); !result) {
std::fprintf(stderr, "client event error=%d\n", static_cast<int>(result.error()));
return 1;
}
const auto state = (*app)->state();
if (state.closed)
break;
const auto now = std::chrono::steady_clock::now();
static_cast<void>(ui.advance(milliseconds(now)).has_value()); // Monotonic clock.
const double seconds =
std::clamp(std::chrono::duration<double>(now - previous).count(), 0.0, 0.1);
previous = now;
// Panel actions from the previous rendered frame.
if (actions.fixture && !enter_fixture())
return 1;
if (actions.cellular_trial)
cellular_trial = *actions.cellular_trial;
if ((actions.connect || actions.retry) && connect(buffers.form())) {
selection.clear();
}
if (actions.cancel || actions.back) {
host.cancel(); // Drops the connection; its unresolved outcomes are unknown.
cellular_feed_target.reset();
selection.clear();
}
if (actions.ask_disconnect && !disconnect_dialog)
if (const auto id = ui.open_dialog("Disconnect from the dev region?",
"Intentions without a final outcome will be "
"unknown. Views stop updating."))
disconnect_dialog = *id;
if (actions.confirm_dialog && actions.confirm_dialog == disconnect_dialog &&
ui.close_dialog(*actions.confirm_dialog)) {
disconnect_dialog.reset();
host.cancel();
cellular_feed_target.reset();
selection.clear();
}
if (actions.cancel_dialog && ui.close_dialog(*actions.cancel_dialog))
disconnect_dialog.reset();
if (actions.dismiss_notice)
static_cast<void>(ui.dismiss(*actions.dismiss_notice));
if (actions.stop_feeding) {
cellular_feed_target.reset();
buffers.cellular_controls.auto_feed = false;
}
if (actions.feed_patch) {
cellular_feed_target = actions.feed_patch;
buffers.cellular_controls.auto_feed = false;
}
if (auto* remote = host.session(); remote && mode() == Mode::remote) {
if (actions.cell_action && remote->request_cellular(*actions.cell_action))
cellular_feed_target.reset();
if (actions.mutation)
static_cast<void>(remote->request_cellular(evo::client_app::CellAction::mutation,
*actions.mutation));
if (actions.restart_life && remote->restart_cellular()) {
cellular_feed_target.reset();
selection.clear();
}
if (actions.keep_unknown)
remote->keep_cellular_unknown();
remote->set_cellular_feed_target(cellular_trial ? cellular_feed_target : std::nullopt);
remote->set_cellular_controls(buffers.cellular_controls);
}
// ADR-0131 sign-in. One request at a time; grants arrive on a later frame.
if (actions.sign_in && auth.sign_in()) {
auth_connect = true;
grant_requested = now;
}
if (actions.auth_connect && auth.request_grant()) {
auth_connect = true;
grant_requested = now;
}
if (actions.cancel_sign_in) {
auth.cancel();
auth_connect = false;
}
if (actions.sign_out) {
host.cancel(); // Logout revokes every grant; do not keep a session behind it.
cellular_feed_target.reset();
selection.clear();
auth_connect = false;
static_cast<void>(auth.sign_out());
}
if (auto grant = auth.take_grant()) {
if (auth_connect) {
auth_connect = false;
if (connect_signed_in(*grant))
selection.clear();
} else if (auto* remote = host.session()) {
// Refresh or reconnect material for the live session (same account).
if (const auto material = grant_material(*grant))
static_cast<void>(remote->supply_grant(*material));
}
grant->bytes.fill(0);
}
if (const auto status = auth.status(); !status.busy && auth_connect && !status.signed_in)
auth_connect = false; // Sign-in failed or was cancelled; the panel shows why.
// About a minute before expiry, or after a lost connection; never for a session the
// launcher has given up on (superseded by another client, cancelled).
const bool live = launcher.phase() == evo::client::LaunchPhase::connecting ||
launcher.phase() == evo::client::LaunchPhase::connected;
if (const auto* remote = host.session();
live && remote && remote->needs_grant(utc_seconds()) &&
now - grant_requested >= std::chrono::seconds{5} && auth.request_grant())
grant_requested = now;
controls.step(actions, **app, ui);
actions = {};
// The launcher and modal dialogs own input: no world movement or selection.
const auto* input_session = host.session();
const bool cell_input_blocked = input_session && input_session->cellular_trial() &&
(!input_session->cellular_play().fresh() ||
input_session->cellular_play().life() == 0 ||
input_session->cellular_play().ended().has_value());
(*app)->set_ui_capture(mode() == Mode::launcher || ui.dialog().has_value() ||
controls.open() || cell_input_blocked);
const auto navigation = (*app)->take_navigation();
// Local input counter; in remote mode the session sets the server tick.
const auto intention = (*app)->sample_intention(count);
if (!intention)
return 1;
host.step(now, *intention, ui); // Only while connecting or connected.
if (const auto* remote = host.session(); remote && cellular_trial)
cellular_feed_target = remote->cellular_feed_target();
// M10.5c: the camera follows the server's view until the user moves it; from then
// on its centre is the session's interest (the server clamps and filters it).
if (auto* remote = host.session(); remote && mode() == Mode::remote) {
if (const auto centre = remote->take_recentre())
if (auto moved = evo::client::Camera::create(camera->viewport(), *centre,
camera->units_per_mm()))
*camera = *moved;
remote->focus(camera->centre());
}
// The fixture authority advances at its own cadence. Presentations refresh
// every N authority ticks; in between the advanced watermark shows as stale.
if (mode() == Mode::fixture && count % frames_per_authority_tick == 0) {
if (count != 0 && !advance(*authority))
return 1;
if ((authority->tick - 1) % refresh_every == 0) {
auto next = query(*authority);
auto cells = organisms(*authority);
if (!next || !cells || !environment.accept(std::move(*next)) ||
!population.accept(std::move(*cells)))
return 1;
}
if (!environment.observe(
{fixture_identity, authority->tick, authority->fields->last_command()}) ||
!population.observe({fixture_identity, authority->tick, 1}))
return 1;
}
const auto* env_layer = shown_environment();
const auto* org_layer = shown_organisms();
const auto* env = env_layer ? env_layer->current() : nullptr;
const auto* orgs = org_layer ? org_layer->current() : nullptr;
const auto change = selection.refresh(env, orgs);
if (change == evo::client::Selection::Change::organism_gone)
static_cast<void>(ui.notify("The selected organism is no longer present.",
evo::client::NoticeLevel::info)
.has_value());
else if (change == evo::client::Selection::Change::cell_gone)
static_cast<void>(ui.notify("The selected habitat cell is no longer in view.",
evo::client::NoticeLevel::info)
.has_value());
boxes.clear();
if (state.logical_width > 0 && state.logical_height > 0 && state.pixel_width > 0 &&
state.pixel_height > 0) {
if (!camera->resize({state.logical_width, state.logical_height, state.pixel_width,
state.pixel_height}))
return 1;
// M11.3: keep the own cell (organism id == life identity) centred, framing the
// arena once; the player's zoom is kept after that.
if (const auto* remote = host.session();
remote && mode() == Mode::remote && cellular_trial && orgs != nullptr)
if (const auto* perception = remote->cellular_perception();
perception && perception->life_identity != 0) {
const auto cells = orgs->cells();
const auto own = std::ranges::find(cells, perception->life_identity,
&evo::client::OrganismCell::id);
if (own != cells.end()) {
const double pitch = evo::world::cell_pitch_mm;
evo::client::WorldPoint centre{static_cast<double>(own->voxel.x) * pitch +
static_cast<double>(own->x.value) / 1000,
static_cast<double>(own->voxel.y) * pitch +
static_cast<double>(own->y.value) /
1000};
const double scale =
cellular_framed ? camera->units_per_mm()
: static_cast<double>(std::min(state.logical_width,
state.logical_height)) /
cellular_view_mm;
// Keep the followed cell in the visible arena beside the journal.
const double shift = state.logical_width < 880 ? 171.0 : -10.0;
centre.x_mm -= shift / scale;
centre.y_mm += 29.0 / scale;
if (auto moved =
evo::client::Camera::create(camera->viewport(), centre, scale)) {
*camera = *moved;
cellular_framed = true;
}
}
}
if (auto result =
camera->pan({navigation.x * 400 * seconds, navigation.y * 400 * seconds});
!result && result.error() != evo::client::CameraError::out_of_range)
return 1;
const evo::client::ScreenPoint anchor{
std::clamp(navigation.pointer.x, 0.0, static_cast<double>(state.logical_width)),
std::clamp(navigation.pointer.y, 0.0, static_cast<double>(state.logical_height))};
if (auto result = camera->zoom(std::exp2(navigation.wheel / 4), anchor);
!result && result.error() != evo::client::CameraError::out_of_range)
return 1;
if (navigation.click)
selection.pick(*navigation.click, env, orgs, *camera);
if (scripted_pick && env != nullptr) {
selection.pick(*scripted_pick, env, orgs, *camera);
scripted_pick.reset();
}
// Copied presentation only; clipped to the viewport before float conversion.
if (!evo::render::build_environment(
boxes, env, env_layer ? env_layer->freshness() : evo::client::Freshness::none,
*camera, display))
return 1;
const double width = state.logical_width, height = state.logical_height;
// 2026-10-16 microscope view: in cellular play, patches and cells are a scene the
// panels draw as granules and living cells; elsewhere organisms stay rectangles.
scene.patches.clear();
scene.cells.clear();
scene_active = false;
const auto* cellular_remote = host.session();
const bool microscope = cellular_remote && mode() == Mode::remote && cellular_trial;
if (microscope) {
const bool fresh = cellular_remote->cellular_play().fresh();
if (const auto* perception = cellular_remote->cellular_perception())
for (const auto& patch : perception->patches) {
const auto low =
camera->world_to_screen({static_cast<double>(patch.x_um) / 1000,
static_cast<double>(patch.y_um) / 1000});
const auto high = camera->world_to_screen(
{(static_cast<double>(patch.x_um) + 1000) / 1000,
(static_cast<double>(patch.y_um) + 1000) / 1000});
if (!low || !high)
continue;
evo::client_app::ScenePatch p;
p.x = static_cast<float>((low->x + high->x) / 2);
p.y = static_cast<float>((low->y + high->y) / 2);
p.half = static_cast<float>(std::abs(high->x - low->x) / 2);
p.stock = {patch.energy_pj, patch.matter_fg[0], patch.matter_fg[1],
patch.matter_fg[2], patch.matter_fg[3]};
p.target = cellular_feed_target &&
cellular_feed_target->first == patch.x_um &&
cellular_feed_target->second == patch.y_um;
p.stale = !fresh;
p.seed = (static_cast<std::uint64_t>(patch.x_um) << 32U) ^ patch.y_um;
scene.patches.push_back(p);
}
const auto own = cellular_remote->cellular_play().life();
if (orgs)
for (const auto& cell : orgs->cells()) {
const auto bounds = evo::render::organism_bounds(cell, *camera);
if (bounds.right < 0 || bounds.left > width || bounds.bottom < 0 ||
bounds.top > height)
continue;
const auto& ph = cell.phenotype;
evo::client_app::SceneCell c;
c.x = static_cast<float>((bounds.left + bounds.right) / 2);
c.y = static_cast<float>((bounds.top + bounds.bottom) / 2);
c.radius = static_cast<float>((bounds.right - bounds.left) / 2);
// One flagellum per 150 um/s of speed (a founder swims at 200).
c.flagella = ph.movement_speed == 0
? 0
: static_cast<int>(std::min<std::uint32_t>(
6, 1 + ph.movement_speed / 150));
const double wall = ph.total_mass == 0
? 0.0
: static_cast<double>(ph.membrane_mass) /
static_cast<double>(ph.total_mass);
c.membrane = static_cast<float>(std::clamp(1.0 + wall * 6.0, 1.0, 7.0));
c.organelles = 2 + static_cast<int>(std::min<std::uint32_t>(
3, ph.conversion_per_thousand / 250));
c.own = own != 0 && cell.id == own;
c.dead = cell.state == evo::client::OrganismState::dead;
c.stale =
org_layer && org_layer->freshness() != evo::client::Freshness::current;
c.seed = cell.id;
// The organism projection's world position (organism_bounds).
constexpr auto pitch = static_cast<double>(evo::world::cell_pitch_mm);
const evo::client::WorldPoint at{
static_cast<double>(cell.voxel.x) * pitch +
static_cast<double>(cell.x.value) / 1000,
static_cast<double>(cell.voxel.y) * pitch +
static_cast<double>(cell.y.value) / 1000};
if (const auto heading = headings.update(cell.id, at, *camera)) {
c.facing = true;
c.heading = *heading;
}
scene.cells.push_back(c);
}
headings.end_frame();
drawn_organisms = static_cast<int>(scene.cells.size());
scene_active = true;
} else {
const auto report = evo::render::append_organisms(
boxes, organism_budget, orgs,
org_layer ? org_layer->freshness() : evo::client::Freshness::none, *camera);
if (!report)
return 1;
drawn_organisms = static_cast<int>(report->drawn);
}
if (const auto* remote = host.session(); remote && mode() == Mode::remote) {
for (const auto& m : remote->markers())
if (const auto at = camera->world_to_screen({m.x_mm, m.y_mm}))
marker_box(boxes, at->x, at->y, m.own, m.stale, m.ghost, width, height);
}
if (const auto* o = selection.organism(orgs)) {
const auto b = evo::render::organism_bounds(*o, *camera);
outline(boxes, b.left - 3, b.top - 3, b.right + 3, b.bottom + 3, width, height);
} else if (const auto* c = selection.cell(env)) {
const double pitch = evo::world::cell_pitch_mm;
const auto low = camera->world_to_screen({static_cast<double>(c->voxel.x) * pitch,
static_cast<double>(c->voxel.y) * pitch});
const auto high =
camera->world_to_screen({static_cast<double>(c->voxel.x + 1) * pitch,
static_cast<double>(c->voxel.y + 1) * pitch});
if (low && high)
outline(boxes, low->x, high->y, high->x, low->y, width, height);
}
}
boxes.push_back({8, static_cast<float>(std::max(state.logical_height - 20, 0)), 64, 8,
(*app)->ui_captured() ? evo::render::Color{240, 140, 32, 255}
: evo::render::Color{64, 180, 140, 255}});
boxes.push_back({36 + static_cast<float>(intention->move_x) / 50,
static_cast<float>(std::max(state.logical_height - 48, 0)) -
static_cast<float>(intention->move_y) / 50,
8,
8,
{240, 240, 240, 255}});
const auto frame = evo::render::Frame::create(boxes, {14, 12, 18, 255}); // Ink.
if (!frame)
return 1;
if (!screenshot.empty() && count + 1 == frames && !(*app)->request_screenshot(screenshot))
return 2;
const auto result = (*app)->present(*frame);
if (!result) {
std::fprintf(stderr, "client frame error=%d\n", static_cast<int>(result.error()));
return 1;
}
if (*result == evo::client::Step::closed)
break;
++count;
std::this_thread::sleep_for(std::chrono::milliseconds{16});
}
return 0;
} catch (const std::exception& e) {
std::fprintf(stderr, "client exception: %.200s\n", e.what());
return 1;
} catch (...) {
std::fputs("client exception\n", stderr);
return 1;
}