Files
aevolution/src/biology/cellular_tuning.cpp
T
dingoandClaude Opus 5.5 40dc2b12ad feat(biology): procedural currents, habitat format 3 and moving food
Phase 2 biology. CellularFlowField generates 2-n seeded closed looping currents
inside the region, each with its own width, speed and direction, strongest at the
centreline and still at the stream edges and walls, rasterized to a Q10 grid with
integer bilinear sampling. The field digest matches across g++-14, clang-19 and
MSVC, so clients regenerate it from the configuration.

Habitat format 3 adds per-deposit induced drift, sub-micrometre carry and a merged
count, with up to 8,192 deposits. advect_cellular_deposits moves bubbles with the
flow plus drift from passing cells (falloff and decay), merges touching bubbles
into the lower id up to the merged cap, keeps pools fixed and addresses unique.
A 2,000-tick run of 1,800 bubbles conserves stock exactly and leaves nothing piled
at the walls; it costs under 0.7 ms per tick optimized. The tuned grid pitch is
capped at 10 mm. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:50:45 -04:00

296 lines
14 KiB
C++

#include "evo/biology/cellular_tuning.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
#include <array>
#include <optional>
namespace evo::biology {
namespace {
struct Field {
std::string_view key;
std::int64_t CellularTuning::* member;
std::int64_t minimum, maximum;
};
constexpr std::int64_t axis_limit = cellular_motion_axis_limit_um;
constexpr std::int64_t speed_limit = 1'000'000; // um/s, the kinematic velocity bound.
constexpr std::int64_t kelvin_limit = 1'000'000; // 1,000 K in millikelvin.
// Schema order is the canonical encoding order.
constexpr std::array fields{
Field{"tuning.version", &CellularTuning::version, 1, 1'000},
Field{"region.width_um", &CellularTuning::region_width_um, 1'000, axis_limit},
Field{"region.height_um", &CellularTuning::region_height_um, 1'000, axis_limit},
Field{"region.organism_cap", &CellularTuning::region_organism_cap, 1, 100'000},
Field{"region.deposit_limit", &CellularTuning::region_deposit_limit, 1, 65'536},
Field{"region.perception_radius_um", &CellularTuning::region_perception_radius_um, 100,
100'000},
Field{"founder.thrust_um_per_s2", &CellularTuning::founder_thrust_um_per_s2, 0, speed_limit},
Field{"founder.reverse_thrust_um_per_s2", &CellularTuning::founder_reverse_thrust_um_per_s2, 0,
speed_limit},
Field{"founder.drag_ppm_per_tick", &CellularTuning::founder_drag_ppm_per_tick, 0, 999'999},
Field{"founder.lateral_drag_ppm_per_tick", &CellularTuning::founder_lateral_drag_ppm_per_tick,
0, 999'999},
Field{"founder.turn_heading_per_s", &CellularTuning::founder_turn_heading_per_s, 0,
10 * std::int64_t{cellular_heading_turn}},
Field{"currents.min_count", &CellularTuning::currents_min_count, 0, 16},
Field{"currents.max_count", &CellularTuning::currents_max_count, 0, 16},
Field{"currents.min_width_um", &CellularTuning::currents_min_width_um, 100, axis_limit},
Field{"currents.max_width_um", &CellularTuning::currents_max_width_um, 100, axis_limit},
Field{"currents.min_speed_um_per_s", &CellularTuning::currents_min_speed_um_per_s, 0,
speed_limit},
Field{"currents.max_speed_um_per_s", &CellularTuning::currents_max_speed_um_per_s, 0,
speed_limit},
Field{"currents.grid_pitch_um", &CellularTuning::currents_grid_pitch_um, 10, 10'000},
Field{"food.merged_bubble_cap_multiple", &CellularTuning::food_merged_bubble_cap_multiple, 1,
1'000},
Field{"food.visible_moving_bubbles", &CellularTuning::food_visible_moving_bubbles, 0, 512},
Field{"food.induced_drift_radius_um", &CellularTuning::food_induced_drift_radius_um, 0,
100'000},
Field{"food.induced_drift_max_um_per_s", &CellularTuning::food_induced_drift_max_um_per_s, 0,
speed_limit},
Field{"food.induced_drift_decay_ppm_per_tick",
&CellularTuning::food_induced_drift_decay_ppm_per_tick, 0, 999'999},
Field{"thermal.ambient_min_mk", &CellularTuning::thermal_ambient_min_mk, 0, kelvin_limit},
Field{"thermal.ambient_max_mk", &CellularTuning::thermal_ambient_max_mk, 0, kelvin_limit},
Field{"founder.preferred_mk", &CellularTuning::founder_preferred_mk, 0, kelvin_limit},
Field{"founder.comfort_band_mk", &CellularTuning::founder_comfort_band_mk, 0, kelvin_limit},
Field{"founder.body_tau_ms", &CellularTuning::founder_body_tau_ms, 1, 3'600'000},
Field{"founder.lethal_cold_mk", &CellularTuning::founder_lethal_cold_mk, 0, kelvin_limit},
Field{"founder.lethal_heat_mk", &CellularTuning::founder_lethal_heat_mk, 0, kelvin_limit},
Field{"thermal.off_preference_per_mille_per_k",
&CellularTuning::thermal_off_preference_per_mille_per_k, 0, 100'000},
Field{"thermal.transition_per_mille_per_k", &CellularTuning::thermal_transition_per_mille_per_k,
0, 100'000},
Field{"thermal.multiplier_cap_per_mille", &CellularTuning::thermal_multiplier_cap_per_mille,
1'000, 1'000'000},
Field{"lifecycle.logout_delay_ms", &CellularTuning::lifecycle_logout_delay_ms, 0, 600'000},
Field{"mutation.step_points", &CellularTuning::mutation_step_points, 1, 100},
Field{"mutation.paired_points", &CellularTuning::mutation_paired_points, 0, 100},
Field{"mutation.recovery_floor_per_mille", &CellularTuning::mutation_recovery_floor_per_mille,
0, 1'000},
Field{"mutation.offer_interval_ms", &CellularTuning::mutation_offer_interval_ms, 1'000,
3'600'000},
Field{"mutation.offer_options", &CellularTuning::mutation_offer_options, 1, 10},
};
std::string_view trim(std::string_view text) noexcept {
while (!text.empty() && (text.front() == ' ' || text.front() == '\t'))
text.remove_prefix(1);
while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r'))
text.remove_suffix(1);
return text;
}
bool valid_key(std::string_view key) noexcept {
if (key.empty())
return false;
for (const char c : key)
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '.'))
return false;
return true;
}
// Optional '-', then digits with single '_' separators between digits; at most 18 digits.
std::optional<std::int64_t> parse_integer(std::string_view text) noexcept {
const bool negative = !text.empty() && text.front() == '-';
if (negative)
text.remove_prefix(1);
if (text.empty() || text.front() == '_' || text.back() == '_')
return std::nullopt;
std::int64_t value{};
std::size_t digits{};
char previous{};
for (const char c : text) {
if (c == '_') {
if (previous == '_')
return std::nullopt;
} else if (c >= '0' && c <= '9') {
if (++digits > 18)
return std::nullopt;
value = value * 10 + (c - '0');
} else {
return std::nullopt;
}
previous = c;
}
return negative ? -value : value;
}
std::optional<CellularTuningError> inconsistent(const CellularTuning& t) {
const auto error = [](std::string_view key) {
return CellularTuningError{CellularTuningErrorKind::inconsistent, 0, std::string{key}};
};
if (t.version != cellular_tuning_version)
return CellularTuningError{CellularTuningErrorKind::unsupported_version, 0,
"tuning.version"};
if (t.currents_min_count > t.currents_max_count)
return error("currents.min_count");
if (t.currents_min_width_um > t.currents_max_width_um)
return error("currents.min_width_um");
if (t.currents_min_speed_um_per_s > t.currents_max_speed_um_per_s)
return error("currents.min_speed_um_per_s");
if (t.thermal_ambient_min_mk > t.thermal_ambient_max_mk)
return error("thermal.ambient_min_mk");
if (t.founder_lethal_cold_mk >= t.founder_preferred_mk ||
t.founder_preferred_mk >= t.founder_lethal_heat_mk)
return error("founder.preferred_mk");
return std::nullopt;
}
} // namespace
std::expected<CellularTuning, CellularTuningError> parse_cellular_tuning(std::string_view text) {
if (text.size() > max_cellular_tuning_bytes)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::too_large, 0, {}}};
CellularTuning tuning{};
std::array<bool, fields.size()> seen{};
std::size_t line_number{};
while (!text.empty()) {
++line_number;
const auto end = text.find('\n');
auto line = text.substr(0, end);
text.remove_prefix(end == std::string_view::npos ? text.size() : end + 1);
if (const auto comment = line.find('#'); comment != std::string_view::npos)
line = line.substr(0, comment);
line = trim(line);
if (line.empty())
continue;
const auto equals = line.find('=');
if (equals == std::string_view::npos)
return std::unexpected{
CellularTuningError{CellularTuningErrorKind::syntax, line_number, {}}};
const auto key = trim(line.substr(0, equals));
const auto value_text = trim(line.substr(equals + 1));
if (!valid_key(key))
return std::unexpected{
CellularTuningError{CellularTuningErrorKind::syntax, line_number, {}}};
std::size_t index{};
while (index < fields.size() && fields.at(index).key != key)
++index;
if (index == fields.size())
return std::unexpected{CellularTuningError{CellularTuningErrorKind::unknown_key,
line_number, std::string{key}}};
if (seen.at(index))
return std::unexpected{CellularTuningError{CellularTuningErrorKind::duplicate_key,
line_number, std::string{key}}};
const auto value = parse_integer(value_text);
if (!value)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::invalid_value,
line_number, std::string{key}}};
const auto& field = fields.at(index);
if (*value < field.minimum || *value > field.maximum)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::out_of_range,
line_number, std::string{key}}};
seen.at(index) = true;
tuning.*field.member = *value;
}
for (std::size_t index = 0; index < fields.size(); ++index)
if (!seen.at(index))
return std::unexpected{CellularTuningError{CellularTuningErrorKind::missing_key, 0,
std::string{fields.at(index).key}}};
if (const auto error = inconsistent(tuning))
return std::unexpected{*error};
return tuning;
}
std::string encode_cellular_tuning(const CellularTuning& tuning) {
std::string text;
for (const auto& field : fields) {
text.append(field.key);
text.append(" = ");
text.append(std::to_string(tuning.*field.member));
text.push_back('\n');
}
return text;
}
std::string_view describe(CellularTuningErrorKind kind) noexcept {
switch (kind) {
case CellularTuningErrorKind::too_large:
return "tuning file too large";
case CellularTuningErrorKind::syntax:
return "expected 'key = value'";
case CellularTuningErrorKind::unknown_key:
return "unknown key";
case CellularTuningErrorKind::duplicate_key:
return "duplicate key";
case CellularTuningErrorKind::invalid_value:
return "value is not an integer";
case CellularTuningErrorKind::out_of_range:
return "value out of range";
case CellularTuningErrorKind::missing_key:
return "missing key";
case CellularTuningErrorKind::inconsistent:
return "values are inconsistent";
case CellularTuningErrorKind::unsupported_version:
return "unsupported tuning version";
}
return "unknown tuning error";
}
CellularHandling founder_cellular_handling(const CellularTuning& tuning,
accounting::Picojoules thrust_cost,
accounting::Picojoules reverse_cost) {
constexpr std::int64_t ticks_per_second =
1'000'000 / static_cast<std::int64_t>(cellular_motion_tick_microseconds);
const auto per_tick_velocity = [](std::int64_t um_per_s2) {
return static_cast<std::uint32_t>(um_per_s2 * cellular_velocity_q10_per_um_s /
ticks_per_second);
};
return {
.thrust_q10 = per_tick_velocity(tuning.founder_thrust_um_per_s2),
.reverse_thrust_q10 = per_tick_velocity(tuning.founder_reverse_thrust_um_per_s2),
.forward_drag_ppm = static_cast<std::uint32_t>(tuning.founder_drag_ppm_per_tick),
.lateral_drag_ppm = static_cast<std::uint32_t>(tuning.founder_lateral_drag_ppm_per_tick),
.turn = static_cast<std::uint16_t>(tuning.founder_turn_heading_per_s / ticks_per_second),
.thrust_cost = thrust_cost,
.reverse_cost = reverse_cost};
}
std::expected<CellularHandling, CellularHandlingError>
derive_cellular_handling(const Genome& genome, const MetabolicBudget& budget,
const CellularTuning& tuning) {
const auto& arrangement = genome.movement_arrangement();
if (!arrangement || genome.development_version() < 6)
return std::unexpected{CellularHandlingError::unsupported_genome};
if (budget.rate_microseconds != accounting::microseconds_per_second)
return std::unexpected{CellularHandlingError::unsupported_rate};
const auto full_cost = accounting::per_tick(
budget.movement.value, cellular_motion_tick_microseconds, accounting::Rounding::up);
if (!full_cost || *full_cost > std::uint64_t{1} << 40U)
return std::unexpected{CellularHandlingError::overflow};
const auto founder = founder_cellular_handling(tuning, {}, {});
const auto& a = *arrangement;
constexpr std::uint64_t reference = movement_reference_points;
const auto scale = [](std::uint64_t value, std::uint64_t index) {
return value * index / reference;
};
const auto cost = [&](std::uint64_t index) {
const auto product = *full_cost * index;
return accounting::Picojoules{product / a.efficiency +
(product % a.efficiency != 0 ? 1 : 0)};
};
constexpr std::uint64_t drag_limit = cellular_drag_ppm_limit - 1;
CellularHandling handling{};
handling.forward_drag_ppm = static_cast<std::uint32_t>(
std::min<std::uint64_t>(drag_limit, founder.forward_drag_ppm * reference * reference /
(std::uint64_t{a.streamlining} * a.coasting)));
handling.lateral_drag_ppm = static_cast<std::uint32_t>(
std::min<std::uint64_t>(drag_limit, founder.lateral_drag_ppm * reference / a.coasting));
if (!genome.carries(Capability::movement) || a.output == 0)
return handling;
constexpr std::uint64_t velocity_limit = cellular_velocity_limit_q10;
handling.thrust_q10 =
static_cast<std::uint32_t>(std::min(velocity_limit, scale(founder.thrust_q10, a.output)));
handling.reverse_thrust_q10 = static_cast<std::uint32_t>(
std::min(velocity_limit, scale(founder.reverse_thrust_q10, a.braking)));
handling.turn = static_cast<std::uint16_t>(
std::min<std::uint64_t>(cellular_heading_turn / 2, scale(founder.turn, a.steering)));
handling.thrust_cost = cost(a.output);
handling.reverse_cost = cost(a.braking);
return handling;
}
} // namespace evo::biology