Files
Dreierpack-Manager/tests/modern_ui_core_tests.cpp
T
MichaelandClaude Fable 5.2 b2500eb7b6 The surroundings on a plot of their own; the stadium views fill the window
The surroundings no longer show the ground: their fourteen objects stand along
an avenue on their own plot. Both views use the whole width of the window; the
lists on the right are gone, the pointer names a part and its state, and the
card of a chosen part lies over the picture.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 08:44:54 +01:00

889 lines
52 KiB
C++

// SPDX-License-Identifier: GPL-3.0-only
#include "modern/ui/demo_sports.hpp"
#include "modern/ui/demo_calendar.hpp"
#include "modern/ui/demo_reports.hpp"
#include "modern/ui/demo_finance.hpp"
#include "modern/ui/desktop.hpp"
#include "modern/ui/stadium_model.hpp"
#include "modern/ui/gui_assets.hpp"
#include "modern/ui/model.hpp"
#include "modern/ui/crest_contrast.hpp"
#include "modern/ui/demo_environment.hpp"
#include "modern/ui/demo_advertising.hpp"
#include "modern/ui/demo_toto.hpp"
#include "modern/ui/demo_lineup.hpp"
#include "modern/ui/demo_transfer.hpp"
#include "modern/ui/demo_stadium.hpp"
#include <chrono>
#include <cmath>
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace bmh::modern_ui;
namespace {
void require(bool value, const char *message) {
if (!value)
throw std::runtime_error(message);
}
void check_crest_contrast() {
using bmh::editor::images::Raster;
Raster source{16, 16, std::vector<uint8_t>(16 * 16 * 4)};
const auto pixel = [](Raster &r, int x, int y, std::array<uint8_t,4> rgba) {
std::copy(rgba.begin(), rgba.end(), r.pixels.begin() + (y * r.width + x) * 4);
};
for (int y = 3; y < 13; ++y)
for (int x = 4; x < 12; ++x) pixel(source,x,y,{255,255,255,255});
pixel(source,4,3,{224,224,224,96}); // antialiased edge
pixel(source,5,3,{100,100,100,64}); // embossed shadow
pixel(source,0,0,{213,29,91,0}); // invisible RGB is irrelevant
const auto original = source;
const auto variant = crest_for_light_surface(source);
require(variant && variant->width == source.width && variant->height == source.height,
"Light crest variant changed bounds or lost a shaded white crest");
require(source.pixels == original.pixels, "Crest display variant mutated source bytes");
for (size_t i = 0; i < source.pixels.size(); i += 4) {
require(variant->pixels[i+3] == source.pixels[i+3], "Crest variant changed alpha coverage");
if (!source.pixels[i+3])
for (int c = 0; c < 3; ++c)
require(variant->pixels[i+c] == source.pixels[i+c], "Invisible source RGB changed");
}
const auto luma = [](const Raster &r, size_t i) {
double out = 0; const std::array<double,3> weights{.2126,.7152,.0722};
for (size_t c = 0; c < 3; ++c) { const double v = r.pixels[i+c]/255.; out += weights[c]*(v<=.04045?v/12.92:std::pow((v+.055)/1.055,2.4)); }
return out;
};
const size_t center = (8*16+8)*4;
require((.8+.05)/(luma(*variant,center)+.05) > 7,
"White crest is still illegible on a light menu surface");
require(luma(*variant,(3*16+5)*4) < luma(*variant,center), "Crest shading was flattened");
auto coloured=source;pixel(coloured,8,8,{255,30,20,255});
require(!crest_for_light_surface(coloured), "Coloured crest details were recoloured");
auto black_white=source;
for (int x=4;x<12;++x) pixel(black_white,x,8,{0,0,0,255});
require(!crest_for_light_surface(black_white), "Black/white club crest was recoloured");
Raster tiny_black_detail{32,32,std::vector<uint8_t>(32*32*4)};
for(int y=4;y<28;++y)for(int x=4;x<28;++x)pixel(tiny_black_detail,x,y,{255,255,255,255});
pixel(tiny_black_detail,16,16,{0,0,0,255});
require(!crest_for_light_surface(tiny_black_detail), "Small black brand detail was recoloured");
auto blue=source;
for(size_t i=0;i<blue.pixels.size();i+=4)if(blue.pixels[i+3]) {blue.pixels[i]=220;blue.pixels[i+1]=240;blue.pixels[i+2]=255;}
require(!crest_for_light_surface(blue), "Pale coloured crest was recoloured");
Raster opaque{16,16,std::vector<uint8_t>(16*16*4,255)};
require(!crest_for_light_surface(opaque), "White rectangular artwork was recoloured");
pixel(opaque,0,0,{0,0,0,0});
require(!crest_for_light_surface(opaque), "Tiny transparent corner made a white backdrop qualify");
Raster empty{16,16,std::vector<uint8_t>(16*16*4,0)};
require(!crest_for_light_surface(empty) && !crest_for_light_surface(*variant),
"Empty/dark crest was recoloured");
require(!crest_for_light_surface(Raster{0,16,{}}) &&
!crest_for_light_surface(Raster{16,16,{255,255,255,255}}),
"Malformed raster bounds were accepted");
}
void write(const fs::path &root, const std::string &file, const Json &value) {
fs::create_directories((root / file).parent_path());
bmh::editor::write_atomic(root / file, value.dump());
}
void table(const fs::path &root, const std::string &name, const Json &rows) {
write(root,
name == "assets" ? "assets/index.json" : "world/" + name + ".json",
{{"schema", name + "@1.0"}, {"items", rows}});
}
void check_club_views(const fs::path &root, std::shared_ptr<const Catalog> world) {
DemoSource source(world);
auto initial = source.snapshot();
require(valid_demo_environment(initial.state, *world) && valid_demo_advertising(initial.state, *world) && valid_demo_toto(initial.state, *world), "Club preview initialization invalid");
require(source.apply({initial.revision, "environment", {{"kind", "level"}, {"index", 0}, {"value", 6}}}).ok, "Environment action failed");
auto changed = source.snapshot();
int slot = -1;
for (int i = 0; i < 16; ++i) if (changed.state["advertising"]["contracts"][size_t(i)]["sponsor"] == -1) {slot=i;break;}
require(slot >= 0, "No test offer slot");
const Json offer = {{"kind", "accept"}, {"slot", slot}, {"offer", 2}};
require(!source.apply({initial.revision, "advertising", offer}).ok && source.snapshot().state == changed.state && source.snapshot().revision == changed.revision, "Stale advertising quote changed source");
require(source.apply({changed.revision, "advertising", offer}).ok, "Valid advertising offer rejected");
changed = source.snapshot();
require(!source.apply({changed.revision, "advertising", offer}).ok && source.snapshot().state == changed.state, "Active advertising contract overwritten");
require(source.apply({changed.revision, "advertising", {{"kind", "spending"}, {"index", 2}, {"value", 7000}}}).ok, "Advertising budget rejected");
changed = source.snapshot();
for (const auto *key : {"cash", "deposit", "debt", "training", "tactics", "calendar", "reports", "finance", "contracts"})
require(changed.state.at(key) == initial.state.at(key), "Club previews changed unrelated state");
const auto saved = root / "club-preview-checkpoint.json";
source.save(saved, default_desktop());
source.apply({source.snapshot().revision, "environment", {{"kind", "level"}, {"index", 0}, {"value", 0}}});
source.load(saved);
require(source.snapshot().state == changed.state && !source.dirty(), "Club preview checkpoint did not roundtrip");
auto malformed = changed.state; malformed["desktop"] = default_desktop();
malformed["advertising"]["spending"][0] = "invalid";
{std::ofstream out(saved);out << malformed.dump();}
const auto before = source.snapshot(); bool threw = false;
try {source.load(saved);} catch (const std::exception &) {threw = true;}
require(threw && source.snapshot().state == before.state && source.snapshot().revision == before.revision, "Malformed club checkpoint partially loaded");
auto legacy = changed.state; legacy["desktop"] = default_desktop();
legacy.erase("environment"); legacy.erase("advertising"); legacy.erase("toto");
{std::ofstream out(saved);out << legacy.dump();}
source.load(saved); const auto migrated = source.snapshot().state;
require(migrated["environment"] == initial.state["environment"] && migrated["advertising"] == initial.state["advertising"] && migrated["toto"] == initial.state["toto"], "Legacy club fields not initialized");
require(migrated["cash"] == changed.state["cash"] && migrated["finance"] == changed.state["finance"], "Legacy migration reset wallet");
}
void check_squad_source(const fs::path &root, const std::shared_ptr<const Catalog> &world) {
DemoSource source(world);
const auto initial = source.snapshot();
const auto club = initial.state.at("managers")[0].at("club").get<std::string>();
require(valid_demo_lineup(initial.state, *world, club) && valid_demo_transfer(initial.state, *world, club),
"Lineup/transfer initialization failed for a small synthetic squad");
require(source.apply({initial.revision, "transfer", {{"kind", "search"}, {"query", "Synthetic"}}}).ok,
"Transfer search failed through the source boundary");
const auto searched = source.snapshot();
require(!source.apply({initial.revision, "lineup", {{"kind", "weight"}, {"index", 0}}}).ok &&
source.snapshot().revision == searched.revision && source.snapshot().state == searched.state,
"Stale lineup request changed state");
const auto points = searched.state.at("lineup").at("points");
const auto &order = searched.state.at("lineup").at("order");
require(order.size() >= 2, "Synthetic roster needs two players");
require(source.apply({searched.revision, "lineup", {{"kind", "move"}, {"player", order[1]}, {"point", {6,1}}}}).ok,
"Lineup move failed through the source boundary");
auto changed = source.snapshot();
require(tactics_diagram(changed.state.at("tactics"), "midnight", points) !=
tactics_diagram(changed.state.at("tactics"), "midnight", changed.state.at("lineup").at("points")),
"Tactics did not reflect edited lineup positions");
for (const auto *key : {"cash", "deposit", "debt", "training", "tactics", "calendar", "reports", "finance", "contracts"})
require(changed.state.at(key) == initial.state.at(key), "Squad preview changed unrelated game state");
auto bad = Json{{"kind", "move"}, {"player", order[1]}, {"point", {19,1}}};
require(!source.apply({changed.revision, "lineup", bad}).ok && source.snapshot().state == changed.state,
"Rejected lineup position partially committed");
const auto file = root / "squad-checkpoint.json";
source.save(file, default_desktop());
require(!source.dirty(), "Squad checkpoint did not clear dirty marker");
source.apply({source.snapshot().revision, "transfer", {{"kind", "search"}, {"query", "Different"}}});
source.load(file);
require(source.snapshot().state == changed.state && !source.dirty(), "Squad preview did not roundtrip");
auto invalid = changed.state; invalid["desktop"] = default_desktop();
invalid["lineup"]["order"][0] = invalid["lineup"]["order"][1];
{std::ofstream out(file);out << invalid.dump();}
const auto before = source.snapshot(); bool rejected = false;
try {source.load(file);} catch (const std::exception &) {rejected = true;}
require(rejected && source.snapshot().state == before.state && source.snapshot().revision == before.revision,
"Malformed squad checkpoint partially replaced the source");
auto legacy = changed.state; legacy["desktop"] = default_desktop();
legacy.erase("lineup"); legacy.erase("transfer");
{std::ofstream out(file);out << legacy.dump();}
source.load(file);
require(source.snapshot().state.at("lineup") == initial.state.at("lineup") &&
source.snapshot().state.at("transfer") == initial.state.at("transfer") &&
source.snapshot().state.at("cash") == changed.state.at("cash"),
"Legacy squad migration reset finances or failed to initialize defaults");
}
void check_stadium_source(const fs::path &root, const std::shared_ptr<const Catalog> &world) {
DemoSource source(world);
const auto initial = source.snapshot();
const auto club = initial.state.at("managers")[0].at("club").get<std::string>();
require(valid_demo_stadium(initial.state, *world, club), "Stadium initialization failed");
const Json request = {{"kind", "block"}, {"index", 0}, {"places", 4000},
{"seats", false}, {"roof", false}};
const Json action = {{"kind", "build"}, {"request", request}};
const auto quote = demo_stadium_quote(initial.state, request, *world, club);
require(quote.value("can_build", false), "Synthetic stadium quote unavailable");
require(source.apply({initial.revision, "stadium", action}).ok,
"Stadium build did not cross source boundary");
const auto built = source.snapshot();
require(built.revision == initial.revision + 1 && source.dirty() &&
built.state.at("stadium").at("blocks")[0].at("job").at("places") == 4000 &&
built.state.at("stadium").at("budget") == quote.at("remaining"),
"Stadium build did not atomically reserve its local budget");
for (const auto &[key, value] : initial.state.items())
if (key != "stadium") require(built.state.at(key) == value, "Stadium build changed unrelated state");
require(!source.apply({initial.revision, "stadium", action}).ok &&
!source.apply({built.revision, "stadium", action}).ok &&
!source.apply({built.revision, "stadium", {{"kind", "build"}, {"request",
{{"kind", "periphery"}, {"index", 0}, {"level", 1}}}}}).ok &&
source.snapshot().state == built.state && source.snapshot().revision == built.revision,
"Stale, duplicate or unchanged periphery build changed state");
const auto file = root / "stadium.ui.json";
source.save(file, default_desktop());
require(source.apply({source.snapshot().revision, "ticket", 9}).ok &&
source.snapshot().state.at("stadium") == built.state.at("stadium"),
"Shared ticket action changed construction ledger");
source.load(file);
require(source.snapshot().state == built.state && !source.dirty(), "Stadium job did not roundtrip");
auto malformed = Json::parse(bmh::editor::read_file(file));
malformed["stadium"]["budget"] = malformed["stadium"]["budget"].get<int64_t>() + 1;
write(root, "invalid-stadium.ui.json", malformed);
const auto accepted = source.snapshot(); bool rejected = false;
try { source.load(root / "invalid-stadium.ui.json"); } catch (const std::exception &) { rejected = true; }
require(rejected && source.snapshot().state == accepted.state &&
source.snapshot().revision == accepted.revision && !source.dirty(),
"Invalid stadium checkpoint partially replaced source");
auto legacy = Json::parse(bmh::editor::read_file(file)); legacy.erase("stadium");
write(root, "legacy-stadium.ui.json", legacy); source.load(root / "legacy-stadium.ui.json");
require(source.snapshot().state.at("stadium") == initial.state.at("stadium") &&
source.snapshot().state.at("cash") == built.state.at("cash") &&
source.snapshot().state.at("ticket") == built.state.at("ticket"),
"Legacy stadium migration reset unrelated values");
const auto perimeter_initial = source.snapshot();
const auto perimeter_action = [](int level) {
return Json{{"kind", "build"}, {"request", {{"kind", "periphery"}, {"index", 0}, {"level", level}}}};
};
require(!source.apply({perimeter_initial.revision, "stadium", perimeter_action(3)}).ok &&
source.snapshot().state == perimeter_initial.state,
"Source accepted skipped periphery level");
require(source.apply({perimeter_initial.revision, "stadium", perimeter_action(2)}).ok,
"Periphery next level did not cross source boundary");
const auto perimeter_built = source.snapshot();
require(perimeter_built.revision == perimeter_initial.revision + 1 && source.dirty() &&
perimeter_built.state.at("stadium").at("periphery")[0].at("job").at("level") == 2 &&
!source.apply({perimeter_initial.revision, "stadium", perimeter_action(2)}).ok &&
!source.apply({perimeter_built.revision, "stadium", perimeter_action(2)}).ok &&
source.snapshot().state == perimeter_built.state,
"Periphery stale/duplicate booking changed source");
for (const auto &[key, value] : perimeter_initial.state.items())
if (key != "stadium") require(perimeter_built.state.at(key) == value, "Periphery changed unrelated state");
source.save(file, default_desktop());
require(source.apply({source.snapshot().revision, "ticket", 8}).ok, "Ticket change failed");
source.load(file);
require(source.snapshot().state == perimeter_built.state && !source.dirty(),
"Periphery pending checkpoint did not roundtrip");
auto old_stadium = Json::parse(bmh::editor::read_file(file));
old_stadium["stadium"].erase("periphery");
old_stadium["stadium"]["budget"] = initial.state.at("stadium").at("budget");
write(root, "old-four-field-stadium.ui.json", old_stadium);
source.load(root / "old-four-field-stadium.ui.json");
require(source.snapshot().state.at("stadium") == initial.state.at("stadium") &&
source.snapshot().state.at("ticket") == perimeter_built.state.at("ticket"),
"Old four-field checkpoint did not migrate periphery through source");
}
void check_finance_source(const fs::path &root,
const std::shared_ptr<const Catalog> &base) {
const auto folder = root / "finance-source";
auto manifest = base->manifest();
manifest["id"] = "world:synthetic-finance-source";
manifest["currency"] = {{"code", "EUR"}, {"minor_units", 2}};
write(folder, "manifest.json", manifest);
table(folder, "nations", base->rows("nations"));
table(folder, "competitions", base->rows("competitions"));
auto clubs = base->rows("clubs"), players = base->rows("players");
clubs.push_back({{"id", "club:finance-next"}, {"name", "Synthetic next club"},
{"nation", "nation:de"}, {"competition", "comp:home"}});
players.push_back({{"id", "player:finance-next"}, {"name", "Synthetic next player"},
{"team", "club:finance-next"}, {"positions", {"gk"}}, {"squad_order", 0}});
table(folder, "clubs", clubs);
table(folder, "players", players);
table(folder, "contracts", Json::array({
{{"id", "contract:finance-real"}, {"person", "player:a"}, {"team", "club:a"},
{"salary", 12000000}},
{{"id", "contract:finance-initialization"}, {"person", "player:b"}, {"team", "club:a"},
{"initialization", {{"kind", "synthetic-demo"}}}},
{{"id", "contract:finance-next"}, {"person", "player:finance-next"}, {"team", "club:finance-next"},
{"salary", 24000000}}}));
const auto immutable_players = bmh::editor::read_file(folder / "world/players.json");
const auto immutable_contracts = bmh::editor::read_file(folder / "world/contracts.json");
auto world = Catalog::open(folder);
DemoSource source(world);
const auto start = source.snapshot();
const auto factor = finance_currency_factor(*world);
require(factor == 100 && start.state["contracts"]["club"] == "club:a",
"Synthetic cent-currency source did not select its first manager");
const auto act = [&](const Json &value) {
return source.apply({source.snapshot().revision, "finance", value});
};
const auto deposit = act({{"kind", "deposit"}, {"value", 400}});
const auto deposited = source.snapshot();
require(deposit.ok && deposit.revision == start.revision + 1 &&
deposited.revision == deposit.revision && source.dirty() &&
deposited.state["cash"] == start.state["cash"].get<int64_t>() - 400 * factor &&
deposited.state["deposit"] == start.state["deposit"].get<int64_t>() + 400 * factor,
"Finance source action lost whole-to-minor conversion or revision/dirty state");
const auto bank = demo_bank_summary(deposited.state, *world);
const auto balance = demo_balance_rows(deposited.state, *world);
require(bank.value("ok", false) && balance.value("ok", false) &&
bank["cash"] == deposited.state["cash"] && balance["cash"] == bank["cash"] &&
bank["deposit"] == deposited.state["deposit"] &&
source.snapshot().state == deposited.state && source.snapshot().revision == deposited.revision,
"Bank/balance projections diverged from the shared wallet or mutated their source");
const auto stale = source.apply({start.revision, "finance", {{"kind", "withdraw"}, {"value", 1}}});
require(!stale.ok && stale.error == "stale_revision" &&
source.snapshot().state == deposited.state && source.snapshot().revision == deposited.revision,
"Stale finance source action mutated the wallet or advanced its revision");
require(act({{"kind", "contract-offer"}, {"player", "player:a"}, {"salary", 1234}, {"months", 36}}).ok &&
act({{"kind", "insurance"}, {"player", "player:a"}, {"value", 24}}).ok &&
act({{"kind", "bonus"}, {"index", 6}, {"value", 255}}).ok &&
act({{"kind", "plan"}, {"index", 0}, {"value", 1000}}).ok,
"Contracts, insurance, bonuses or balance planning failed through the shared source");
const auto edited = source.snapshot();
require(edited.state["contracts"]["players"]["player:a"]["salary"] == 1234 * factor &&
edited.state["contracts"]["players"]["player:a"]["months"] == 36 &&
edited.state["contracts"]["players"]["player:a"]["insurance"] == 24 &&
edited.state["contracts"]["bonuses"][6] == 255 &&
edited.state["balance"]["plan"][0] == 1000 * factor &&
edited.state["cash"] == deposited.state["cash"] &&
edited.state["deposit"] == deposited.state["deposit"] && edited.state["debt"] == deposited.state["debt"],
"Contract/plan edits double-converted money or booked unrelated wallet movements");
const auto file = folder / "finance.ui.json";
const auto layout = default_desktop();
source.save(file, layout);
require(!source.dirty(), "Saved finance source remained dirty");
require(act({{"kind", "withdraw"}, {"value", 1}}).ok, "Post-save finance edit failed");
const auto before_restore = source.snapshot().revision;
require(source.load(file) == layout && source.snapshot().state == edited.state &&
source.snapshot().revision == before_restore + 1 && !source.dirty(),
"Finance checkpoint lost wallet/contracts/plans or failed revision and clean-state restoration");
auto legacy = Json::parse(bmh::editor::read_file(file));
for (const auto *key : {"finance", "balance", "contracts"}) legacy.erase(key);
write(folder, "legacy-finance.ui.json", legacy);
DemoSource migrated(world);
migrated.load(folder / "legacy-finance.ui.json");
const auto upgraded = migrated.snapshot();
require(valid_demo_finance(upgraded.state, *world, "club:a") && !migrated.dirty() &&
upgraded.state["contracts"] == demo_contracts(*world, "club:a") &&
upgraded.state["managers"] == edited.state["managers"],
"Legacy finance checkpoint did not initialize a complete manager-scoped preview");
for (const auto *key : {"cash", "deposit", "debt", "ticket"})
require(upgraded.state.at(key) == edited.state.at(key),
"Legacy finance migration overwrote an existing wallet/ticket value");
auto corrupt = Json::parse(bmh::editor::read_file(file));
corrupt["contracts"]["players"]["player:a"]["salary"] = -1;
write(folder, "invalid-finance.ui.json", corrupt);
const auto accepted = source.snapshot();
bool rejected = false;
try { source.load(folder / "invalid-finance.ui.json"); }
catch (const std::exception &) { rejected = true; }
require(rejected && source.snapshot().state == accepted.state &&
source.snapshot().revision == accepted.revision && !source.dirty(),
"Malformed existing finance fields were repaired or partially loaded");
const auto change = source.apply({accepted.revision, "managers", Json::array({
{{"name", "Synthetic next manager"}, {"club", "club:finance-next"}, {"portrait", 1}}})});
const auto changed = source.snapshot();
require(change.ok && changed.revision == accepted.revision + 1 &&
changed.state["contracts"] == demo_contracts(*world, "club:finance-next") &&
changed.state["lineup"] == demo_lineup(*world, "club:finance-next") &&
changed.state["transfer"] == demo_transfer(*world, "club:finance-next") &&
changed.state["stadium"] == demo_stadium(*world, "club:finance-next") &&
changed.state["contracts"]["players"].contains("player:finance-next") &&
!changed.state["contracts"]["players"].contains("player:a") &&
changed.state["cash"] == accepted.state["cash"] &&
changed.state["deposit"] == accepted.state["deposit"] &&
changed.state["debt"] == accepted.state["debt"] &&
changed.state["finance"] == accepted.state["finance"] &&
changed.state["balance"] == accepted.state["balance"],
"First-manager club change retained another club's contracts or reset the shared finances");
require(!source.apply({accepted.revision, "finance", {{"kind", "insurance"},
{"player", "player:a"}, {"value", 12}}}).ok &&
!source.apply({changed.revision, "finance", {{"kind", "contract-offer"},
{"player", "player:a"}, {"salary", 2000}, {"months", 24}}}).ok &&
source.snapshot().state == changed.state && source.snapshot().revision == changed.revision,
"Old-club contract targets were silently retargeted after a manager switch");
require(act({{"kind", "bonus"}, {"index", 0}, {"value", 17}}).ok,
"New club bonus edit failed");
const auto before_rename = source.snapshot();
require(source.apply({before_rename.revision, "managers", Json::array({
{{"name", "Renamed manager"}, {"club", "club:finance-next"}, {"portrait", 1}}})}).ok &&
source.snapshot().state["contracts"] == before_rename.state["contracts"],
"Renaming a manager in the same club reset its contracts/bonuses");
require(bmh::editor::read_file(folder / "world/players.json") == immutable_players &&
bmh::editor::read_file(folder / "world/contracts.json") == immutable_contracts,
"Finance source edits modified immutable catalogue players or contracts");
}
} // namespace
int main(int argc, char **argv) try {
check_crest_contrast();
if (argc == 2) {
auto catalog = Catalog::open(bmh::editor::path(argv[1]));
const auto before = catalog->summary();
DemoSource demo(catalog);
require(!demo.apply({0, "kickoff", {}}).ok,
"Demo must never expose kickoff");
require(demo.snapshot().revision == 0, "Rejected action changed revision");
require(catalog->summary() == before, "UI modified its world");
std::cout << before.dump(2) << '\n';
return 0;
}
const auto root =
fs::temp_directory_path() /
("openbmh-modern-ui-" +
std::to_string(
std::chrono::steady_clock::now().time_since_epoch().count()));
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{root};
fs::create_directories(root);
write(root, "manifest.json",
{{"format", "openbmh-world"},
{"kind", "world"},
{"format_version", "1.1"},
{"id", "world:synthetic-ui"},
{"title", {{"default", "Synthetic UI world"}}},
{"requires", {"editor:world-v1"}},
{"x-editor", {{"profile", "editor-world-v1"}, {"playable", false}}}});
table(root, "nations",
Json::array({{{"id", "nation:de"}, {"name", "Testland"}},
{{"id", "nation:other"}, {"name", "Otherland"}}}));
table(root, "competitions",
Json::array({{{"id", "comp:home"},
{"name", "Home league"},
{"type", "league"},
{"nation", "nation:de"}},
{{"id", "comp:other"},
{"name", "Other league"},
{"type", "league"},
{"nation", "nation:other"}}}));
table(root, "clubs",
Json::array({{{"id", "club:a"},
{"name", "Test A"},
{"nation", "nation:de"},
{"competition", "comp:home"}},
{{"id", "club:b"},
{"name", "Test B"},
{"nation", "nation:other"},
{"competition", "comp:other"}}}));
table(root, "players",
Json::array({{{"id", "player:a"},
{"name", {{"first", "Alex"}, {"last", "Example"}}},
{"team", "club:a"},
{"squad_order", 1}},
{{"id", "player:b"},
{"name", {{"first", "Robin"}, {"last", "Sample"}}},
{"team", "club:a"},
{"squad_order", 0}}}));
bmh::editor::write_atomic(root / "small.txt", "low resolution");
bmh::editor::write_atomic(root / "vector.svg", "vector artwork");
table(root, "assets",
Json::array(
{{{"key", "asset:club/a/crest"},
{"files", {{"native", "small.txt"}, {"svg", "vector.svg"}}}}}));
const auto original = bmh::editor::read_file(root / "manifest.json");
auto world = Catalog::open(root);
require(world->manageable("club:a") && !world->manageable("club:b"),
"Foreign management policy");
require(world->clubs("comp:other").size() == 1,
"Foreign clubs must remain visible");
require(world->squad("club:a").front()->at("id") == "player:b",
"Squad order must come from OBW");
require(world->name(world->rows("players")[0]) == "Alex Example",
"Split names were not presented");
require(world->asset("asset:club/a/crest").first == "vector artwork",
"Low-resolution native image overrides SVG");
require(number(-1234567) == "-1.234.567", "Integer presentation");
require(money(-1, {{"minor_units", 2}, {"code", "EUR"}}) == "-0,01 €",
"Minor currency units");
DemoSource source(world);
const auto before = source.snapshot();
const auto archive_index = source.read_almanac({{"kind", "index"}});
require(archive_index.value("ok", false) &&
source.snapshot().revision == before.revision &&
source.snapshot().state == before.state && !source.dirty(),
"Almanac read mutated presentation state or revision");
require(!source.read_almanac({{"kind", "invalid"}}).value("ok", true) &&
source.snapshot().state == before.state && !source.dirty(),
"Rejected almanac query mutated state");
require(!source
.apply({0, "managers",
Json::array({{{"name", "Pat"}, {"club", "club:b"}}})})
.ok,
"Foreign club was selectable");
require(source.snapshot().state == before.state &&
source.snapshot().revision == 0,
"Rejected action mutated state");
require(source.apply({0, "ticket", 17}).ok && source.dirty(),
"Accepted draft action");
require(!source.apply({0, "ticket", 18}).ok &&
source.snapshot().state["ticket"] == 17,
"Stale revision mutated state");
require(!source.apply({1, "kickoff", {}}).ok, "Kickoff became available");
require(!source.apply({1, "ticket", 26}).ok,
"Invalid demo ticket was accepted");
const auto save = root / "demo.ui.json";
auto layout = default_desktop();
require(valid_desktop(layout), "Default desktop must validate");
auto old_layout = layout;
old_layout["objects"].erase("app-almanac");
const auto preserved_layout = old_layout;
require(migrate_desktop(old_layout) && valid_desktop(old_layout) &&
old_layout["objects"]["app-almanac"]["visible"] == true,
"Older desktop did not gain its Almanac icon");
auto without_added_icon = old_layout;
without_added_icon["objects"].erase("app-almanac");
require(without_added_icon == preserved_layout,
"Almanac migration moved or reset existing desktop objects");
auto bad_old_layout = preserved_layout;
bad_old_layout["objects"]["calendar"]["x"] = -1;
const auto before_bad_migration = bad_old_layout;
require(!migrate_desktop(bad_old_layout) && bad_old_layout == before_bad_migration,
"Desktop migration partially repaired invalid existing data");
auto moved = layout;
require(!place_desktop_object(moved, "account", 3000, 1500) &&
moved == layout,
"Pinned widget moved");
moved["objects"]["account"]["pinned"] = false;
require(resize_desktop_widget(moved, "account", 4, 1),
"Approved 4x1 account size failed");
require(valid_desktop(moved), "Resize produced invalid desktop");
const auto resized = moved;
require(!resize_desktop_widget(moved, "account", 3, 7) && moved == resized,
"Invalid widget size mutated layout");
// a taller screen shows more of the desk; a shorter one brings what lies below back into sight
{
auto tall = layout;
tall["objects"]["app-almanac"]["pinned"] = false;
set_desktop_height(2400);
require(place_desktop_object(tall, "app-almanac", 1800, 2150) && valid_desktop(tall) &&
tall["objects"]["app-almanac"]["y"].get<int>() + 224 > 2160 &&
tall["objects"]["app-almanac"]["y"].get<int>() + 224 <= 2400,
"Taller desk did not offer its lower rows");
auto unchanged = tall;
require(!fit_desktop(unchanged) && unchanged == tall, "Fit moved an object that is in sight");
set_desktop_height(2160);
require(valid_desktop(tall), "Layout of a taller screen is invalid on a shorter one");
require(fit_desktop(tall) && valid_desktop(tall) && tall["objects"]["app-almanac"]["y"].get<int>() + 224 <= 2160,
"Object below the shown desk was not brought back into sight");
}
// the stadium's card model: drawn from the overview alone, the same picture for the same input
{
Json overview = {{"blocks", Json::array()}, {"facilities", Json::array()}, {"periphery", Json::array()}};
for (int i = 0; i < 8; ++i)
overview["blocks"].push_back({{"letter", std::string(1, char('A' + i))}, {"display_places", 3000 + 1000 * i}, {"max_places", 18000},
{"display_seats", i % 2 == 0}, {"display_roof", i == 3}, {"building", i == 5}, {"job", {{"places", 9000}, {"weeks", 12}}}});
for (int i = 0; i < 8; ++i) overview["facilities"].push_back({{"name", "Anlage"}, {"display_level", 2}, {"building", false}});
for (int i = 0; i < 14; ++i) overview["periphery"].push_back({{"name", "Haus"}, {"level", i % 3}, {"max_level", 3}, {"building", false}});
const auto scene = stadium3d::build(overview, "#aa2233", true);
require(scene.centres.contains("block:7") && scene.centres.contains("facility:0") && !scene.centres.contains("periphery:0"),
"The stadium's view should offer stands and facilities only");
const auto inside = stadium3d::fixed_camera(false);
const auto whole = stadium3d::draw(scene, inside, 2612, 1600);
const auto again = stadium3d::draw(stadium3d::build(overview, "#aa2233", true), inside, 2612, 1600);
require(whole.svg == again.svg && whole.svg.size() > 4000, "Stadium model is not drawn the same way twice");
require(std::count_if(whole.anchors.begin(), whole.anchors.end(), [](const auto &a) { return a.id == "facility:0"; }) == 4,
"Each floodlight mast should choose the floodlights");
for (const auto &part : whole.parts)
if (part.id.starts_with("block:"))
require(part.cx > 100 && part.cx < 2512 && part.cy > 100 && part.cy < 1500, "A stand lies outside the fixed camera's picture");
// the surroundings: every object is a part of its own, and every level draws more
const auto around = stadium3d::build(overview, "#aa2233", true, 1);
require(around.centres.size() == 14 && around.centres.contains("periphery:13") && !around.centres.contains("block:0"),
"The surroundings should offer their fourteen objects only");
auto grown = overview;
grown["periphery"][0]["level"] = 4;
grown["periphery"][4]["level"] = 3;
require(stadium3d::build(grown, "#aa2233", true, 1).faces.size() > around.faces.size() + 20,
"Higher levels of road and parking should show more");
const auto outside = stadium3d::draw(around, stadium3d::fixed_camera(true), 2612, 1600);
for (const auto &anchor : outside.anchors)
require(anchor.x > 40 && anchor.x < 2572 && anchor.y > 40 && anchor.y < 1560, "An object of the surroundings lies outside the picture");
}
auto corrupt = layout;
corrupt["objects"]["calendar"]["x"] = 999999;
require(!valid_desktop(corrupt), "Out of bounds desktop accepted");
source.save(save, layout);
require(!source.dirty(), "Saved demo remains dirty");
auto old_icon_save = Json::parse(bmh::editor::read_file(save));
old_icon_save["desktop"]["objects"].erase("app-almanac");
write(root, "old-icon.ui.json", old_icon_save);
DemoSource old_icon_source(world);
const auto migrated_icon_layout = old_icon_source.load(root / "old-icon.ui.json");
require(valid_desktop(migrated_icon_layout) &&
migrated_icon_layout["objects"].contains("app-almanac") &&
!old_icon_source.dirty(),
"Older UI checkpoint rejected its missing Almanac desktop icon");
require(source.apply({1, "ticket", 21}).ok, "Second action");
const auto desktop = source.load(save);
require(source.snapshot().state["ticket"] == 17 && desktop == layout,
"Demo restoration");
require(bmh::editor::read_file(root / "manifest.json") == original,
"Demo altered the OBW source");
auto bad = Json::parse(bmh::editor::read_file(save));
bad["world"] = "world:different";
write(root, "bad.ui.json", bad);
const auto accepted = source.snapshot();
bool rejected = false;
try {
source.load(root / "bad.ui.json");
} catch (const std::exception &) {
rejected = true;
}
require(rejected && source.snapshot().state == accepted.state &&
source.snapshot().revision == accepted.revision,
"Failed load changed the session");
bad = Json::parse(bmh::editor::read_file(save));
bad["desktop"] = corrupt;
write(root, "bad-layout.ui.json", bad);
rejected = false;
try {
source.load(root / "bad-layout.ui.json");
} catch (const std::exception &) {
rejected = true;
}
require(rejected && source.snapshot().state == accepted.state &&
source.snapshot().revision == accepted.revision,
"Invalid desktop partially restored demo");
DemoSource sports(world);
const auto initial_sports = sports.snapshot();
require(!sports
.apply({0,
"training",
{{"kind", "ball"},
{"group", "type"},
{"index", 0},
{"value", 3}}})
.ok,
"Training preview budget exceeded");
require(sports.snapshot().state == initial_sports.state &&
sports.snapshot().revision == 0,
"Rejected training mutated demo");
require(!sports
.apply({0,
"training",
{{"kind", "ball"},
{"group", "area"},
{"index", 0},
{"value", 1.5}}})
.ok,
"Fractional training value accepted");
const auto player = world->squad("club:a").front()->value("id", "");
require(sports
.apply({0,
"training",
{{"kind", "ball"},
{"group", "player"},
{"player", player},
{"value", 1}}})
.ok,
"Player intensity action failed");
require(sports.snapshot().state["training"]["players"][player]["intensity"] ==
0,
"Selected intensity must toggle to zero in UI demo");
require(sports
.apply({1,
"training",
{{"kind", "focus"}, {"player", player}, {"value", 7}}})
.ok,
"Direct focus selection failed");
for (int i = 0; i < 4; ++i)
require(sports
.apply({sports.snapshot().revision,
"tactics",
{{"kind", "cycle"}, {"index", 0}}})
.ok,
"Tactic cycle failed");
require(sports.snapshot().state["tactics"]["values"][0] ==
initial_sports.state["tactics"]["values"][0],
"Tactic cycle did not wrap");
require(
sports
.apply(
{sports.snapshot().revision, "training", {{"kind", "auto-all"}}})
.ok,
"Global automatic training failed");
const auto automated = sports.snapshot();
require(automated.state["training"]["players"][player]["intensity"] == 2 &&
automated.state["training"]["players"][player]["focus"] == 7,
"Automatic training must preserve focuses");
require(!sports.apply({automated.revision,
"training",
{{"kind", "focus"}, {"player", player}, {"value", 0}}})
.ok &&
sports.snapshot().state == automated.state,
"Automatic player controls accepted manual changes");
sports.save(root / "sports.ui.json", default_desktop());
DemoSource restored_sports(world);
restored_sports.load(root / "sports.ui.json");
require(restored_sports.snapshot().state == sports.snapshot().state,
"Training/tactics were lost on restoration");
auto legacy = Json::parse(bmh::editor::read_file(root / "sports.ui.json"));
// A checkpoint predating training also predates the aggregate settings block.
legacy.erase("settings");
legacy.erase("training");
legacy.erase("tactics");
legacy.erase("calendar");
write(root, "legacy-ui.json", legacy);
restored_sports.load(root / "legacy-ui.json");
require(valid_demo_training(restored_sports.snapshot().state["training"],
*world, "club:a"),
"Older UI checkpoint did not migrate safely");
require(valid_demo_calendar(restored_sports.snapshot().state["calendar"],
*world),
"Older UI checkpoint lost its season calendar");
for (const auto *theme : {"midnight", "silver", "matchday"}) {
const auto diagram = bmh::editor::images::decode(
tactics_diagram(demo_tactics(), theme), ".svg", 256);
require(diagram.width == 256 && diagram.height > 0,
"Tactic SVG failed to decode");
}
const Json formation_points = {{0,4},{5,1},{5,3},{5,5},{5,7},{10,1},{10,3},{10,5},{10,7},{16,3},{16,5}};
auto moved_points = formation_points;
moved_points[1] = {6,1};
require(tactics_diagram(demo_tactics(), "midnight", formation_points) !=
tactics_diagram(demo_tactics(), "midnight", moved_points),
"Tactic projection ignored the current lineup positions");
auto invalid_points = formation_points;
invalid_points[1] = invalid_points[0];
bool duplicate_rejected = false;
try { tactics_diagram(demo_tactics(), "midnight", invalid_points); }
catch (const bmh::editor::Error &) { duplicate_rejected = true; }
require(duplicate_rejected, "Tactic projection silently accepted duplicate lineup positions");
const auto leap_days = calendar_days("2027-07-01");
require(leap_days.size() == 366 && leap_days.front().weekday == 3 &&
leap_days.back().iso == "2028-06-30" &&
std::count_if(leap_days.begin(), leap_days.end(), [](const auto &d) {
return d.iso == "2028-02-29";
}) == 1,
"Season dates lost weekday alignment or leap day");
require(calendar_days("2026-07-01").size() == 365 &&
calendar_days("2099-07-01").size() == 365 &&
calendar_days("0000-07-01").empty() &&
calendar_days("2027-06-01").empty(),
"Season date validation or Gregorian century handling failed");
auto calendar_clubs = world->rows("clubs");
for (int i = 1; i < 20; ++i) {
if (i < 18)
calendar_clubs.push_back({{"id", "club:home" + std::to_string(i)},
{"name", "Home " + std::to_string(i)},
{"nation", "nation:de"},
{"competition", "comp:home"}});
calendar_clubs.push_back({{"id", "club:other" + std::to_string(i)},
{"name", "Other " + std::to_string(i)},
{"nation", "nation:other"},
{"competition", "comp:other"}});
}
table(root, "clubs", calendar_clubs);
auto calendar_world = Catalog::open(root);
DemoSource calendar_source(calendar_world);
auto calendar = calendar_source.snapshot().state.at("calendar");
const auto fixtures = calendar_fixtures(calendar, *calendar_world, "club:a");
require(fixtures.size() == 34, "Eighteen-team season needs 34 preview rounds");
std::map<std::string, int> opponents;
std::set<int> occupied;
for (const auto &fixture : fixtures) {
require(fixture.home == "club:a" || fixture.away == "club:a",
"Calendar fixture belongs to another career club");
require(fixture.home != fixture.away && occupied.insert(fixture.day).second,
"Preview generated self match or duplicate date");
++opponents[fixture.home == "club:a" ? fixture.away : fixture.home];
}
require(opponents.size() == 17 &&
std::all_of(opponents.begin(), opponents.end(), [](const auto &p) {
return p.second == 2;
}),
"Preview must show two meetings per opponent");
const auto original_calendar = calendar_source.snapshot();
require(!calendar_source.apply({0, "calendar", {{"kind", "select"}, {"value", -1}}}).ok &&
!calendar_source.apply({0, "calendar", {{"kind", "select"}, {"value", 365}}}).ok &&
!calendar_source.apply({0, "calendar", {{"kind", "select"}, {"value", 1.5}}}).ok &&
calendar_source.snapshot().state == original_calendar.state &&
calendar_source.snapshot().revision == 0,
"Invalid calendar selection mutated the demo");
require(calendar_source.apply({0, "calendar", {{"kind", "select"}, {"value", 30}}}).ok &&
calendar_source.apply({1, "calendar", {{"kind", "league"}, {"value", "comp:other"}}}).ok,
"Calendar day or foreign preview league selection failed");
calendar = calendar_source.snapshot().state.at("calendar");
require(calendar_fixtures(calendar, *calendar_world, "club:a").size() == 38 &&
calendar["selected"] == 30 &&
calendar_source.snapshot().state["managers"] == original_calendar.state["managers"],
"Foreign calendar preview changed selection or career identity");
calendar_source.save(root / "calendar.ui.json", default_desktop());
DemoSource restored_calendar(calendar_world);
restored_calendar.load(root / "calendar.ui.json");
require(restored_calendar.snapshot().state["calendar"] == calendar,
"Calendar selection was lost on process restoration");
require(restored_calendar.snapshot().state["reports"]["league"] == "comp:other",
"Calendar and report league selection diverged");
require(restored_calendar.apply({restored_calendar.snapshot().revision, "reports",
{{"kind", "league"}, {"value", "comp:home"}}}).ok &&
restored_calendar.snapshot().state["calendar"]["league"] == "comp:home" &&
restored_calendar.snapshot().state["calendar"]["selected"] == 30,
"Report selection failed to sync without losing the calendar day");
require(restored_calendar.apply({restored_calendar.snapshot().revision, "opening", "complete"}).ok &&
restored_calendar.snapshot().state["opening_created"] == true,
"Completed opening lost its cup preview marker");
restored_calendar.save(root / "reports.ui.json", default_desktop());
DemoSource restored_reports(calendar_world);
restored_reports.load(root / "reports.ui.json");
require(restored_reports.snapshot().state == restored_calendar.snapshot().state,
"Report state or completed opening failed to round-trip");
auto old_reports = Json::parse(bmh::editor::read_file(root / "calendar.ui.json"));
old_reports.erase("reports");
old_reports.erase("opening_created");
write(root, "old-reports.ui.json", old_reports);
restored_reports.load(root / "old-reports.ui.json");
require(valid_demo_reports(restored_reports.snapshot().state["reports"], *calendar_world) &&
restored_reports.snapshot().state["reports"]["league"] == "comp:other" &&
restored_reports.snapshot().state["opening_created"] == false,
"Old checkpoint migration lost the selected league or invented a draw");
const auto accepted_reports = restored_reports.snapshot();
auto bad_reports = Json::parse(bmh::editor::read_file(root / "reports.ui.json"));
bad_reports["reports"]["round"] = -1;
write(root, "bad-reports.ui.json", bad_reports);
rejected = false;
try {
restored_reports.load(root / "bad-reports.ui.json");
} catch (const std::exception &) {
rejected = true;
}
require(rejected && restored_reports.snapshot().state == accepted_reports.state &&
restored_reports.snapshot().revision == accepted_reports.revision &&
!restored_reports.apply({accepted_reports.revision, "reports",
{{"kind", "league"}, {"value", "missing"}}}).ok &&
restored_reports.snapshot().state == accepted_reports.state,
"Rejected report load/action partially mutated the session");
const auto planning_before = restored_reports.snapshot();
const auto plan_action = [&](const Json &change) {
return restored_reports.apply({restored_reports.snapshot().revision, "calendar", change}).ok;
};
require(plan_action({{"kind", "friendly-league"}, {"value", "comp:other"}}) &&
plan_action({{"kind", "friendly-opponent"}, {"value", "club:b"}}) &&
plan_action({{"kind", "friendly-venue"}, {"value", true}}) &&
plan_action({{"kind", "friendly-stage"}, {"value", 1}}) &&
plan_action({{"kind", "select"}, {"value", 7}}) &&
plan_action({{"kind", "friendly-book"}}),
"Planning through the shared source failed");
require(restored_reports.snapshot().state["cash"] == planning_before.state["cash"] &&
restored_reports.snapshot().state["managers"] == planning_before.state["managers"] &&
restored_reports.snapshot().state["training"] == planning_before.state["training"],
"Presentation planning mutated finances, managers or training");
require(plan_action({{"kind", "select"}, {"value", 30}}) &&
plan_action({{"kind", "postpone-source"}}) &&
plan_action({{"kind", "select"}, {"value", 8}}) &&
plan_action({{"kind", "postpone-move"}}),
"Rescheduling used the foreign preview instead of the manager schedule");
restored_reports.save(root / "planning.ui.json", default_desktop());
DemoSource restored_planning(calendar_world);
restored_planning.load(root / "planning.ui.json");
require(restored_planning.snapshot().state == restored_reports.snapshot().state,
"Bookings or moves were lost on source round-trip");
const auto planning_accepted = restored_planning.snapshot();
auto colliding_plan = Json::parse(bmh::editor::read_file(root / "planning.ui.json"));
colliding_plan["calendar"]["friendlies"][0]["day"] = 8;
write(root, "colliding-plan.ui.json", colliding_plan);
rejected = false;
try { restored_planning.load(root / "colliding-plan.ui.json"); }
catch (const std::exception &) { rejected = true; }
require(rejected && restored_planning.snapshot().state == planning_accepted.state &&
restored_planning.snapshot().revision == planning_accepted.revision,
"Conflicting plan partially loaded");
auto old_planning = Json::parse(bmh::editor::read_file(root / "calendar.ui.json"));
for (const auto *key : {"source_day", "friendly_league", "opponent", "home", "friendly_stage"})
old_planning["calendar"].erase(key);
old_planning["reports"]["sorts"].erase("indoor");
write(root, "old-planning.ui.json", old_planning);
restored_planning.load(root / "old-planning.ui.json");
require(restored_planning.snapshot().state["calendar"]["league"] == "comp:other" &&
restored_planning.snapshot().state["calendar"]["friendly_league"] == "comp:home" &&
restored_planning.snapshot().state["reports"]["sorts"]["indoor"]["key"] == "points",
"Old checkpoint lost league preview or failed planning/indoor migration");
check_finance_source(root, world);
check_club_views(root, world);
check_squad_source(root, world);
check_stadium_source(root, world);
GuiAssets absent(root / "missing-gui");
require(!absent.available(),
"World resources were mistaken for GUI resources");
std::cout << "Modern UI catalogue, asset priority, ownership, revision and "
"demo-save checks passed\n";
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}