Files
Dreierpack-Manager/src/modern/content/ui_contract.cpp
T
MichaelandClaude Fable 5.2 eec7f40a52 A player's card with figures and skills; shirts in the club's colour; table zones; reduced motion
The card shows age, strength, condition, technique and form as numerals, the seven
skills as marks and contract and status as a list. The line-up pitch draws shirts in
the club's colour with a condition dot instead of the data set's figures. League
tables carry the prediction's European places and the promotion and relegation
places. A display setting turns transitions off. The desk hangs from the top edge of
a taller screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 18:43:40 +01:00

758 lines
48 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
#include "modern/content/ui_contract.hpp"
#include <algorithm>
#include <cstdio>
#include <random>
#include <string>
#include <variant>
#include "formats/executable_layout.hpp"
#include "game/state.hpp"
#include "game/table.hpp"
#include "game/schedule.hpp"
#include "modern/content/projections.hpp"
#include "modern/content/press_journal.hpp"
#include "modern/content/statistics.hpp"
#include "modern/content/world_package.hpp"
#include "modern/content/world_save.hpp"
#include "modern/content/toto_quote.hpp"
#include "modern/game/almanac.hpp"
#include "modern/game/desk_actions.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/reschedule.hpp"
namespace bmh::modern {
namespace {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
constexpr const char* kContractVersion = "bmh-modern-ui@draft1";
constexpr size_t kRecord = 0xb0c;
const std::string& entry(const std::vector<std::string>& v, size_t i) {
static const std::string none;
return i < v.size() ? v[i] : none;
}
const J* field(const J& request, const char* key) {
const auto* o = request.object();
if (!o) return nullptr;
const auto it = o->find(key);
return it == o->end() ? nullptr : &it->second;
}
std::string text_field(const J& request, const char* key) {
const J* v = field(request, key);
return v && v->string() ? *v->string() : std::string{};
}
J text(const std::string& s) { return O{{"key", nullptr}, {"text", s}, {"locale", "de"}, {"args", O{}}}; }
J available() { return O{{"status", "available"}, {"reasonCode", nullptr}, {"missingFields", A{}}}; }
J unavailable(const char* reason) { return O{{"status", "unavailable"}, {"reasonCode", reason}, {"missingFields", A{}}}; }
std::string iso(const AlmanacDate& d) {
char out[16];
std::snprintf(out, sizeof out, "%04d-%02d-%02d", d.year, d.month, d.day);
return out;
}
// Managers with a human at their desk: during the national coach's takeover the coach sits in
// slot 0 and the others wait (OriginalManagerCount keeps their number).
int human_managers(const ModernState& g) {
if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0 &&
g.memory.has(::bmh::layout::OriginalManagerCount))
return g.memory.u8(::bmh::layout::OriginalManagerCount);
return int(g.manager_teams.size());
}
std::string manager_name(const ModernState& g, int manager) {
if (const auto* p = g.manager_presentation(manager)) return p->name;
std::string name;
const size_t at = size_t(manager) * kRecord + 0xa8;
for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i)
name.push_back(char(g.manager_records[at + i]));
return almanac_utf8(name);
}
int64_t money_of(const ModernState& g, int manager) {
const size_t at = size_t(manager) * kRecord + 0x314;
if (at + 3 >= g.manager_records.size()) return 0;
return int32_t(uint32_t(g.manager_records[at]) | uint32_t(g.manager_records[at + 1]) << 8 |
uint32_t(g.manager_records[at + 2]) << 16 | uint32_t(g.manager_records[at + 3]) << 24);
}
int team_of(const ModernState& g, int manager) {
return manager >= 0 && size_t(manager) < g.manager_teams.size() ? g.manager_teams[size_t(manager)] : -1;
}
std::string team_id(const ModernState& g, int team) {
std::string id = entry(g.world_club_id, size_t(team));
return id.empty() ? "team:" + std::to_string(team) : id;
}
// TeamRef of the contract: id, kind, name, shortName, nationId, crestAssetId, nameAsOf.
J team_ref(const ModernState& g, int team, const std::string& as_of) {
if (team < 0) return nullptr;
std::string name = entry(g.world_club_name, size_t(team)), short_name = entry(g.world_club_short, size_t(team));
if (name.empty()) name = almanac_utf8(g.club_name(team));
if (short_name.empty()) short_name = name;
const bool national = team >= no_team();
// nation and crest as the world names them (the asset key is passed through, the UI draws it)
const World* world = current_world();
const WorldClub* club = world ? world->club(team_id(g, team)) : nullptr;
const auto text_or_null = [](const std::string* s) { return s && !s->empty() ? J(*s) : J(nullptr); };
return O{{"id", team_id(g, team)}, {"kind", national ? "national" : "club"}, {"name", name},
{"shortName", short_name}, {"nationId", text_or_null(club ? &club->nation : nullptr)},
{"crestAssetId", text_or_null(club ? &club->crest : nullptr)}, {"nameAsOf", as_of}};
}
std::string human_manager_id(const ModernState& g, int human) {
const std::string& id = entry(g.manager_ids, size_t(human));
return id.empty() ? "manager:slot-" + std::to_string(human) : id;
}
std::string manager_id(const ModernState& g, int runtime) {
return human_manager_id(g, g.human_manager_slot(runtime));
}
int human_team(const ModernState& g, int human) {
const int record = g.manager_record_slot(human);
if (record >= 0 && size_t(record) < g.manager_teams.size()) return g.manager_teams[size_t(record)];
const size_t at = size_t(record) * kRecord + 0x290;
return record >= 0 && at + 1 < g.manager_records.size() ? int(uint16_t(g.manager_records[at]) | uint16_t(g.manager_records[at + 1]) << 8) : -1;
}
// A human manager (Manager of the contract). After the career's end he is archived: resigned
// when he gave up, retired when the set duration ran out.
J manager_json(const ModernState& g, int human) {
const int manager = g.manager_record_slot(human);
const int team = human_team(g, human);
const size_t at = size_t(manager) * kRecord;
const int portrait = at + 0x221 < g.manager_records.size() ? g.manager_records[at + 0x221] : 0;
const auto* presentation = g.manager_presentation_for_human(human);
const std::string style = presentation ? presentation->portrait_style : "photo";
const bool ended = !g.career_end_reason.empty();
const char* status = !ended ? "active" : g.career_end_reason == "last_human_resigned" ? "resigned" : "retired";
return O{{"id", human_manager_id(g, human)}, {"slot", human}, {"runtimeSlot", manager}, {"name", manager_name(g, manager)},
{"control", ended ? "archived" : "human"}, {"status", status},
{"teamId", team >= 0 ? J(team_id(g, team)) : J(nullptr)},
{"portraitGuiKey", "gui:manager/" + style + "/" + std::to_string(portrait)}, {"portraitStyle", style},
{"strengthChoice", nullptr}, {"employments", manager_employments(g, human, human_manager_id(g, human))}};
}
// The commands the desk accepts now (the session refuses the others): none after the career's
// end; the national coach's desk has no toto, bank, camp, training, stadium, advertising,
// transfers, contracts or surroundings (ui/desk_state.cpp).
A allowed_commands(const ModernState& g, const UiContext& c) {
if (c.career_ended) return {};
const int team = team_of(g, c.manager);
const bool national = team == no_team();
static constexpr const char* kAll[] = {
"session.advance", "lineup.commit", "tactics.commit", "friendly.book", "manager.resign.commit",
"training.commit", "camp.book", "bank.commit", "toto.submit", "quote.request", "contract.offer",
"stadium.commit", "advertising.accept", "budget.commit", "ticket.commit", "transfer.submit",
"sponsor.answer", "environment.commit", "fixture.reschedule", "contract.cancel", "news.update", "balance.commit", "settings.commit", "manager.join.commit"};
A out;
for (size_t i = 0; i < std::size(kAll); ++i)
if (!national || i < 5 || std::string(kAll[i]) == "settings.commit") out.push_back(kAll[i]);
return out;
}
J meta(const ModernState& g, const UiContext& c) {
const AlmanacDate today = almanac_date(g.date, g.display_start_year);
const int start = g.display_start_year + g.season, next = (start + 1) % 100;
const std::string label = std::to_string(start) + "/" + (next < 10 ? "0" : "") + std::to_string(next);
const int team = team_of(g, c.manager);
const bool national = team == no_team();
const std::string revision = std::to_string(c.state_revision);
const World* world = current_world();
return O{{"contractVersion", kContractVersion}, {"draft", true}, {"sourceRevision", nullptr},
{"careerId", g.career_id.empty() ? J(nullptr) : J(g.career_id)},
{"worldId", world ? J(world->id) : J(nullptr)},
{"worldRevision", world ? J(world->data_revision) : J(nullptr)},
{"stateRevision", revision}, {"projectionRevision", revision}, {"locale", "de"},
{"date", iso(today)},
{"season", O{{"id", "season:" + std::to_string(start) + "-" + (next < 10 ? "0" : "") + std::to_string(next)},
{"startDate", iso(AlmanacDate{start, 7, 1})}, {"endDate", iso(AlmanacDate{start + 1, 6, 30})},
{"label", label}, {"completed", false}}},
{"scope", O{{"managerId", manager_id(g, c.manager)},
{"teamId", team >= 0 ? J(team_id(g, team)) : J(nullptr)},
{"role", national ? "national" : "club"},
{"scopeId", "scope:desk-" + revision + "-" + std::to_string(c.manager)},
{"allowedCommands", allowed_commands(g, c)}}},
{"availability", available()},
{"currency", O{{"code", "EUR"}, {"minorUnits", 2}}}};
}
J snapshot(const std::string& request_id, J meta_json, J data) {
return O{{"messageType", "snapshot"}, {"requestId", request_id}, {"meta", std::move(meta_json)}, {"data", std::move(data)}};
}
J failure(const std::string& request_id, const char* code, const std::string& message, uint64_t revision) {
return O{{"messageType", "error"}, {"requestId", request_id}, {"code", code}, {"message", text(message)},
{"currentRevision", std::to_string(revision)}, {"retryable", false}, {"stateChanged", false}};
}
// The session (Session of the contract): the human managers and their teams while it runs; after
// its end no active manager, the managers archived (their ids) and why it ended.
J session_data(const ModernState& g, const UiContext& c) {
A managers, ownership, archived_ids;
const bool ended = c.career_ended || !g.career_end_reason.empty();
bool national = false, club = false;
for (int m = 0; m < human_managers(g); ++m) {
const int team = human_team(g, m);
(team == no_team() ? national : club) = true;
if (ended) {
archived_ids.push_back(human_manager_id(g, m));
continue;
}
managers.push_back(manager_json(g, m));
if (team >= 0)
ownership.push_back(O{{"teamId", team_id(g, team)}, {"controller", "human"}, {"managerId", human_manager_id(g, m)},
{"sinceRevision", "0"}});
}
const std::string reason = !g.career_end_reason.empty() ? g.career_end_reason : ended ? "career_completed" : "";
return O{{"kind", "session"}, {"sessionState", ended ? "ended" : "desktop"},
{"activeManagerId", ended ? J(nullptr) : J(manager_id(g, c.manager))},
{"managers", std::move(managers)}, {"humanOwnership", std::move(ownership)},
{"archivedManagerIds", std::move(archived_ids)}, {"archivedManagerCount", int64_t(ended ? human_managers(g) : 0)},
{"terminationReason", reason.empty() ? J(nullptr) : J(reason)},
{"mode", national && club ? "mixed" : national ? "national" : "club"},
{"canAdvance", !ended}, {"blockingReason", ended ? J("session_ended") : J(nullptr)}};
}
J desktop_data(const ModernState& g, const UiContext& c, const std::string& today) {
const int team = team_of(g, c.manager);
const bool national = team == no_team();
O data{{"kind", "desktop"}, {"manager", manager_json(g, g.human_manager_slot(c.manager))}, {"team", team_ref(g, team, today)}};
// the account: the bank's savings and credit follow with the bank read
data["accounts"] = O{{"cash", ui_money(money_of(g, c.manager))}, {"savings", nullptr}, {"debt", nullptr},
{"netAssets", nullptr}};
J next = nullptr;
if (c.next_opponent && *c.next_opponent >= 0) {
J own = team_ref(g, team, today), other = team_ref(g, *c.next_opponent, today);
next = O{{"competition", text(c.next_competition)}, {"home", c.next_away ? other : own},
{"away", c.next_away ? own : other}, {"status", "scheduled"}, {"result", nullptr}};
}
data["nextFixture"] = std::move(next);
// ui/desk_state.cpp: at the national coach's desk there is no toto, bank, camp, training or stadium
O menus;
for (const char* menu : {"squad", "lineup", "tactics", "training", "camps", "transfer", "contracts", "bank", "balance",
"advertising", "environment", "stadium", "toto", "calendar", "statistics", "almanac"}) {
const std::string m = menu;
const bool closed = national && (m == "toto" || m == "bank" || m == "camps" || m == "training" || m == "stadium");
menus[m] = closed ? unavailable("national_desk") : available();
}
data["menuAvailability"] = std::move(menus);
return data;
}
J metric(int value) {
return O{{"value", value}, {"unit", "rating"}, {"scale", nullptr}, {"availability", available()}};
}
// The team a request names (teamId: a world id or "team:<n>"), or the manager's own team.
int requested_team(const ModernState& g, const UiContext& c, const J& request) {
const std::string wanted = text_field(request, "teamId");
if (wanted.empty()) return team_of(g, c.manager);
for (int t = 0; t < int(g.world_club_id.size()); ++t)
if (g.world_club_id[size_t(t)] == wanted) return t;
if (wanted.starts_with("team:")) {
try {
const int t = std::stoi(wanted.substr(5));
if (t >= 0 && t < world_layout().total_teams()) return t;
} catch (const std::exception&) {
}
}
return -1;
}
// A squad: every player with identity, position, values, absence and (for the manager's own
// club, from his tactics board) monthly salary and remaining contract months.
J squad_data(const ModernState& g, const UiContext& c, int team, const std::string& today) {
static constexpr const char* kPositions[4] = {"gk", "def", "mid", "fwd"};
static constexpr const char* kSkills[7] = {"teamplay", "speed", "shooting", "passing", "tackling", "free_kick", "corner"};
const bool own = team == team_of(g, c.manager) && team < league_clubs();
const size_t board = size_t(c.manager) * 0x840;
const SquadRange r = squad_range(team);
A players;
for (size_t s = r.first; s < r.first + r.count && s < g.squad_slots.size(); ++s) {
const uint16_t e = g.squad_slots[s];
const int id = e & 0x0fff;
if (id == 0x0fff) continue;
const Player& p = g.players.at(size_t(id));
std::string pid = entry(g.world_player_id, size_t(id));
if (pid.empty()) pid = "player:legacy-" + std::to_string(id);
const std::string& first = entry(g.player_first, size_t(id));
std::string last = entry(g.player_last, size_t(id));
if (last.empty()) last = almanac_utf8(g.player_name(id));
const std::string& nation = entry(g.player_nation, size_t(id));
const auto photo_of = [](const std::string& player) -> J {
const World* world = current_world();
const WorldPlayer* wp = world ? world->player(player) : nullptr;
return wp && !wp->photo.empty() ? J(wp->photo) : J(nullptr);
};
const uint32_t absence = p.w364 >> 16 & 0x1f; // weeks out; bit 4: banned instead of injured
const int injured = (absence & 0x10) ? 0 : int(absence), banned = (absence & 0x10) ? int(absence & 0xf) : 0;
O skills;
for (int k = 0; k < 7; ++k) skills[kSkills[k]] = int(p.w368 >> (2 * k) & 3);
O row{{"player", O{{"id", pid}, {"name", first.empty() ? last : first + " " + last}, {"photoAssetId", photo_of(pid)},
{"nationIds", nation.empty() ? A{} : A{J(nation)}}, {"positions", A{J(kPositions[p.position()])}},
{"shirtNumber", nullptr}}},
{"clubId", team < league_clubs() ? J(team_id(g, team)) : J(nullptr)},
{"squadTeamId", team_id(g, team)},
{"role", (e & 0x8000) ? "starter" : (e & 0x4000) ? "bench" : "reserve"},
{"availability", injured ? "injured" : banned ? "suspended" : "fit"},
{"injuryRemaining", O{{"value", injured}, {"unit", "weeks"}}},
{"suspensionRemaining", O{{"value", banned}, {"unit", "weeks"}}},
{"age", p.age()},
{"metrics", O{{"strength", metric(p.strength())}, {"condition", metric(p.condition())},
{"technique", metric(p.technique())}, {"form", metric(p.form())}}},
{"skills", std::move(skills)}};
const size_t at = board + (s - r.first) * 0x58;
if (own && at + 0x58 <= g.tactics.size()) {
const int64_t salary = int64_t(uint32_t(g.tactics[at + 0x50]) | uint32_t(g.tactics[at + 0x51]) << 8 |
uint32_t(g.tactics[at + 0x52]) << 16 | uint32_t(g.tactics[at + 0x53]) << 24);
row["salaryMonthly"] = ui_money(salary);
row["contractRemaining"] = O{{"value", int(g.tactics[at + 0x0c])}, {"unit", "months"}};
} else {
row["salaryMonthly"] = nullptr;
row["contractRemaining"] = nullptr;
}
row["contractUntil"] = nullptr;
players.push_back(std::move(row));
}
return O{{"kind", "squad"}, {"team", team_ref(g, team, today)}, {"players", std::move(players)}};
}
J report_league(const ModernState& g, int league, int own) {
const int first=league_first_team(league), count=kLeagueSizes[league];
const World* world=current_world();
const WorldClub* club=world?world->club(team_id(g,first)):nullptr;
A members;
for(int i=0;i<count;++i)members.push_back(team_id(g,first+i));
return O{{"id",size_t(league)<g.world_league_id.size()&&!g.world_league_id[size_t(league)].empty()?g.world_league_id[size_t(league)]:"league:"+std::to_string(league)},
{"name",size_t(league)<g.world_league_name.size()&&!g.world_league_name[size_t(league)].empty()?g.world_league_name[size_t(league)]:"Liga "+std::to_string(league+1)},
{"nationId",club&&!club->nation.empty()?J(club->nation):J(nullptr)},
{"members",std::move(members)},{"clubCount",count},{"matchdays",league_matchdays(league)},
{"played",size_t(league)<g.league_rounds.size()?int(g.league_rounds[size_t(league)]):0},
{"own",own>=first&&own<first+count}};
}
J league_report_data(const ModernState& g,int league,int filter,const std::string& today) {
const int first=league_first_team(league), count=kLeagueSizes[league], half=count-1;
const int played=size_t(league)<g.league_rounds.size()?g.league_rounds[size_t(league)]:0;
const int from=filter==2?half:0, until=filter==1?std::min(played,half):played;
const int flags=4|(filter==3?1:filter==4?2:3);
auto table=compute_league_table(g,league,from,until,flags,1);
bool any=false;for(int i=0;i<count;++i)any|=table.games(i)>0;
if(!any)sort_table(table,0); // A not-yet-played half still has unique Source ranks.
A rows,strengths;
for(int i=0;i<count;++i) {
const int team=first+i;
std::string form;int form_points=0;
for(int n=0;n<8;++n) {
const int code=int(table.form[size_t(i)]>>(3*n)&7);
if(!code)break;
const int outcome=code&3;const char symbol=outcome==3?'S':outcome==2?'U':outcome==1?'N':'-';
form.insert(form.begin(),symbol);form_points+=outcome==3?3:outcome==2?1:0;
}
const int games=table.games(i),wins=table.wins[size_t(i)],loss=table.defeats[size_t(i)];
// the places the season decides (schedule.hpp): the top of the first league is the
// prediction's European target, the top of a lower league goes up, the foot goes down
const int place=table.rank(i)+1, top=league==0?4:kLeagueEurope[league];
const char* zone=place<=top?(league==0?"europe":"promotion"):place>count-int(kLeagueRelegation[league])?"relegation":"";
rows.push_back(O{{"zone",zone},{"team",team_ref(g,team,today)},{"original",i},{"rank",table.rank(i)+1},{"played",games},{"wins",wins},
{"draw",std::max(0,games-wins-loss)},{"loss",loss},{"gf",int(table.goals_for[size_t(i)])},{"ga",int(table.goals_against[size_t(i)])},
{"diff",int(table.goals_for[size_t(i)])-int(table.goals_against[size_t(i)])},{"points",int(table.points[size_t(i)])},{"form",form_points},{"form_text",form}});
int positions[4]={};
if(fields_players(g,team)) {
const auto range=squad_range(team);
for(size_t s=range.first;s<range.first+range.count&&s<g.squad_slots.size();++s) {
const int player=g.squad_slots[s]&0xfff;
if(player!=0xfff&&size_t(player)<g.players.size())++positions[g.players[size_t(player)].position()];
}
}
O row{{"team",team_ref(g,team,today)},{"original",i},{"basis","squad"}};
const char* keys[4]={"keeper","defence","midfield","attack"};
int total=0;
for(int p=0;p<4;++p){total+=positions[p];row[keys[p]]=positions[p]?J(team_average(g,team,uint16_t(0xf|(0x10<<p))).value):J(nullptr);}
row["strength"]=total?J(team_average(g,team,0xff).value):J(nullptr);
strengths.push_back(std::move(row));
}
return O{{"kind","league-report"},{"leagueId",size_t(league)<g.world_league_id.size()&&!g.world_league_id[size_t(league)].empty()?g.world_league_id[size_t(league)]:"league:"+std::to_string(league)},
{"filter",filter},{"table",std::move(rows)},{"strengths",std::move(strengths)},{"zones",nullptr}};
}
// The training camps (docs/new_engine/trainingslager.md): catalogue, the price for the own
// squad (base price + 5000 per player, no random draw: a binding quote), focus and bookings.
J camps_data(const ModernState& g, const UiContext& c, const std::string& revision) {
const size_t rec = size_t(c.manager) * kRecord;
const TrainingCampBookingBlock block = training_camp_booking_block(g, c.manager);
const char* reason = block == TrainingCampBookingBlock::booked_this_week ? "booked_this_week"
: block == TrainingCampBookingBlock::visit_limit ? "visit_limit"
: block == TrainingCampBookingBlock::invalid_request ? "no_club"
: nullptr;
const int64_t cash = money_of(g, c.manager);
A maps;
for (const CampMap& m : g.camp_maps)
maps.push_back(O{{"id", m.id}, {"name", text(m.name)}, {"guiAssetKey", "gui:map/" + (m.id.starts_with("map:") ? m.id.substr(4) : m.id)},
{"width", m.width ? J(*m.width) : J(nullptr)}, {"height", m.height ? J(*m.height) : J(nullptr)}});
A camps;
for (size_t i = 0; i < g.training_camps.size(); ++i) {
const TrainingCamp& t = g.training_camps[i];
J quote = nullptr;
if (block != TrainingCampBookingBlock::invalid_request) {
const int64_t price = training_camp_price(g, c.manager, int(i));
const int64_t base = t.base_price;
const char* blocked = reason ? reason : nullptr;
// book_money allows the credit line too; the read names only the plain case
quote = O{{"id", "quote:camp-" + revision + "-" + std::to_string(i)}, {"ownerManagerId", manager_id(g, c.manager)},
{"teamId", team_id(g, team_of(g, c.manager))}, {"expectedRevision", revision},
{"scopeId", "scope:desk-" + revision + "-" + std::to_string(c.manager)}, {"expiresOn", nullptr},
{"total", ui_money(price)}, {"totalBasis", "immediate"}, {"chargesNow", ui_money(price)},
{"breakdown", A{O{{"code", "base"}, {"amount", ui_money(base)}},
O{{"code", "squad"}, {"amount", ui_money(price - base)}}}},
{"allowed", blocked == nullptr}, {"reasonCode", blocked ? J(blocked) : J(nullptr)},
{"exceedsCash", price > cash}};
}
camps.push_back(O{{"id", t.id}, {"mapId", t.map}, {"name", text(t.name)}, {"place", t.place},
{"nationId", t.country.empty() ? J(nullptr) : J(t.country)},
{"position", t.x && t.y ? J(O{{"x", *t.x}, {"y", *t.y}}) : J(nullptr)},
{"quality", O{{"pitch", int(t.quality[0])}, {"fitness", int(t.quality[1])},
{"catering", int(t.quality[2])}, {"lodging", int(t.quality[3])}}},
{"guiImageKey", "gui:camp/" + std::to_string(i)}, {"worldImageAssetId", nullptr},
{"sponsorChance", t.sponsor_chance}, {"quote", std::move(quote)}});
}
const uint8_t stays = rec + 0x21f < g.manager_records.size() ? g.manager_records[rec + 0x21f] : 0;
O focus;
if (rec + 0xc4 < g.manager_records.size())
focus = O{{"condition", int(g.manager_records[rec + 0xc1])}, {"technique", int(g.manager_records[rec + 0xc2])},
{"play", int(g.manager_records[rec + 0xc3])}, {"recovery", int(g.manager_records[rec + 0xc4])}};
return O{{"kind", "camps"}, {"maps", std::move(maps)}, {"camps", std::move(camps)}, {"focus", std::move(focus)},
{"staysThisSeason", int(stays & 0x7f)}, {"staysLimit", 3}, {"bookedThisWeek", (stays & 0x80) != 0},
{"availability", reason ? unavailable(reason) : available()}};
}
} // namespace
void ensure_ui_identities(ModernState& g) {
if (g.career_id.empty()) {
std::random_device device;
const uint64_t value = uint64_t(device()) << 32 | device();
char id[32];
std::snprintf(id, sizeof id, "career:%016llx", static_cast<unsigned long long>(value));
g.career_id = id;
}
const size_t humans = size_t(std::max(0, human_managers(g)));
if (g.manager_ids.size() < humans) g.manager_ids.resize(humans);
for (auto& id : g.manager_ids)
if (id.empty()) id = "manager:" + std::to_string(++g.manager_serial);
}
cli::Json ui_command_result(const std::string& request_id, uint64_t previous, uint64_t next,
const std::vector<std::string>& changed_reads, const std::string& feedback) {
A changed;
for (const auto& k : changed_reads) changed.push_back(k);
return O{{"messageType", "command_result"}, {"requestId", request_id}, {"accepted", true},
{"previousRevision", std::to_string(previous)}, {"newRevision", std::to_string(next)},
{"outcome", next == previous ? "no_change" : "applied"}, {"changedReadKinds", std::move(changed)},
{"ownershipChange", nullptr}, {"feedback", text(feedback)}};
}
cli::Json ui_error(const std::string& request_id, const std::string& code, const std::string& message,
uint64_t revision, bool retryable) {
return O{{"messageType", "error"}, {"requestId", request_id}, {"code", code}, {"message", text(message)},
{"currentRevision", std::to_string(revision)}, {"retryable", retryable}, {"stateChanged", false}};
}
std::string ui_manager_id(const ModernState& g, int manager) { return manager_id(g, manager); }
cli::Json ui_money(int64_t euros) {
return O{{"minor", std::to_string(euros * 100)}, {"currency", "EUR"}, {"minorUnits", 2}};
}
cli::Json ui_snapshot(const ModernState& g, const UiContext& c, const std::string& request_id, cli::Json data) {
return snapshot(request_id, meta(g, c), std::move(data));
}
std::string ui_team_id(const ModernState& g, int team) { return team_id(g, team); }
cli::Json ui_manager(const ModernState& g, int manager) { return manager_json(g, g.human_manager_slot(manager)); }
std::string ui_player_id(const ModernState& g, int player) {
std::string id = entry(g.world_player_id, size_t(player));
return id.empty() ? "player:legacy-" + std::to_string(player) : id;
}
cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& request) {
const std::string request_id = text_field(request, "requestId");
const std::string kind = text_field(request, "kind");
if (c.manager < 0 || c.manager >= int(g.manager_teams.size()))
return failure(request_id, "no_active_manager", "Kein Manager am Schreibtisch.", c.state_revision);
// A read names the manager it is for; it must be the one at the desk (the session decides
// who acts, not the request).
if (const std::string wanted = text_field(request, "managerId"); !wanted.empty() && wanted != manager_id(g, c.manager))
return failure(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", c.state_revision);
J m = meta(g, c);
const std::string today = *std::get<O>(m.value).at("date").string();
if (kind == "session") return snapshot(request_id, std::move(m), session_data(g, c));
if (kind == "desktop") return snapshot(request_id, std::move(m), desktop_data(g, c, today));
if (kind == "file-metadata") {
const auto* world=current_world();
if(!world)return failure(request_id,"world_unavailable","Keine aktive Modern-Welt.",c.state_revision);
try{return snapshot(request_id,std::move(m),world_career_metadata(*world,g));}
catch(const std::exception&){return failure(request_id,"metadata_unavailable","Spielstandangaben nicht verfügbar.",c.state_revision);}
}
if (kind == "camps") return snapshot(request_id, std::move(m), camps_data(g, c, std::to_string(c.state_revision)));
if (kind == "player-rankings" || kind == "fairplay") {
J data = query_rankings(g, c.manager, request);
auto* values = std::get_if<O>(&data.value);
if (!values || !values->count("ok") || !std::holds_alternative<bool>(values->at("ok").value) || !std::get<bool>(values->at("ok").value))
return failure(request_id, "rankings_unavailable", "Diese Statistik ist im aktuellen Kontext nicht verfügbar.", c.state_revision);
values->erase("ok"); return snapshot(request_id, std::move(m), std::move(data));
}
if (kind == "other-index" || kind == "other-fixtures") {
J data = query_projection(g, c.manager, request);
auto* values = std::get_if<O>(&data.value);
if (!values || !values->count("ok") || !std::holds_alternative<bool>(values->at("ok").value) || !std::get<bool>(values->at("ok").value))
return failure(request_id, "other_reports_unavailable", "Wettbewerb oder Runde ist derzeit nicht verfügbar.", c.state_revision);
values->erase("ok"); return snapshot(request_id, std::move(m), std::move(data));
}
if(kind=="report-index") {
A leagues;for(int l=0;l<kLeagueCount;++l)leagues.push_back(report_league(g,l,team_of(g,c.manager)));
return snapshot(request_id,std::move(m),O{{"kind","report-index"},{"leagues",std::move(leagues)}});
}
if(kind=="league-fixtures") {
const std::string id=text_field(request,"leagueId");int league=-1;
for(int l=0;l<kLeagueCount;++l)if(*std::get<O>(report_league(g,l,-1).value).at("id").string()==id){league=l;break;}
const auto* round=field(request,"round");
if(league<0||(round&&(!round->integer()||*round->integer()<1||*round->integer()>league_matchdays(league))))
return failure(request_id,"invalid_fixture_request","Liga oder Spieltag ist nicht verfügbar.",c.state_revision);
O query{{"kind","fixtures"},{"league",id}};
if(round)query["matchday"]=*round;
J data=query_projection(g,c.manager,query);
auto* values=std::get_if<O>(&data.value);
if(!values||!values->count("ok")||!std::holds_alternative<bool>(values->at("ok").value)||!std::get<bool>(values->at("ok").value))
return failure(request_id,"fixtures_unavailable","Die Paarungen sind derzeit nicht verfügbar.",c.state_revision);
values->erase("ok");(*values)["kind"]="league-fixtures";(*values)["leagueId"]=id;(*values)["round"]=values->at("matchday");(*values)["rounds"]=league_matchdays(league);
return snapshot(request_id,std::move(m),std::move(data));
}
if(kind=="league-report") {
const std::string id=text_field(request,"leagueId");int league=-1;
for(int l=0;l<kLeagueCount;++l)if(*std::get<O>(report_league(g,l,-1).value).at("id").string()==id){league=l;break;}
const auto* f=field(request,"filter");const auto* value=f?f->integer():nullptr;
if(league<0||!value||*value<0||*value>4)return failure(request_id,"invalid_report_request","Liga oder Tabellenfilter ist nicht verfügbar.",c.state_revision);
return snapshot(request_id,std::move(m),league_report_data(g,league,int(*value),today));
}
if (kind == "almanac") {
const J* query = field(request, "query");
if (!query || !query->object())
return failure(request_id, "invalid_almanac_request", "Eine Almanachabfrage wird benötigt.", c.state_revision);
J result = query_almanac(g, *query);
const J* ok = field(result, "ok");
if (!ok || !std::holds_alternative<bool>(ok->value) || !std::get<bool>(ok->value))
return failure(request_id, text_field(result, "error").c_str(), "Der Spielarchiv-Eintrag ist nicht verfügbar.", c.state_revision);
return snapshot(request_id, std::move(m), O{{"kind", "almanac"}, {"query", *query}, {"result", std::move(result)}});
}
if (kind == "news") {
// the press events of a team (teamId, default the desk's team) from `from` to `until` (ISO,
// default everything up to today), newest last, at most `limit` (default 50) of the newest
const int team = requested_team(g, c, request);
if (team < 0) return failure(request_id, "unknown_team", "teamId nennt kein Team.", c.state_revision);
const std::string from = text_field(request, "from").empty() ? "0000-00-00" : text_field(request, "from");
const std::string until = text_field(request, "until").empty() ? today : text_field(request, "until");
const J* limit_field = field(request, "limit");
const int64_t limit = limit_field && limit_field->integer() && *limit_field->integer() > 0 ? *limit_field->integer() : 50;
J news = query_news(g, team_id(g, team), from, until);
A events = std::move(std::get<A>(std::get<O>(news.value).at("events").value));
for (J& e : journal_events(g, team_id(g, team), from, until)) events.push_back(std::move(e));
std::stable_sort(events.begin(), events.end(), [](const J& a, const J& b) {
return *std::get<O>(a.value).at("date").string() < *std::get<O>(b.value).at("date").string();
});
const size_t total = events.size();
if (events.size() > size_t(limit)) events.erase(events.begin(), events.end() - limit);
return snapshot(request_id, std::move(m),
O{{"kind", "news"}, {"teamId", team_id(g, team)}, {"from", from}, {"until", until}, {"total", int64_t(total)},
{"events", std::move(events)},
{"sources", A{J("almanac"), J("journal")}}});
}
if (kind == "friendly-plan") {
// Read the saved plan, never a UI-local booking log. These are the same
// verified 30 day/team entries used by book_friendly_match.
const int own = team_of(g, c.manager);
const bool national = own == no_team();
if (!national && (own < 0 || own >= league_clubs()))
return failure(request_id, "no_club", "Freundschaftsplanung ist hier nicht verfügbar.", c.state_revision);
constexpr uint32_t entries = 30;
if (!g.memory.has(layout::FriendlyDays + entries * 2 - 1) ||
!g.memory.has(layout::FriendlyTeams + entries * 4 - 1))
return failure(request_id, "friendly_plan_unavailable", "Der Spielplan ist unvollständig.", c.state_revision);
A opponents, bookings;
for (int t = national ? no_team() + 1 : 0; t < (national ? world_layout().total_teams() : first_foreign_cup()); ++t) {
if (t == own) continue;
const int league = team_league(t);
const std::string league_id = league >= 0 && size_t(league) < g.world_league_id.size() ? g.world_league_id[size_t(league)] : std::string{};
opponents.push_back(O{{"team", team_ref(g, t, today)},
{"competitionId", league_id.empty() ? J(nullptr) : J(league_id)},
{"strength", t < league_clubs() ? J(team_average(g, t, 0xff).value) : J(nullptr)}});
}
for (uint32_t i = 0; i < entries; ++i) {
const int day = g.memory.u16(layout::FriendlyDays + i * 2);
if (!day) continue;
const int home = int16_t(g.memory.u16(layout::FriendlyTeams + i * 4));
const int away = int16_t(g.memory.u16(layout::FriendlyTeams + i * 4 + 2));
if (home != own && away != own) continue;
if (day > 365 || home < 0 || away < 0 || home >= world_layout().total_teams() || away >= world_layout().total_teams())
return failure(request_id, "friendly_plan_unavailable", "Ungültiger Eintrag im Spielplan.", c.state_revision);
const std::string date = iso(almanac_date(g.season_start + uint32_t(day), g.display_start_year));
bookings.push_back(O{{"id", "friendly:" + date + ":" + team_id(g, home) + ":" + team_id(g, away)},
{"date", date}, {"home", team_ref(g, home, date)}, {"away", team_ref(g, away, date)}});
}
return snapshot(request_id, std::move(m), O{{"kind", "friendly-plan"}, {"national", national}, {"teamId", team_id(g, own)},
{"opponents", std::move(opponents)}, {"bookings", std::move(bookings)}});
}
if (kind == "calendar") {
// the season calendar of the desk's team: days from `from` to `until` (ISO dates, default
// the current month) with the day's competitions and the team's league matches (planned
// day, or the replay day of a moved/postponed one with its original date). No draw.
const int own = team_of(g, c.manager);
const auto date_of = [&](int day) { return iso(almanac_date(g.season_start + uint32_t(day), g.display_start_year)); };
const std::string from = text_field(request, "from").empty() ? today.substr(0, 8) + "01" : text_field(request, "from");
const std::string until = text_field(request, "until").empty() ? today.substr(0, 8) + "31" : text_field(request, "until");
if (from.size() != 10 || until.size() != 10 || until < from)
return failure(request_id, "invalid_range", "from und until sind ISO-Daten, until nicht vor from.", c.state_revision);
A days, fixtures;
for (const ClubCalendarDay& d : club_calendar(g, own)) {
const std::string date = date_of(d.day);
if (date < from || date > until) continue;
A kinds, ids;
if (own == no_team()) {
// day_competitions rotates the national qualifiers/finals through
// bits 9..12. Club tournament flags do not describe this desk.
if (d.competitions & 0x801e00) kinds.push_back("national");
} else {
if (d.competitions & 0x1f) kinds.push_back("league");
for (int bit = 5; bit < 15; ++bit)
if (d.competitions >> bit & 1) kinds.push_back("cup:" + std::to_string(bit - 5));
if (d.competitions & 0x8000) kinds.push_back("replay");
if (d.competitions & 0x10000) kinds.push_back("indoor");
if (d.competitions & 0x40000) kinds.push_back("special");
if (d.competitions & 0x800000) kinds.push_back("national");
}
if (d.friendly) kinds.push_back("friendly");
for (const ClubCalendarMatch& cm : d.matches) {
const std::string id = "fixture:league-" + std::to_string(cm.league) + "-" + std::to_string(cm.round + 1) + "-" + std::to_string(cm.match);
ids.push_back(id);
const bool open = (cm.result & 0xcc) == 0xcc;
const bool past = d.day < g.season_day();
const std::string league_id = cm.league < int(g.world_league_id.size()) && !g.world_league_id[size_t(cm.league)].empty()
? g.world_league_id[size_t(cm.league)] : "league:" + std::to_string(cm.league);
fixtures.push_back(O{{"id", id}, {"competition", O{{"id", league_id}, {"kind", "league"}}},
{"round", cm.round + 1}, {"originalDate", cm.original_day >= 0 ? J(date_of(cm.original_day)) : J(date)},
{"scheduledDate", date}, {"home", team_ref(g, cm.home, date)}, {"away", team_ref(g, cm.away, date)},
{"status", !open ? "played" : cm.result == 0xcd && cm.original_day < 0 ? "postponed"
: cm.original_day >= 0 ? "rescheduled" : past ? "void" : "scheduled"},
{"result", open ? J(nullptr) : J(A{J(cm.result >> 4), J(cm.result & 0xf)})}});
}
if (kinds.empty() && ids.empty()) continue;
days.push_back(O{{"date", date}, {"seasonDay", d.day}, {"today", d.day == g.season_day()},
{"eventKinds", std::move(kinds)}, {"fixtureIds", std::move(ids)}});
}
return snapshot(request_id, std::move(m),
O{{"kind", "calendar"}, {"from", from}, {"until", until}, {"days", std::move(days)}, {"fixtures", std::move(fixtures)}});
}
if (kind == "scheduling" || kind == "friendly") {
const int own = team_of(g, c.manager);
if (own < 0 || own >= league_clubs())
return failure(request_id, "no_club", "Am Schreibtisch des Bundestrainers gibt es das nicht.", c.state_revision);
const auto date_of = [&](int day) { return iso(almanac_date(g.season_start + uint32_t(day), g.display_start_year)); };
if (kind == "scheduling") {
// league matches that can be moved (own home matches, rounds 1 .. matchdays - 3) with
// the dates they can go to, and moved ones that can be taken back (no random draw)
const auto ref_id = [](const LeagueMatchRef& r) {
return "move:" + std::to_string(r.day) + "-" + std::to_string(r.league) + "-" + std::to_string(r.round) + "-" + std::to_string(r.match);
};
A movable, moved;
for (const auto& r : reschedulable_matches(g, c.manager)) {
A targets;
for (int day : reschedule_target_days(g, c.manager, r)) targets.push_back(date_of(day));
movable.push_back(O{{"id", ref_id(r)}, {"date", date_of(r.day)}, {"round", r.round + 1},
{"home", team_ref(g, r.home, date_of(r.day))}, {"away", team_ref(g, r.away, date_of(r.day))},
{"targetDates", std::move(targets)}});
}
for (const auto& r : moved_matches(g, c.manager))
moved.push_back(O{{"date", date_of(r.day)}, {"round", r.round + 1}, {"home", team_ref(g, r.home, date_of(r.day))},
{"away", team_ref(g, r.away, date_of(r.day))}});
return snapshot(request_id, std::move(m), O{{"kind", "scheduling"}, {"movable", std::move(movable)}, {"moved", std::move(moved)}});
}
// friendly {opponentId, home?}: the price and venue quote and the free dates (no random draw)
const int opponent = requested_team(g, UiContext{c.state_revision, c.manager}, O{{"teamId", text_field(request, "opponentId")}});
const J* home_field = field(request, "home");
const bool home = !home_field || !std::holds_alternative<bool>(home_field->value) || std::get<bool>(home_field->value);
if (opponent < 0 || text_field(request, "opponentId").empty())
return failure(request_id, "unknown_team", "opponentId nennt keinen Verein.", c.state_revision);
const FriendlyBookingQuote q = quote_friendly_match(g, c.manager, opponent, home);
if (q.status != FriendlyQuoteStatus::quoted)
return failure(request_id, "friendly_unavailable", "Gegen diesen Verein ist kein Freundschaftsspiel möglich.", c.state_revision);
A dates;
for (int day = g.season_day() + 1; day <= 365; ++day) {
const FriendlyDateStatus st = friendly_match_date_status(g, q, uint16_t(day));
if (st == FriendlyDateStatus::available || st == FriendlyDateStatus::available_with_calendar_event)
dates.push_back(O{{"date", date_of(day)}, {"withCalendarEvent", st == FriendlyDateStatus::available_with_calendar_event}});
}
return snapshot(request_id, std::move(m),
O{{"kind", "friendly"}, {"home", team_ref(g, q.home_team, iso(almanac_date(g.date, g.display_start_year)))}, {"away", team_ref(g, q.away_team, iso(almanac_date(g.date, g.display_start_year)))},
{"cost", ui_money(q.cost)}, {"payerManagerId", q.payer_manager >= 0 ? J(manager_id(g, q.payer_manager)) : J(nullptr)},
{"opponentHuman", q.opponent_manager >= 0}, {"dates", std::move(dates)}});
}
if (kind == "environment") {
// the club's surroundings (Diamond 3.6): three youth teams, co-trainer, doctor, physio, each
// with a monthly budget level 0-6 and its cost; the youth teams' strength, place and league
static constexpr const char* kItems[6] = {"youth_youngest", "youth_academy", "youth_oldest", "co_trainer", "doctor", "physio"};
if (team_of(g, c.manager) < 0 || team_of(g, c.manager) >= league_clubs())
return failure(request_id, "no_club", "Am Schreibtisch des Bundestrainers gibt es kein Umfeld.", c.state_revision);
const EnvironmentState e = environment_state(g, c.manager);
A items, youth;
for (int i = 0; i < 6; ++i)
items.push_back(O{{"id", std::string("environment:") + kItems[i]}, {"level", e.level[size_t(i)]}, {"maxLevel", 6},
{"monthly", ui_money(e.monthly[size_t(i)])}, {"stepCost", ui_money(kEnvironmentStep[size_t(i)])}});
for (size_t t = 0; t < 3; ++t)
youth.push_back(O{{"id", std::string("youth:") + kItems[t]}, {"strength", int(e.youth_strength[t])},
{"place", int(e.youth_position[t])}, {"league", int(e.youth_league[t])}});
return snapshot(request_id, std::move(m), O{{"kind", "environment"}, {"items", std::move(items)}, {"youth", std::move(youth)},
{"academyActive", environment_academy_active(g, c.manager)}});
}
if (kind == "toto" || kind == "sponsor") {
// the existing projections (ui-abfragen.md), amounts as Money
J p = query_projection(g, c.manager, O{{"kind", kind}});
auto* o = std::get_if<O>(&p.value);
if (!o || !(*o)["ok"].value.index() || !std::get<bool>((*o)["ok"].value))
return failure(request_id, "unavailable", "Nicht verfügbar.", c.state_revision);
o->erase("ok");
const auto money = [](J& v) { if (v.integer()) v = ui_money(*v.integer()); };
if (kind == "toto") {
if(const auto* draft=field(request,"draft"))(*o)["draftQuote"]=quote_toto_draft(g,c.manager,*draft);
money((*o)["stake"]), money((*o)["cost"]);
auto& last = std::get<O>((*o)["last"].value);
money(last["paid"]), money(last["won"]);
} else {
for (const char* key : {"offer", "queued"})
if (auto* row = std::get_if<O>(&(*o)[key].value)) money((*row)["monthly"]);
}
(*o)["kind"] = kind;
return snapshot(request_id, std::move(m), std::move(p));
}
if (kind == "squad") {
const int team = requested_team(g, c, request);
if (team < 0 || !fields_players(g, team))
return failure(request_id, "unknown_team", "Dieses Team hat keinen Kader.", c.state_revision);
return snapshot(request_id, std::move(m), squad_data(g, c, team, today));
}
return failure(request_id, "unknown_read", "Unbekannte Abfrage: " + kind, c.state_revision);
}
} // namespace bmh::modern