Compare commits

...
Author SHA1 Message Date
Codex 9f1928bd9e Add read-only game and league regulations to editor 0.5.2 (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 06:28:12 +02:00
Codex 221478b629 Add sortable editor ratings and payroll comparisons (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 05:26:10 +02:00
39 changed files with 2282 additions and 43 deletions

No files matched your search

+2 -2
View File
@@ -49,9 +49,9 @@ jobs:
if [[ "$RUNNER_OS" == "macOS" ]]; then args+=(-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0); fi
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON -DBMH_DATA= "${args[@]}"
- name: Build editor and synthetic tests
run: cmake --build build --target openbmh_editor editor_core_tests --parallel 2
run: cmake --build build --target openbmh_editor editor_core_tests editor_comparison_tests editor_regulations_tests --parallel 2
- name: Native editor core and MCP tests
run: ctest --test-dir build -C Release -R "^editor_(core_tests|version)$" --output-on-failure --output-junit editor-tests.xml
run: ctest --test-dir build -C Release -R "^editor_(core_tests|comparison_tests|regulations_tests|version)$" --output-on-failure --output-junit editor-tests.xml
- name: Linux native GUI smoke
if: runner.os == 'Linux'
run: |
+2 -2
View File
@@ -1,8 +1,8 @@
# OpenBMH
The separate [OpenBMH Editor 0.5.0](docs/EDITOR.md) uses native RmlUI,
The separate [OpenBMH Editor 0.5.2](docs/EDITOR.md) uses native RmlUI,
supports German/English, three themes, image editing and a local MCP server.
Download its own `editor-v0.5.0` release or build with
Download its own `editor-v0.5.2` release or build with
`-DOPENBMH_BUILD_EDITOR=ON`. Edited worlds are independent of the Classic runtime.
A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* engine.
+42 -1
View File
@@ -142,7 +142,7 @@ button.quiet:hover { background-color: var(--hover); }
aside { width: 220dp; flex-shrink: 0; padding: 28dp 14dp 18dp; display: flex; flex-direction: column; background-color: var(--sidebar); border-right: 1dp var(--divider); }
.eyebrow { font-size: 11dp; font-weight: bold; letter-spacing: 1.5dp; color: var(--muted); text-transform: uppercase; }
#nav-label { padding: 0 14dp 18dp; }
#navigation { display: flex; flex-direction: column; gap: 5dp; }
#navigation { display: flex; flex-direction: column; gap: 5dp; min-height: 0; overflow-y: auto; }
.nav { width: 100%; display: flex; align-items: center; padding: 11dp 13dp; text-align: left; border-color: transparent; background-color: transparent; decorator: none; font-size: 15dp; }
.nav .glyph { width: 20dp; height: 20dp; margin-right: 16dp; flex-shrink: 0; }
.nav.selected { background-color: var(--selected); color: var(--accent); border-color: var(--accent-border); }
@@ -178,6 +178,29 @@ select option:hover, select option:checked { background-color: var(--selected);
.table-header button:hover { color: var(--text); }
.table-header button:first-child { flex: 2; }
.table-scroll { flex: 1; overflow-y: auto; }
.comparison-layout { flex: 1; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.comparison-bar { display: flex; align-items: center; gap: 12dp; margin-bottom: 14dp; flex-shrink: 0; }
.comparison-bar label, .comparison-bar span { color: var(--muted); font-size: 12dp; }
.comparison-bar span { margin-left: auto; }
#comparison-set { width: 310dp; }
.comparison-panel { min-height: 0; }
.comparison-x { flex: 1; min-height: 0; overflow-x: auto; overflow-y: hidden; display: flex; }
.comparison-table { flex-shrink: 0; display: flex; flex-direction: column; min-height: 0; }
.comparison-head { display: flex; flex-shrink: 0; align-items: stretch; background-color: var(--wash); border-bottom: 1dp var(--border); padding-right: 20dp; }
.comparison-head button { border: 0; border-radius: 0; decorator: none; background-color: transparent; color: var(--muted); font-size: 13dp; padding: 12dp 10dp; white-space: normal; }
.comparison-head button:disabled { opacity: 1; cursor: default; }
.comparison-head small { font-size: 11dp; }
.comparison-direction { width: 7dp; height: 7dp; border-bottom: 1.5dp var(--accent); border-right: 1.5dp var(--accent); transform: rotate(45deg); margin-left: 8dp; margin-bottom: 3dp; }
.comparison-direction.ascending { transform: rotate(225deg); margin-bottom: 0; }
.comparison-body { flex: 1; min-height: 0; overflow-y: auto; }
.comparison-row { display: flex; align-items: center; border: 0; border-bottom: 1dp var(--divider); border-radius: 0; decorator: none; background-color: transparent; padding: 0; min-height: 47dp; text-align: left; }
.comparison-cell { flex-shrink: 0; padding: 14dp 10dp; text-align: right; font-size: 14dp; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.comparison-cell.text { text-align: left; }
.comparison-name-text { display: block; overflow: hidden; text-overflow: ellipsis; }
.comparison-note { flex-shrink: 0; margin-top: 12dp; font-size: 12dp; line-height: 1.6; color: var(--muted); }
.comparison-choices { display: flex; flex-wrap: wrap; max-height: 430dp; overflow-y: auto; margin-top: 16dp; gap: 6dp; }
.comparison-choices label { width: 31%; display: flex; align-items: center; padding: 10dp 4dp; font-size: 14dp; }
.comparison-choices input { flex-shrink: 0; margin-right: 10dp; border-radius: 4dp; }
.record { display: flex; align-items: center; width: 100%; min-height: 49dp; padding: 9dp 16dp; border: 0; border-bottom: 1dp var(--divider); border-radius: 0; background-color: transparent; decorator: none; text-align: left; }
.record:hover { background-color: var(--hover); }
.record.selected { background-color: var(--selected); border-left: 3dp var(--accent); padding-left: 13dp; }
@@ -214,6 +237,19 @@ footer { height: 57dp; padding: 0 28dp; display: flex; align-items: center; gap:
.metric span { display: block; font-size: 28dp; font-weight: bold; color: var(--text); margin-top: 9dp; }
.note { margin-top: 22dp; padding: 18dp 20dp; background-color: var(--note); border: 1dp var(--accent-border); border-radius: 10dp; color: var(--positive); font-size: 13dp; line-height: 1.6; }
.source-json { font-size: 11dp; line-height: 1.5; white-space: pre-wrap; color: var(--muted); margin: 14dp 0; }
.regulation-layout { flex: 1; display: flex; gap: 20dp; min-width: 0; min-height: 0; }
.regulation-list { width: 270dp; flex: none; }
.regulation-choice { display: block; width: 100%; text-align: left; white-space: normal; padding: 15dp 18dp; border-radius: 0; border: 0; border-bottom: 1dp var(--divider); }
.regulation-choice small { font-size: 11dp; }
.regulation-detail { min-width: 0; }
.regulation-scroll { flex: 1; overflow-y: auto; padding: 25dp; }
.regulation-scroll p { margin-top: 12dp; font-size: 15dp; line-height: 1.55; }
.regulation-scroll h2 { line-height: 1.4; }
.regulation-section { margin: 27dp 0; padding-top: 22dp; border-top: 1dp var(--divider); }
.regulation-section h2 { font-size: 18dp; margin-bottom: 13dp; }
.regulation-clause { padding: 15dp 18dp; border: 1dp var(--border); border-radius: 10dp; background-color: var(--wash); margin-bottom: 12dp; }
.regulation-clause p { margin-top: 8dp; }
.regulation-scroll .source-json { font-size: 13dp; line-height: 1.55; }
.history-row, .diagnostic { padding: 15dp 20dp; border-bottom: 1dp var(--divider); line-height: 1.6; }
.diagnostic.error { color: var(--danger); }
.diagnostic.warning { color: var(--warning); }
@@ -240,5 +276,10 @@ scrollbarvertical slidertrack { background-color: transparent; }
scrollbarvertical sliderbar { background-color: var(--scrollbar); border-radius: 4dp; min-height: 30dp; }
scrollbarvertical sliderbar:hover { background-color: var(--scrollbar-hover); }
scrollbarvertical sliderarrowdec, scrollbarvertical sliderarrowinc { height: 0; }
scrollbarhorizontal { height: 10dp; margin: 3dp; }
scrollbarhorizontal slidertrack { background-color: transparent; }
scrollbarhorizontal sliderbar { background-color: var(--scrollbar); border-radius: 4dp; min-width: 40dp; }
scrollbarhorizontal sliderbar:hover { background-color: var(--scrollbar-hover); }
scrollbarhorizontal sliderarrowdec, scrollbarhorizontal sliderarrowinc { width: 0; }
button:focus, input:focus, select:focus, textarea:focus { border-color: var(--focus); }
.nav:focus { border-color: var(--focus); }
+50 -7
View File
@@ -1,10 +1,10 @@
# OpenBMH Editor 0.5.0
# OpenBMH Editor 0.5.2
Der eigenständige, native Editor verwendet **RmlUI, SDL2 und OpenGL**. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert. Editor 0.5.0 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.0`; die Spielversion ist 0.2.0.
Der eigenständige, native Editor verwendet **RmlUI, SDL2 und OpenGL**. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert. Editor 0.5.2 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.2`; die Spielversion ist 0.2.0.
## Starten und Daten öffnen
Das vollständige Paket `OpenBMHEditor-0.5.0-<plattform>.zip` entpacken und `OpenBMHEditor.exe` (Windows) beziehungsweise `OpenBMHEditor` (Linux/macOS) starten. `assets/editor` muss beim Programm bleiben. Auf macOS kann die unsignierte Anwendung über **Rechtsklick → Öffnen** gestartet werden. Eine Signatur/Notarisierung ist nicht Bestandteil dieser Version. `OpenBMHEditor --version` zeigt die Editorversion ohne Grafikstart.
Das vollständige Paket `OpenBMHEditor-0.5.2-<plattform>.zip` entpacken und `OpenBMHEditor.exe` (Windows) beziehungsweise `OpenBMHEditor` (Linux/macOS) starten. `assets/editor` muss beim Programm bleiben. Auf macOS kann die unsignierte Anwendung über **Rechtsklick → Öffnen** gestartet werden. Eine Signatur/Notarisierung ist nicht Bestandteil dieser Version. `OpenBMHEditor --version` zeigt die Editorversion ohne Grafikstart.
**Öffnen** bietet OBW-Dateien und entpackte Welten an. **BMH / FLTD importieren** liest einen Ordner mit einer unterstützten BMH- oder Football-Limited-Installation durch den bestehenden Konverter. Das Original wird nicht überschrieben. Eine bestehende Classic-OBW wird zunächst überprüft und dann in eine bearbeitbare Editorwelt übernommen.
@@ -25,6 +25,28 @@ Das vollständige Paket `OpenBMHEditor-0.5.0-<plattform>.zip` entpacken und `Ope
Shortcuts: Ctrl/Cmd+O, Ctrl/Cmd+S, Shift+Ctrl/Cmd+S, Ctrl/Cmd+Z und Shift+Ctrl/Cmd+Z. In Textfeldern gilt die lokale Text-Rückgängig-Funktion.
## Stärken und Gehälter vergleichen
**Wertevergleich** in der Seitenleiste (oder die gleichnamige Schaltfläche bei Spielern, Vereinen und Wettbewerben) öffnet eine Übersicht mit drei Ansichten: **Spieler**, **Mannschaften**, **Ligen**. Spieler zeigen ihre einzelnen Spielwerte und das Gehalt je Saison; Mannschaften und Ligen zeigen Durchschnittswerte, Spielergehaltssummen, das Durchschnittsgehalt und die Anzahl bekannter Gehälter. Ein Klick auf eine Zeile öffnet ihren Datensatz zur Bearbeitung.
- Auf einen Spaltenkopf klicken, um auf- oder absteigend zu sortieren. Sortiert wird der gesamte gefilterte Bestand vor der Aufteilung auf Seiten mit bis zu 200 Zeilen. Suche sowie Land-, Liga- und Vereinsfilter grenzen die Ansicht ein. Fehlende Zahlen stehen in beiden Sortierrichtungen hinten.
- **Spalten auswählen** blendet beliebige vorhandene Spielwerte ein. Bei vielen Spalten horizontal scrollen; Tabellenkopf und Werte bewegen sich gemeinsam. Die Wertebereiche stehen im Spaltenkopf, Gruppenwerte sind spielergewichtete Durchschnitte über bekannte Werte. Der gesamte Kader einschließlich Reserve zählt; reine Quellenduplikate mit `x-simulation.squad_role: source-only-duplicate` werden ausgeschlossen und ihre Anzahl angezeigt.
- Verschiedene Attributsysteme bleiben getrennt. Bei einem einzigen System werden dessen Spielwerte automatisch angezeigt. Bei mehreren ein **Attributsystem** wählen, um dessen Spieler und die daraus gebildeten Mannschafts-/Ligawerte zu vergleichen. Das FC-Attribut `strength` heißt in einem System mit `overall` **Körperkraft**; es wird nicht als Classic-Gesamtstärke interpretiert. Es wird keine neue Stärkeskala berechnet.
- **Gehälter gelten je Saison**, in der Währung und kleinsten Einheit aus dem OBW-Manifest. Berücksichtigt werden zum Saisonstart gültige Verträge des Spielers mit seiner aktuellen Mannschaft. Personalverträge, abgelaufene und zukünftige Verträge zählen nicht. Mehrere gleichzeitig gültige Verträge derselben Zuordnung sind unklar und werden nicht addiert. Ohne Vertragsangabe steht **—**, ein ausdrücklich gespeichertes Nullgehalt bleibt **0**.
- Unvollständige Gehaltssummen und Durchschnitte tragen ein **\***. Sie berücksichtigen nur bekannte Spielergehälter; die Spalte **Gehälter bekannt** zeigt die Abdeckung. Auch Spielwertdurchschnitte verwenden nur bekannte Werte (Anzahl per Tooltip). Classic-Grunddaten liefern häufig keine konkreten Verträge: Der Editor erfindet diese Gehälter nicht.
[Native Vorher-/Nachher-Bilder](qa/editor-comparison/README.md) dokumentieren die Ansichten und Spaltenauswahl.
Die Übersicht verändert weder Daten noch Undo-Historie. Änderungen und Rückgängig aktualisieren ihre Werte automatisch. Alle drei Themes und beide Sprachen werden unterstützt.
Über MCP liefert **`editor_compare`** dieselbe schreibgeschützte Übersicht. Beispielargumente:
```json
{"table":"players","sort":"attributes.overall","descending":true,"limit":200}
```
`table` ist `players`, `clubs` oder `leagues`. Weitere Sortierschlüssel sind `name`, `salary` (Spieler), `salary_total`, `salary_average`, `salary_known`, `player_count`, `club_count` sowie `attributes.<feld>`. `attribute_set` grenzt das System ein, `search`, `nation`, `competition`, `team` filtern, `offset`/`limit` blättern. Die Antwort enthält Originalskalen, Stichtag, Währung und Abdeckung. Gehälter bleiben Integer in kleinster Währungseinheit; das Durchschnittsgehalt wird auf diese Einheit gerundet. Das entsprechende Session-Kommando für Command-Scripts heißt `compare`.
## Optionen und MCP
**Optionen** bietet Deutsch/Englisch, Midnight Glass/Silver Glass/Matchday und den integrierten MCP-Server. Die Sprache ändert die Oberfläche; Namen und Quelldaten werden nicht übersetzt. Einstellungen werden im Benutzerprofil gespeichert.
@@ -41,7 +63,24 @@ Der MCP-Server ist standardmäßig aktiviert und bindet ausschließlich `127.0.0
Implementiert ist [MCP Streamable HTTP 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), mit Aushandlung von 2025-06-18; JSON-Antworten, ohne optionale SSE-Sitzungen. Neuere MCP-Versionen werden nicht als unterstützt beworben. Der Server prüft Token, Host und gegebenenfalls Origin. Oberfläche und Agent bearbeiten dieselbe Welt, verwenden dieselbe Validierung und dieselbe Undo-Historie. Für konkurrierende Änderungen `expected_revision` aus `editor_info`/`editor_get` mitsenden.
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_get`, `editor_apply`, `editor_rules`, `editor_validate`, `editor_history`, `editor_save`, `editor_undo`, `editor_redo`, `editor_roster_move`, `editor_roster_swap`, `editor_roster_order`, `editor_review_resolve`, `editor_image_import`, `editor_image_edit`, `editor_image_preview`, `editor_image_export`. Die eingeblendeten Tools enthalten Parameterschemata und Beschreibungen. Öffnen einer anderen Welt verwirft ungespeicherte Änderungen nur mit `discard: true`.
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_compare`, `editor_regulations`, `editor_get`, `editor_apply`, `editor_rules`, `editor_validate`, `editor_history`, `editor_save`, `editor_undo`, `editor_redo`, `editor_roster_move`, `editor_roster_swap`, `editor_roster_order`, `editor_review_resolve`, `editor_image_import`, `editor_image_edit`, `editor_image_preview`, `editor_image_export`. Die eingeblendeten Tools enthalten Parameterschemata und Beschreibungen. Öffnen einer anderen Welt verwirft ungespeicherte Änderungen nur mit `discard: true`.
## Spiel- und Ligaregeln ansehen
**Regelwerk** zeigt Auf- und Abstieg, Ziel-Ligen, Relegation und internationale
Qualifikation. Wettbewerbe lassen sich durchsuchen und nach Land filtern.
**Spielregeln** zeigt die übernommenen Einträge aus `world/rules.json`, etwa
Wertebereiche, Kreditfaktoren, Trainingslager und Classic-Verfahren. Phasen und
weitere Originalfelder sind ebenfalls einsehbar. Dieser Bereich ist vollständig
schreibgeschützt; er verändert weder Welt noch Undo-Historie.
Explizite OBW-Regeln werden direkt dargestellt. Bei Classic-Importen kennzeichnet
die Ansicht die versionierten Classic-Verfahrensregeln. Parallel-Ligen behalten
Meister plus bedingte Relegationsplätze; die unterste Liga nutzt den Nachrückerpool.
Internationale Plätze folgen dem ursprünglichen Champions-League-/UEFA-/
Pokalsieger-Cup-Verfahren. Nicht festgelegte Regeln bleiben als solche sichtbar.
Das sind keine heutigen UEFA-Regeln und kein neuer Saison-Simulator.
`editor_regulations` bietet dieselben Informationen schreibgeschützt über MCP.
## Kompilieren
@@ -49,8 +88,8 @@ Voraussetzungen entsprechen dem Hauptprojekt: C++20-Compiler, Git, CMake ≥ 3.2
```sh
cmake -S . -B build-editor -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON
cmake --build build-editor --target openbmh_editor editor_core_tests --parallel 2
ctest --test-dir build-editor -C Release -R '^editor_(core_tests|version)$' --output-on-failure
cmake --build build-editor --target openbmh_editor editor_core_tests editor_comparison_tests editor_regulations_tests --parallel 2
ctest --test-dir build-editor -C Release -R '^editor_(core_tests|comparison_tests|regulations_tests|version)$' --output-on-failure
```
macOS ARM zusätzlich bei der Konfiguration: `-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0`. Unter Windows das Argument nach `-R` ohne einfache Shell-Anführungszeichen verwenden. Der Editor wird beim normalen Spiel-Build standardmäßig nicht mitgebaut.
@@ -71,8 +110,12 @@ Pakete baut `tools/package/make_editor_package.py --build build-editor --out dis
Extract the complete package and run **OpenBMHEditor**. Open an OBW archive or an unpacked world, import a supported BMH/Football Limited installation, or open the synthetic demo. Use the sidebar, searchable/filterable list and property inspector; **Apply** records one shared, undoable transaction. **Save** writes only an **OBW 1.1 editor world**, not a playable Classic mod or a legacy installation.
Use **Comparison** to inspect sortable player, team and league ratings and per-season salaries. Select attribute columns and filter by country, league, club or attribute system. Group ratings are player-weighted means; salary totals and means use known player contracts only and explicitly flag incomplete coverage. Missing values remain unknown. The read-only MCP tool `editor_compare` returns the same data.
Use **Regulations** to inspect promotion, relegation, playoffs, international qualification and stored game rules. Explicit OBW declarations and versioned Classic policies are distinguished; missing rules stay unspecified. This page and `editor_regulations` are read only.
The editor retains full squads, original image data, source claims and unknown extensions. Its 24-player view does not remove players. Image import offers normalized crop, arbitrary rotation and mirroring; re-editing uses the preserved source. Classic portraits keep their frozen appearance recipe. Unsupported editing areas are preserved rather than replaced.
In **Options**, switch the interface to **English**, choose one of the three themes, and enable/disable the integrated local MCP server. **Copy connection** provides the authenticated configuration. The server defaults to loopback port 8765; use port 0 for a free port. GUI and MCP share the same world, validation and undo history. It supports MCP Streamable HTTP 2025-11-25/2025-06-18 and optional stdio mode. Use `expected_revision` for concurrent edits.
Build with the three commands above, including `-DOPENBMH_BUILD_EDITOR=ON`. The native application requires OpenGL 3.3 (macOS 4.1) and the platform development dependencies documented in the main README. Editor 0.5.0 is unsigned and does not bundle any real-world dataset or proprietary game assets.
Build with the three commands above, including `-DOPENBMH_BUILD_EDITOR=ON`. The native application requires OpenGL 3.3 (macOS 4.1) and the platform development dependencies documented in the main README. Editor 0.5.2 is unsigned and does not bundle any real-world dataset or proprietary game assets.
+16
View File
@@ -469,6 +469,22 @@ A resolver looks a key up in the active packs by priority (§9.5), then in the w
Asset metadata sits next to the files in `assets/index.json`: key, files per size, author, source and licence (required).
**Optional visual defaults (1.1).** A world may set
`manifest.presentation: "assets/presentation.json"`. The referenced document has
`schema: "asset-presentation@1"`, an optional `player_photo_fallback` asset key,
`trophy_fallback` (normally `asset:comp/generic/trophy`), and
`youth_photos: {assets: [<photo keys>], selection: "random-on-creation",
fallback: <photo key>}`. All keys resolve through the normal asset index. A
client supporting youth creation chooses once using its saved game RNG and
persists the selected key; it does not reroll a face on display or rename. This
document supplies pictures, never player records, ratings or generation rules.
Readers without this optional feature retain it and use their existing visual
fallbacks. The current editor preserves it without generating youth players.
An explicitly indexed player `photo` is displayed before composing a retained
`appearance` recipe. A visual overlay can therefore keep Classic appearance and
all game data intact while displaying a supplied photo or silhouette. Sealed
Classic rendering and runtime capabilities are unaffected.
**Player pictures** (`asset:player/<key>/photo`) resolve in this order:
1. A photo from an active pack.
+21
View File
@@ -126,6 +126,27 @@ the current edition's selection and qualification algorithm, including FA Cup
qualifying/proper rounds and League Cup for English data, or indoor/Masters for
German data. The generic `format` field alone is insufficient to execute a stage.
For inspection, `classic-season-entrants@1` assigns each first-division champion
to the Champions League. A holder in that league also qualifies (or the
runner-up if already champion). Domestic cup winners, with finalists as
replacements, enter the Cup Winners' Cup. Title-holder overlap affects the
remaining allocation. The regular UEFA-Cup quotas are `[4,4,4,4,3]` for source
league indices `[0,5,6,7,8]`, taking the next unqualified clubs by rank. Foreign
cup representatives follow the Classic selection procedure. The historical
`x-legacy.europe_places` field is a prediction/colouring value, not that quota.
The versioned Classic ladder uses its first four domestic groups. Relegation
counts come from each league's `x-legacy.relegation_places`. A single lower
league supplies the corresponding top-ranked clubs; parallel lower leagues
supply champions plus winners of the Classic playoffs. Without that playoff
result only the champions are exchanged. The last domestic group draws from
the newcomer pool, never a foreign league named by an unused `below` entry.
License withdrawals and the Classic protection of a human manager at the
bottom tier can affect the actual result. Foreign Classic leagues have no
regular promotion/relegation. These are compatibility policy summaries, not
independent typed modern rule declarations or permission to simulate them in
the editor.
`classic-calendar@1` retains the complete source day table and bindings.
`classic-season-calendar@1` applies options, season cycle, weekday alignment and
leap-year behavior using the Classic calendar algorithm at runtime. Cup series
+50 -1
View File
@@ -2,7 +2,7 @@
This additive profile is a native editing interchange. It does **not** change
`classic-installation-v1`, its seals, the Classic runtime or save files.
It is implemented by OpenBMH Editor 0.5.0, whose application version is separate
It is implemented by OpenBMH Editor 0.5.x, whose application version is separate
from the OBW format version and the OpenBMH 0.2.0 game version.
## Identification
@@ -61,6 +61,55 @@ Competition `trophy` and optional fallback remain logical asset references;
images are indexed just like crests and portraits. Arbitrary new competitions
can use their own trophy or a package-supplied generic trophy.
### Read-only comparisons (Editor 0.5.1)
The editor's `compare` command / `editor_compare` MCP tool projects ratings and
salaries without writing an additional OBW table. Player attributes retain their
set and range. Club and league attributes are player-weighted means of known
values within one set; mixed sets require a filter. Full rosters include reserves,
except source evidence explicitly marked
`x-simulation.squad_role: "source-only-duplicate"`. League membership uses a club's
explicit league, or an unambiguous league `members` reference as fallback.
`contracts.salary` is per season, in integer `manifest.currency` minor units.
Only contracts active on `manifest.start_date` and matching the player's current
team count; absent bounds are open and explicit date bounds are inclusive.
Multiple matching active contracts are ambiguous, not summed. Missing or invalid
salary remains null, independently of an explicit zero. Club/league payrolls
exclude staff and use known player salaries only. `salary_known`,
`salary_unknown`, `salary_ambiguous`, `salary_complete` and `salary_overflow`
describe coverage; a missing/empty/overflowed sum is null. Means of known salaries
round to the nearest minor unit. Attribute means separately report their sample
sizes in `attribute_counts`. No current date, invented contract or foreign-club
strength-band interpretation is substituted for missing data.
### Read-only regulations (Editor 0.5.2)
The `regulations` command / `editor_regulations` MCP tool exposes the same
read-only projection as the Regulations page. It accepts `language` (de/en),
`search`, `nation` and `competition`. It returns `items`, all preserved `rules`,
the world date, `read_only: true` and the session revision. It creates no table,
edits, undo entries or runtime entrants.
Each item retains its full `record` and `stages`. Explicit `movement` entries
retain rank ranges and destination references; tier comparisons label promotion
and relegation, participant roles label playoffs. Competition/stage `slots`
retain their full selector, fallback, explicit destination and phase; they are
visible on both the source and destination competition. Fixed participant lists
are not reinterpreted as qualification rules.
Imported `classic_runtime.qualifications: classic-season-entrants@1` and
`legacy_ladder` records permit a labelled presentation of the existing Classic
policy, documented in [classic-v1](classic-v1.md). Explicit declared rules take
precedence. Unknown rules stay unspecified; the editor never substitutes modern
UEFA quotas or infers qualification from historical colouring fields. This
presentation registry does not implement a new season engine.
Optional `manifest.presentation` references the `asset-presentation@1` visual
defaults described in [OBW §9.2](../OBW.md#92-resolution-and-image-formats).
Youth pools, silhouette and generic trophy keys remain indexed assets. They are
preserved across editor saves, independent of Classic source recipes or seals.
## Sources, conflicts and images
- `x-source/` can contain unchanged or losslessly gzipped normalized source
+51
View File
@@ -0,0 +1,51 @@
# Editor 0.5.1 — ratings and salaries
These are actual 1440×900 SDL2/OpenGL/RmlUI captures on Linux under Xvfb
with software OpenGL. All content is the synthetic `World::demo()` fixture:
52 invented players, two invented clubs, one league and 50 explicitly synthetic
per-season contracts (one unknown salary per club). No real-world data, original
game images, personal paths, settings or credentials are included. This editor
uses starting worlds, not a career save; reproduce the data with `--demo`.
| View | Evidence |
|---|---|
| Before, released Editor 0.5.0 | [Player inspector](before-players-0.5.0.png), without a ratings/payroll overview |
| Players, Midnight Glass / German | [Salary descending](players-midnight-de.png) |
| Teams, Silver Glass / English | [Player-weighted means, payroll and coverage](teams-silver-en.png) |
| Leagues, Matchday / German | [League aggregate](leagues-matchday-de.png) |
| Attribute selection | [Choose columns](columns-midnight-de.png) |
| Horizontal navigation | [Further attributes](players-scroll-midnight-de.png); header and values remain aligned |
The after views use Editor 0.5.1. The before capture uses the released 0.5.0
Linux executable and its own assets. No screenshot is a browser mockup.
Validation:
- `editor_core_tests`, `editor_comparison_tests`, `editor_version` pass locally.
The comparison suite checks 36 outcomes, including actual currency units,
unknown versus zero salaries, date/team selection, conflicting contracts,
staff exclusion, complete reserves, duplicate evidence, player-weighted means,
coverage, empty groups, numeric sorting across more than 200 rows, stable ties,
nulls last in both directions, different rating systems, overflow, read-only
session state, cache refresh after editing/undo and the shared MCP tool.
- `tests/editor_gui_smoke.py` performs real keyboard/mouse operations. It selects
a rating column via its label, sorts ratings and salaries, opens the first row
and edits it. MCP verifies the expected stable player/club/league identifier
changed, then undoes it. The existing inspector/search/JSON/undo/save checks
still pass. The comparison leaves the saved world clean.
- All three themes and both languages were inspected. Header arrows do not rely
on missing font glyphs; horizontal scrolling keeps column alignment.
- The completed private season was checked independently: 18,920 eligible
player rows, 545 teams, 32 leagues; 832 source-only duplicate rows excluded.
Every eligible player has one known current-team salary in that package.
These are dataset estimates, not verified real wages. No private rows or
screenshots are distributed in this public directory.
Build the targets and run the CTest commands in [the editor guide](../../EDITOR.md).
For the native input test, run `python3 tests/editor_gui_smoke.py <OpenBMHEditor>`
inside a graphical session or Xvfb with xdotool. `OpenBMHEditor --demo --page
comparison` opens the overview; the three buttons choose players, teams or
leagues. **Choose columns** selects additional attributes.
Windows/macOS native build and core tests run in the editor CI. The Linux
window checks do not establish human acceptance on those operating systems.
Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

+41
View File
@@ -0,0 +1,41 @@
<!-- SPDX-License-Identifier: GPL-3.0-only -->
# Editor 0.5.2: read-only regulations
Native 1440×900 SDL2/OpenGL/RmlUI captures on Linux with software OpenGL. All
records and artwork are synthetic. No installation, real club/player data,
savegame, private archive or user profile is included.
| View | Capture |
|---|---|
| Before: competition inspector, released 0.5.1 | [Before](before-competitions-0.5.1.png) |
| Promotion/relegation, Midnight Glass / German | [After](rules-midnight-de.png) |
| International qualification and replacement | [Qualification](qualification-midnight-de.png) |
| Preserved game rule and attribute ranges | [Game rules](game-rules-midnight-de.png) |
| Silver Glass / English | [Silver](rules-silver-en.png) |
| Matchday / German | [Matchday](rules-matchday-de.png) |
Create the display fixture using the editor's own synthetic demo:
```sh
python3 docs/qa/editor-regulations/make_fixture.py PATH/TO/OpenBMHEditor TEMP/synthetic.obw
OpenBMHEditor --open TEMP/synthetic.obw --page regulations
```
The recipe adds synthetic upper/lower leagues, explicit rank ranges, a playoff,
an international qualification selector and fallback. It is a display fixture,
not a playable season. Options selects the language/theme. Scroll the right
panel to qualification; select **Game rules** and `demo@1` to inspect the stored
attribute ranges. Before was captured with the same fixture in the 0.5.1
competition inspector, which had no dedicated rule view.
Validation: existing editor core/MCP tests, comparisons, version and new
regulations tests; native mouse/keyboard integration and package-boundary
checks. The regulations tests cover declared movement, both slot locations,
explicit destinations, fallback preservation, language/filtering, parallel
Classic champions/playoffs, the bottom newcomer pool, foreign closed leagues,
the named UEFA quotas, declared-rule precedence, null extensions and unchanged
revision/history. The GUI test switches both rule tabs, searches and verifies
the shared read-only MCP projection without changing the world.
Actual Diamond source identity, unchanged game data, images, round-trip checks
and captures are recorded separately in the private content repository.
Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

@@ -0,0 +1,54 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Make a synthetic display fixture; no real-world or installed game data."""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
import zipfile
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('editor', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='obw-rule-fixture-') as temporary:
root = Path(temporary)
settings = root / 'settings.json'
settings.write_text('{"mcp_enabled":false}')
subprocess.run([str(args.editor.resolve()), '--headless', '--demo', '--settings', str(settings),
'--output', str(root / 'demo.obw')], check=True)
with zipfile.ZipFile(root / 'demo.obw') as source:
docs = {file: source.read(file) for file in source.namelist()}
comps = json.loads(docs['world/competitions.json'])
league = comps['items'][0]
league.update({'tier': 2, 'stages': [{'id': 'regular', 'format': 'league', 'teams': 18, 'legs': 2,
'points': {'win': 3, 'draw': 1, 'loss': 0}, 'tiebreakers': ['points', 'goal_difference', 'goals_for']}],
'movement': [{'ranks': [1, 2], 'to': 'comp:upper'},
{'ranks': [3], 'to': 'comp:playoff', 'role': 'challenger'},
{'ranks': [16, 18], 'to': 'comp:lower'}]})
clubs = json.loads(docs['world/clubs.json'])
for i in range(16):
club_id = 'club:fixture-' + str(i)
clubs['items'].append({'id': club_id, 'name': 'Testverein ' + str(i + 1), 'type': 'club',
'nation': 'nation:de', 'competition': 'comp:demo'})
league['members'].append(club_id)
for code, title, tier in [('upper', 'Oberliga (Demo)', 1), ('lower', 'Unterliga (Demo)', 3)]:
comps['items'].append({'id': 'comp:' + code, 'name': title, 'nation': 'nation:de', 'type': 'league',
'tier': tier, 'stages': [{'id': 'regular', 'format': 'league', 'teams': 18}]})
comps['items'].append({'id': 'comp:playoff', 'name': 'Relegation (Demo)', 'type': 'cup'})
comps['items'].append({'id': 'comp:international', 'name': 'Internationaler Demo-Pokal',
'type': 'club_international', 'slots': [{'from': 'comp:demo', 'ranks': [1, 4], 'stage': 'main',
'fallback': {'from': 'comp:upper', 'next_unqualified': True}}]})
for key, value in [('world/competitions.json', comps), ('world/clubs.json', clubs)]:
docs[key] = json.dumps(value, ensure_ascii=False).encode()
args.output.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(args.output, 'w', zipfile.ZIP_DEFLATED) as output:
for file, data in docs.items():
output.writestr(file, data)
if __name__ == '__main__':
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

+33 -1
View File
@@ -1,5 +1,37 @@
<!-- SPDX-License-Identifier: GPL-3.0-only -->
# OpenBMH Editor 0.5.0
# OpenBMH Editor 0.5.2
Adds **Regulations / Regelwerk**, a read-only view of game and league rules.
Inspect promotion/relegation places and destinations, playoff conditions,
international qualification selectors and replacement rules. Search competitions
and filter by country; inspect preserved game-rule records and stage details.
Both interface languages and all three themes are supported. The read-only MCP
tool `editor_regulations` returns the same projection.
Explicit OBW declarations take precedence. Imported worlds show the named
Classic ladder and qualification policy, clearly labelled. The parallel third
divisions retain champion-plus-playoff promotion; the bottom tier uses its
newcomer pool. Historical display/colouring quotas are not reinterpreted as
European qualification rules. Undeclared rules stay unspecified.
This adds no season simulation or rule editing.
## Editor 0.5.1
Adds **Ratings & salaries / Wertevergleich**: sortable player, team and league
overviews, searchable and filterable by country/league/club and attribute system.
Choose the attribute columns and scroll horizontally for additional metrics.
Click a row to open its existing editor. All three themes and both interface
languages are supported.
Player values retain their native scales. Group ratings are player-weighted
means; salaries are per-season amounts from contracts active at the world start
date. Partial wage bills are marked, unknown values stay unknown, explicit zero
salaries remain zero. All reserves are included; source-only duplicate evidence
is excluded. Different rating systems are not combined. The read-only MCP tool
`editor_compare` exposes the same results and pagination. Comparison caches
refresh after edits and undo/redo without changing the world.
## Initial editor 0.5.0
The first standalone editor release uses SDL2, RmlUI and OpenGL on Windows x64,
Linux x64 and macOS ARM64. Its version is independent of OpenBMH 0.2.0.
+14 -2
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-only
include(FetchContent)
set(OPENBMH_EDITOR_VERSION "0.5.0")
set(OPENBMH_EDITOR_VERSION "0.5.2")
file(WRITE "${CMAKE_BINARY_DIR}/editor-version.json" "{\"version\": \"${OPENBMH_EDITOR_VERSION}\"}\n")
set(JSON_BuildTests OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_json GIT_REPOSITORY https://github.com/nlohmann/json.git
@@ -44,7 +44,7 @@ foreach(component editor_json editor_http editor_images editor_svg editor_xml)
endforeach()
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n")
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp images.cpp options.cpp mcp.cpp)
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp comparison.cpp regulations.cpp images.cpp options.cpp mcp.cpp)
target_compile_definitions(bmh_editor_core PUBLIC OPENBMH_EDITOR_VERSION="${OPENBMH_EDITOR_VERSION}")
target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR})
target_link_libraries(bmh_editor_core PUBLIC nlohmann_json::nlohmann_json bmh_content
@@ -85,5 +85,17 @@ if(MSVC)
target_compile_options(editor_core_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_core_tests COMMAND editor_core_tests)
add_executable(editor_comparison_tests ../../tests/editor_comparison_tests.cpp)
target_link_libraries(editor_comparison_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_comparison_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_comparison_tests COMMAND editor_comparison_tests)
add_executable(editor_regulations_tests ../../tests/editor_regulations_tests.cpp)
target_link_libraries(editor_regulations_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_regulations_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_regulations_tests COMMAND editor_regulations_tests)
add_test(NAME editor_version COMMAND openbmh_editor --version)
set_tests_properties(editor_version PROPERTIES PASS_REGULAR_EXPRESSION "OpenBMH Editor ${OPENBMH_EDITOR_VERSION}")
+307
View File
@@ -0,0 +1,307 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/world.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
namespace bmh::editor {
namespace {
bool date_valid(const std::string &date) {
if (date.size() != 10 || date[4] != '-' || date[7] != '-')
return false;
for (size_t i = 0; i < date.size(); ++i)
if (i != 4 && i != 7 && (date[i] < '0' || date[i] > '9'))
return false;
if (std::stoi(date.substr(0, 4)) < 1583)
return false;
return std::chrono::year_month_day{std::chrono::year(std::stoi(date.substr(0, 4))),
std::chrono::month(unsigned(std::stoi(date.substr(5, 2)))),
std::chrono::day(unsigned(std::stoi(date.substr(8, 2))))}
.ok();
}
bool source_duplicate(const Json &player) {
const auto simulation = player.value("x-simulation", Json::object());
return str(simulation, "squad_role") == "source-only-duplicate";
}
std::optional<int64_t> money(const Json &value) {
if (!value.is_number_integer() ||
(value.is_number_unsigned() && value.get<uint64_t>() > uint64_t(std::numeric_limits<int64_t>::max())))
return {};
const auto number = value.get<int64_t>();
return number >= 0 ? std::optional<int64_t>(number) : std::nullopt;
}
struct Mean {
long double sum = 0;
size_t count = 0;
void add(const Json &value) {
if (value.is_number() && std::isfinite(value.get<double>())) {
sum += value.get<double>();
++count;
}
}
Json value() const { return count ? Json(double(sum / count)) : Json(); }
};
struct Group {
size_t players = 0, known = 0, ambiguous = 0;
int64_t salary = 0;
bool overflow = false;
std::map<std::string, Mean> attributes;
void add(const Json &player) {
++players;
for (auto it = player["attributes"].begin(); it != player["attributes"].end(); ++it)
attributes[it.key()].add(it.value());
ambiguous += player.value("salary_ambiguous", size_t(0));
if (const auto amount = money(player["salary"])) {
++known;
if (salary > std::numeric_limits<int64_t>::max() - *amount)
overflow = true;
else
salary += *amount;
}
}
void write(Json &row, const Json &fields) const {
row["player_count"] = players;
row["salary_known"] = known;
row["salary_unknown"] = players - known;
row["salary_ambiguous"] = ambiguous;
row["salary_overflow"] = overflow;
row["salary_complete"] = players > 0 && known == players && !overflow;
row["salary_total"] = known && !overflow ? Json(salary) : Json();
// Salaries remain integer minor units. Round the mean to the nearest
// minor unit without overflowing the sum or inventing unknown wages.
row["salary_average"] =
known && !overflow
? Json(salary / int64_t(known) + (salary % int64_t(known) >= int64_t((known + 1) / 2)))
: Json();
row["attributes"] = Json::object();
row["attribute_counts"] = Json::object();
for (const auto &field : fields) {
const auto key = str(field, "key");
const auto found = attributes.find(key);
row["attributes"][key] = found == attributes.end() ? Json() : found->second.value();
row["attribute_counts"][key] = found == attributes.end() ? 0 : found->second.count;
}
}
};
} // namespace
Json comparison_data(const World &world, const Json &args) {
const auto table = str(args, "table", "players"), language = str(args, "language", "de");
if (table != "players" && table != "clubs" && table != "leagues")
throw Error("unknown_table");
if (language != "de" && language != "en")
throw Error("invalid_change");
std::map<std::string, const Json *> clubs, leagues;
std::map<std::string, std::set<std::string>> memberships;
for (const auto &league : world.rows("competitions"))
if (str(league, "type") == "league") {
const auto id = str(league, "id");
leagues[id] = &league;
for (const auto &member : league.value("members", Json::array()))
if (member.is_string())
memberships[member.get<std::string>()].insert(id);
}
for (const auto &club : world.rows("clubs"))
clubs[str(club, "id")] = &club;
auto league_for = [&](const std::string &id) {
const auto comp = clubs.contains(id) ? str(*clubs.at(id), "competition") : "";
if (leagues.contains(comp))
return comp;
const auto found = memberships.find(id);
return found != memberships.end() && found->second.size() == 1 ? *found->second.begin()
: std::string();
};
std::map<std::string, size_t> sets;
size_t excluded = 0;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player)) {
++excluded;
continue;
}
++sets[str(player, "attribute_set")];
}
auto selected_set = str(args, "attribute_set");
if (!selected_set.empty() && !sets.contains(selected_set))
throw Error("invalid_attribute_set");
if (selected_set.empty() && sets.size() == 1)
selected_set = sets.begin()->first;
// Equal-looking numbers can have different meanings (FC physical strength
// versus Classic playing strength). Never average or sort mixed systems.
const bool mixed = selected_set.empty() && sets.size() > 1;
std::map<std::string, Json> fields;
if (!mixed) {
for (const auto &rule : world.rows("rules")) {
auto id = str(rule, "attribute_set", str(rule, "id"));
if (str(rule, "type") == "attribute_set" &&
(id == selected_set || id == "rule:" + selected_set)) {
const auto definitions = rule.value("fields", Json::object());
for (auto it = definitions.begin(); it != definitions.end(); ++it)
fields[it.key()] = {{"key", it.key()},
{"min", it.value().value("min", Json())},
{"max", it.value().value("max", Json())}};
}
}
for (const auto &player : world.rows("players"))
if (!source_duplicate(player) && str(player, "attribute_set") == selected_set) {
const auto attributes = player.value("attributes", Json::object());
for (auto it = attributes.begin(); it != attributes.end(); ++it)
if (it.value().is_number() && !fields.contains(it.key()))
fields[it.key()] = {{"key", it.key()}, {"min", nullptr}, {"max", nullptr}};
}
}
Json definitions = Json::array();
for (const auto &[_, field] : fields)
definitions.push_back(field);
Json available_sets = Json::array();
for (const auto &[id, count] : sets)
available_sets.push_back({{"id", id}, {"players", count}});
const auto date = str(world.manifest, "start_date");
std::map<std::pair<std::string, std::string>, std::vector<const Json *>> contracts;
if (date_valid(date))
for (const auto &contract : world.rows("contracts")) {
const auto start = str(contract, "start"), end = str(contract, "end");
// An absent date is an open bound. A malformed bound cannot be
// treated as evidence of an active employment contract.
const auto start_value = contract.value("start", Json()),
end_value = contract.value("end", Json());
if ((!start_value.is_null() && !start_value.is_string()) ||
(!end_value.is_null() && !end_value.is_string()) ||
(!start.empty() && (!date_valid(start) || start > date)) ||
(!end.empty() && (!date_valid(end) || end < date)))
continue;
contracts[{str(contract, "person"), str(contract, "team")}].push_back(&contract);
}
Json players = Json::array();
std::map<std::string, Group> club_groups, league_groups;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player) ||
(!selected_set.empty() && str(player, "attribute_set") != selected_set))
continue;
const auto id = str(player, "id"), team = str(player, "team"), league = league_for(team);
const auto *club = clubs.contains(team) ? clubs.at(team) : nullptr;
Json row{{"id", id},
{"name", world.title(player, language)},
{"team", team},
{"nation", club ? str(*club, "nation") : ""},
{"competition", league},
{"positions", player.value("positions", Json::array())},
{"attribute_set", str(player, "attribute_set")},
{"player_count", 1},
{"attributes", Json::object()},
{"salary", nullptr},
{"salary_ambiguous", 0}};
const auto attributes = player.value("attributes", Json::object());
for (const auto &[key, _] : fields) {
const auto value = attributes.value(key, Json());
row["attributes"][key] = value.is_number() && std::isfinite(value.get<double>()) ? value : Json();
}
if (!team.empty()) {
const auto found = contracts.find({id, team});
if (found != contracts.end()) {
if (found->second.size() == 1) {
const auto salary = money(found->second.front()->value("salary", Json()));
if (salary)
row["salary"] = *salary;
} else
row["salary_ambiguous"] = 1;
}
}
if (club)
club_groups[team].add(row);
if (!league.empty())
league_groups[league].add(row);
players.push_back(std::move(row));
}
Json rows = Json::array();
if (table == "players")
rows = std::move(players);
else if (table == "clubs") {
for (const auto &[id, club] : clubs) {
Json row{{"id", id},
{"name", world.title(*club, language)},
{"nation", str(*club, "nation")},
{"competition", league_for(id)}};
club_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
} else
for (const auto &[id, league] : leagues) {
Json row{{"id", id},
{"name", world.title(*league, language)},
{"nation", str(*league, "nation")},
{"competition", id},
{"club_count", 0}};
for (const auto &[club_id, _] : clubs)
if (league_for(club_id) == id)
row["club_count"] = row["club_count"].get<size_t>() + 1;
league_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
const auto simulation = world.manifest.value("x-simulation", Json());
return {{"table", table},
{"items", std::move(rows)},
{"attributes", definitions},
{"attribute_sets", available_sets},
{"attribute_set", selected_set},
{"mixed_attribute_sets", mixed},
{"currency", world.manifest.value("currency", Json())},
{"date", date},
{"excluded_players", excluded},
{"fictional_completion",
simulation.is_object() && simulation.value("fictional_completion", Json()) == true}};
}
Json query_comparison(const Json &data, const Json &args) {
const auto search = folded(str(args, "search")), nation = str(args, "nation"),
league = str(args, "competition"), team = str(args, "team"), sort = str(args, "sort", "name");
const bool descending = args.value("descending", false);
bool valid_sort = sort == "name" || sort == "salary" || sort == "salary_total" ||
sort == "salary_average" || sort == "player_count" || sort == "club_count" ||
sort == "salary_known";
for (const auto &field : data["attributes"])
valid_sort |= sort == "attributes." + str(field, "key");
if (!valid_sort)
throw Error("invalid_comparison_sort");
auto value = [&](const Json &row) {
if (sort == "name")
return Json(folded(str(row, "name")));
if (sort.starts_with("attributes."))
return row["attributes"].value(sort.substr(11), Json());
return row.value(sort, Json());
};
std::vector<const Json *> matches;
for (const auto &row : data["items"]) {
if ((!nation.empty() && str(row, "nation") != nation) ||
(!league.empty() && str(row, "competition") != league) ||
(!team.empty() && str(row, "team", str(row, "id")) != team) ||
(!search.empty() && folded(str(row, "name")).find(search) == std::string::npos &&
folded(str(row, "id")).find(search) == std::string::npos))
continue;
matches.push_back(&row);
}
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
const auto av = value(*a), bv = value(*b);
if (av.is_null() != bv.is_null())
return !av.is_null(); // Unknown values are last in both directions.
if (av == bv)
return str(*a, "id") < str(*b, "id");
return descending ? av > bv : av < bv;
});
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
Json result = Json::object();
for (auto it = data.begin(); it != data.end(); ++it)
if (it.key() != "items")
result[it.key()] = it.value();
result["items"] = Json::array();
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
i < matches.size() && int64_t(result["items"].size()) < limit; ++i)
result["items"].push_back(*matches[i]);
result["total"] = matches.size();
result["offset"] = offset;
result["limit"] = limit;
return result;
}
} // namespace bmh::editor
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
class World;
// Read-only projections. Session caches the unfiltered data at its revision;
// searching, sorting and paging always operate on the complete projection.
Json comparison_data(const World &, const Json &args);
Json query_comparison(const Json &data, const Json &args);
} // namespace bmh::editor
+39
View File
@@ -52,6 +52,8 @@ const std::map<std::string, std::string> commands{{"editor_info", "info"},
{"editor_open", "open"},
{"editor_new", "new"},
{"editor_list", "list"},
{"editor_compare", "compare"},
{"editor_regulations", "regulations"},
{"editor_get", "get"},
{"editor_apply", "apply"},
{"editor_validate", "validate"},
@@ -142,6 +144,43 @@ Json McpServer::tools() {
{"descending", field("boolean")},
{"unresolved_only", field("boolean")}},
{"table"}, true);
add("editor_compare",
"Read-only ratings and salary comparison for players, clubs or leagues. Attributes are native player "
"values "
"or player-weighted group means, within one attribute_set. Mixed systems need a filter for ratings. "
"Salary is integer world-currency minor units per season, from contracts active at "
"manifest.start_date "
"and matching the player's current team. Unknown/ambiguous salaries stay null. Group totals/means "
"cover "
"known player salaries only; salary_known/unknown/complete report coverage. All reserves are "
"included; "
"source-only duplicate evidence is excluded. Sorts the complete result before paging (max 200); "
"nulls last in both directions. Does not edit the world.",
{{"table", {{"type", "string"}, {"enum", {"players", "clubs", "leagues"}}}},
{"language", {{"type", "string"}, {"enum", {"de", "en"}}}},
{"attribute_set", field("string", "Optional set ID; automatic when only one system is present.")},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"team", id},
{"sort", field("string", "name, player_count, club_count, salary, salary_total, salary_average, "
"salary_known, attributes.<key>")},
{"descending", field("boolean")},
{"offset", field("integer")},
{"limit", field("integer")}},
{}, true);
add("editor_regulations",
"Read-only declared game/league rules, promotion, relegation and qualification selectors. "
"Also identifies inherited classic-season-entrants@1 and Classic ladder policies, without "
"replacing them with current football regulations. Missing rules remain unspecified. "
"Preserves source definitions and returns all game rule records. Never simulates a season or edits "
"data.",
{{"language", {{"type", "string"}, {"enum", {"de", "en"}}}},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"expected_revision", revision}},
{}, true);
add("editor_get", "Read a complete row, including preserved extensions and sources.",
{{"table", table}, {"id", id}}, {"table", "id"}, true);
add("editor_apply",
+164 -17
View File
@@ -89,6 +89,135 @@ std::string tr(const std::string &language, const std::string &key) {
using Pair = std::pair<std::string, std::string>;
static const std::map<std::string, Pair> words{
{"data_areas", {"Datenbereiche", "World data"}},
{"regulations", {"Regelwerk", "Regulations"}},
{"regulations_title", {"Spiel- & Ligaregeln", "Game & league rules"}},
{"subtitle_regulations",
{"Aufstieg, Abstieg und internationale Qualifikation",
"Promotion, relegation and international qualification"}},
{"regulation_readonly", {"Nur Anzeige", "Read only"}},
{"regulation_competitions", {"Ligen & Wettbewerbe", "Leagues & competitions"}},
{"regulation_game", {"Spielregeln", "Game rules"}},
{"regulation_movement_title", {"Auf- & Abstieg", "Promotion & relegation"}},
{"regulation_qualification_title",
{"Internationale Qualifikation & Teilnehmer", "International qualification & entrants"}},
{"regulation_promotion", {"Aufstieg", "Promotion"}},
{"regulation_relegation", {"Abstieg", "Relegation"}},
{"regulation_playoff", {"Relegationsspiele", "Playoffs"}},
{"regulation_playoff_winner", {"Sieger der Classic-Relegation", "Classic playoff winner"}},
{"regulation_classic_playoffs",
{"Bei parallelen unteren Ligen steigen die Meister direkt auf. Weitere Aufsteiger bestimmt die "
"Classic-Relegation. Ohne deren Ergebnis werden nur die Meister ausgetauscht.",
"For parallel lower leagues, champions go up directly. Additional promotion follows the Classic "
"playoffs. Without a playoff result, only champions are exchanged."}},
{"regulation_movement", {"Ligenwechsel", "League movement"}},
{"regulation_rank", {"Platz", "Rank"}},
{"regulation_to", {"in", "to"}},
{"regulation_closed", {"Kein regulärer Auf- oder Abstieg.", "No regular promotion or relegation."}},
{"regulation_unspecified", {"Nicht im OBW festgelegt.", "Not specified in the OBW."}},
{"regulation_amateur_pool",
{"Nachrückerpool der untersten Spielklasse", "Lowest-tier newcomer pool"}},
{"regulation_declared", {"Im OBW festgelegt", "Declared in the OBW"}},
{"regulation_classic", {"Classic-Verfahrensregel", "Classic adapter policy"}},
{"regulation_classic_movement_note",
{"Reguläre Plätze. Lizenzentzüge können die Saisonentscheidung ändern. Die Zuordnung zu parallelen "
"Ligen erfolgt beim Saisonwechsel.",
"Regular places. License withdrawals can change the season outcome. Allocation to parallel leagues "
"occurs at season rollover."}},
{"regulation_classic_intro",
{"Übernommenes Classic-Verfahren, keine heutigen UEFA-Regeln.",
"Inherited Classic policy; current UEFA regulations do not apply."}},
{"regulation_classic_champion",
{"Meister qualifiziert für die Champions League. Titelverteidiger werden zusätzlich berücksichtigt; "
"ist dieser bereits Meister, rückt der Zweite nach.",
"Champion qualifies for the Champions League. The holder also qualifies; if already champion, the "
"runner-up receives the extra place."}},
{"regulation_classic_cup",
{"Nationaler Pokalsieger qualifiziert für den Pokalsieger-Wettbewerb, bei bestehender Qualifikation "
"der Finalist. Ausländische Pokalvertreter werden im Classic-Verfahren bestimmt.",
"Domestic cup winner qualifies for the Cup Winners’ Cup; the finalist replaces an already "
"qualified winner. Foreign cup entrants follow the Classic selection policy."}},
{"regulation_classic_uefa",
{"reguläre Plätze nach Tabellenrang; bereits qualifizierte Teams werden übersprungen.",
"regular places by league rank; already qualified teams are skipped."}},
{"regulation_classic_holders",
{"Titelverteidiger von UEFA- und Pokalsieger-Cup sowie Doppelqualifikationen können zusätzliche "
"Plätze und Nachrücker auslösen.",
"UEFA/Cup Winners’ Cup holders and overlapping qualifications may produce extra places or "
"replacements."}},
{"regulation_runtime",
{"Teilnehmer werden durch das hinterlegte Classic-Verfahren bestimmt.",
"Entrants are resolved by the stored Classic policy."}},
{"regulation_winner", {"Sieger", "Winner"}},
{"regulation_runner_up", {"Finalist / Zweiter", "Runner-up"}},
{"regulation_next_unqualified", {"Nächstes noch nicht qualifiziertes Team", "Next unqualified team"}},
{"regulation_holder", {"Titelverteidiger", "Title holder"}},
{"regulation_coefficient",
{"Qualifikation nach Koeffizientenrang", "Qualification by coefficient rank"}},
{"regulation_fallback", {"Nachrücken", "Replacement"}},
{"regulation_stage", {"Phase", "Stage"}},
{"regulation_stages", {"Wettbewerbsphasen & Spielregeln", "Competition stages & match rules"}},
{"regulation_show_source", {"OBW-Details anzeigen", "Show OBW details"}},
{"regulation_hide_source", {"OBW-Details ausblenden", "Hide OBW details"}},
{"regulation_preserved",
{"Unveränderte Angaben aus world/rules.json. Diese Ansicht ist schreibgeschützt.",
"Unmodified values from world/rules.json. This view is read only."}},
{"regulation_type_league", {"Liga", "League"}},
{"regulation_type_cup", {"Pokal", "Cup"}},
{"regulation_type_national_team", {"Nationalmannschaften", "National teams"}},
{"regulation_type_club_international",
{"Internationaler Vereinswettbewerb", "International club competition"}},
{"regulation_type_friendly", {"Freundschaftsspiel", "Friendly"}},
{"regulation_type_indoor", {"Hallenturnier", "Indoor tournament"}},
{"rule_type_attribute_set", {"Spielwerte & Wertebereiche", "Attributes & ranges"}},
{"rule_type_fixture_tables", {"Spielplanverfahren", "Fixture generation"}},
{"rule_type_legacy_ladder", {"Classic-Ligenpyramide", "Classic league pyramid"}},
{"rule_type_training_camps", {"Trainingslager", "Training camps"}},
{"rule_type_credit_rates", {"Kreditregeln", "Credit rules"}},
{"rule_type_classic_runtime", {"Classic-Verfahren", "Classic runtime policies"}},
{"rule_type_classic_data_regions", {"Übernommene Classic-Regeldaten", "Preserved Classic rule data"}},
{"comparison", {"Wertevergleich", "Comparison"}},
{"comparison_title", {"Stärken & Gehälter", "Ratings & salaries"}},
{"subtitle_comparison",
{"Spieler, Mannschaften und Ligen im Vergleich", "Compare players, teams and leagues"}},
{"teams", {"Mannschaften", "Teams"}},
{"leagues", {"Ligen", "Leagues"}},
{"physical_strength", {"Körperkraft", "Physical strength"}},
{"comparison_columns", {"Spalten auswählen", "Choose columns"}},
{"comparison_columns_hint",
{"Spielwerte einblenden. Weitere Spalten sind horizontal erreichbar.",
"Select attributes. Scroll horizontally to see further columns."}},
{"comparison_all_sets", {"Alle Spieler · Systeme getrennt", "All players · separate systems"}},
{"comparison_all_players", {"alle Spieler", "all players"}},
{"all_columns", {"Alle auswählen", "Select all"}},
{"no_columns", {"Keine auswählen", "Select none"}},
{"comparison_player_values", {"Originalskala des Datensatzes", "Dataset's original scale"}},
{"comparison_mean_values", {"Spielwerte: Durchschnitt je Spieler", "Attributes: mean per player"}},
{"comparison_known_values", {"bekannte Werte", "known values"}},
{"salary_season", {"Gehalt / Saison", "Salary / season"}},
{"salary_total", {"Gehaltssumme / Saison", "Total salary / season"}},
{"salary_average", {"Ø Gehalt / Spieler", "Mean salary / player"}},
{"salary_coverage", {"Gehälter bekannt", "Salaries known"}},
{"salary_missing", {"Gehälter unbekannt", "salaries unknown"}},
{"salary_ambiguous", {"mehrere aktive Verträge", "multiple active contracts"}},
{"comparison_salary_note",
{"Gehälter je Saison in Weltwährung. * Nur bekannte Gehälter; Summe/Ø unvollständig. Stichtag",
"Salaries per season in world currency. * Known salaries only; total/mean incomplete. As of"}},
{"comparison_scope_note",
{"Gesamter Kader inklusive Reserven. Fehlende Spielwerte bleiben leer; Ø nur aus bekannten Werten.",
"Full squads including reserves. Missing attributes stay blank; means use known values only."}},
{"comparison_mixed_note",
{"Für Stärken ein Attributsystem auswählen. Unterschiedliche Systeme werden nicht vermischt.",
"Choose an attribute set to compare ratings. Different systems are not mixed."}},
{"comparison_excluded", {"Quellenduplikate nicht eingerechnet", "source duplicates excluded"}},
{"comparison_fictional",
{"Der Datensatz enthält als fiktiv oder geschätzt gekennzeichnete Ergänzungen.",
"The dataset includes additions marked as fictional or estimated."}},
{"comparison_sort_hint", {"Spaltenkopf anklicken zum Sortieren", "Click a column heading to sort"}},
{"invalid_attribute_set",
{"Dieses Attributsystem ist nicht im Datenbestand.",
"This attribute set is not present in the dataset."}},
{"invalid_comparison_sort",
{"Diese Vergleichsspalte ist nicht verfügbar.", "This comparison column is unavailable."}},
{"invalid_manifest",
{"Die Kennzeichnung der Editorwelt ist ungültig.", "The editor world identification is invalid."}},
{"facilities", {"Ausstattung", "Facilities"}},
@@ -109,9 +238,11 @@ std::string tr(const std::string &language, const std::string &key) {
{"x", {"Links", "Left"}},
{"y", {"Oben", "Top"}},
{"open_folder", {"Entpackte Welt öffnen", "Open unpacked world"}},
{"subtitle_overview", {"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_overview",
{"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_nations", {"Länder, Verbände und Simulation", "Countries, associations and simulation"}},
{"subtitle_competitions", {"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_competitions",
{"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_clubs", {"Stammdaten, Farben und Spielstätten", "Details, colours and home grounds"}},
{"subtitle_players",
{"Spielerdaten und quellengerechte Spielwerte", "Player details and source-specific attributes"}},
@@ -120,7 +251,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"subtitle_assets", {"Wappen, Porträts und Pokale", "Crests, portraits and trophies"}},
{"subtitle_review", {"Quellen vergleichen", "Compare sources"}},
{"subtitle_roster", {"Vollständige Kader ohne Datenverlust", "Complete squads without losing data"}},
{"subtitle_changes", {"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"subtitle_changes",
{"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"preservation_note",
{"Quellen, Bilder und Erweiterungen bleiben erhalten. Bearbeitungen "
"ändern keine Originalinstallation.",
@@ -136,12 +268,14 @@ std::string tr(const std::string &language, const std::string &key) {
"Drag a rectangle on the image or enter crop values. Without cropping, "
"the original resolution is retained."}},
{"video_failed",
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).", "The interface requires OpenGL 3.3 (macOS: 4.1)."}},
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).",
"The interface requires OpenGL 3.3 (macOS: 4.1)."}},
{"ui_assets_missing",
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
"Editor interface files are missing. Please extract the complete "
"package."}},
{"dialog_failed", {"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"dialog_failed",
{"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"invalid_attributes", {"Ungültige Spielwerte.", "Invalid player attributes."}},
{"app", {"OpenBMH Editor", "OpenBMH Editor"}},
{"editor_tagline", {"OBW-Dateneditor", "OBW world editor"}},
@@ -223,6 +357,7 @@ std::string tr(const std::string &language, const std::string &key) {
{"condition", {"Kondition", "Condition"}},
{"form", {"Form", "Form"}},
{"overall", {"Gesamtstärke", "Overall"}},
{"tacticalawareness", {"Taktisches Verständnis", "Tactical awareness"}},
{"potential", {"Potenzial", "Potential"}},
{"acceleration", {"Antritt", "Acceleration"}},
{"sprintspeed", {"Sprinttempo", "Sprint speed"}},
@@ -313,7 +448,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"resolve", {"Auswahl übernehmen", "Use selected value"}},
{"resolved", {"Erledigt", "Resolved"}},
{"unresolved", {"Offen", "Open"}},
{"review_hint", {"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"review_hint",
{"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"roster_hint",
{"Verein wählen, Spieler verschieben oder zwei Spieler tauschen.",
"Choose a club, move a player or swap two players."}},
@@ -326,7 +462,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"errors", {"Fehler", "Errors"}},
{"no_changes", {"Noch keine Änderungen", "No changes yet"}},
{"dirty_prompt", {"Änderungen speichern?", "Save changes?"}},
{"dirty_detail", {"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"dirty_detail",
{"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"delete_prompt", {"Datensatz wirklich löschen?", "Delete this record?"}},
{"new_name", {"Name des neuen Datensatzes", "Name of the new record"}},
{"new_title", {"Neue Fußballwelt", "New football world"}},
@@ -342,22 +479,27 @@ std::string tr(const std::string &language, const std::string &key) {
{"Speichern fehlgeschlagen. Die bisherige Datei bleibt erhalten.",
"Saving failed. The previous file is retained."}},
{"invalid_archive",
{"Das Archiv ist beschädigt oder wird nicht unterstützt.", "The archive is damaged or unsupported."}},
{"unsupported_archive", {"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"Das Archiv ist beschädigt oder wird nicht unterstützt.",
"The archive is damaged or unsupported."}},
{"unsupported_archive",
{"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"archive_limit",
{"Das Datenpaket überschreitet die unterstützten Grenzen.", "The data package exceeds the supported limits."}},
{"Das Datenpaket überschreitet die unterstützten Grenzen.",
"The data package exceeds the supported limits."}},
{"unsafe_path", {"Unzulässiger Dateipfad.", "Invalid file path."}},
{"size_limit", {"Die Datei ist zu groß.", "The file is too large."}},
{"missing_manifest", {"Keine OBW-Welt gefunden.", "No OBW world found."}},
{"not_world", {"Bitte eine OBW-Startdatenbank öffnen.", "Please open an OBW starting world."}},
{"unsupported_version", {"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"unsupported_version",
{"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"invalid_json", {"Die JSON-Daten sind ungültig.", "The JSON data is invalid."}},
{"invalid_table", {"Eine Datentabelle ist ungültig.", "A data table is invalid."}},
{"unknown_table", {"Unbekannter Datenbereich.", "Unknown data table."}},
{"missing_asset", {"Das Bild fehlt im Datenpaket.", "The image is missing from the package."}},
{"unsafe_asset", {"Das Bild kann nicht übernommen werden.", "The image cannot be imported."}},
{"invalid_image", {"Das Bild konnte nicht gelesen werden.", "The image could not be decoded."}},
{"image_dimensions", {"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"image_dimensions",
{"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"invalid_transform",
{"Der Bildzuschnitt oder Drehwinkel ist ungültig.", "The image crop or rotation is invalid."}},
{"external_svg_resource",
@@ -367,7 +509,8 @@ std::string tr(const std::string &language, const std::string &key) {
"SVG."}},
{"image_encode_failed",
{"Das bearbeitete Bild konnte nicht erstellt werden.", "The edited image could not be created."}},
{"obw_only", {"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"obw_only",
{"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"preserve_source",
{"Bitte unter einem neuen Namen speichern. Der Classic-Import bleibt "
"erhalten.",
@@ -381,8 +524,10 @@ std::string tr(const std::string &language, const std::string &key) {
{"Eine Kennung fehlt oder ist mehrfach vorhanden.", "An identifier is missing or duplicated."}},
{"missing_reference", {"Ein verknüpfter Datensatz fehlt.", "A referenced record is missing."}},
{"attribute_range",
{"Ein Spielwert liegt außerhalb seines Wertebereichs.", "An attribute is outside its declared range."}},
{"unknown_attribute_set", {"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"Ein Spielwert liegt außerhalb seines Wertebereichs.",
"An attribute is outside its declared range."}},
{"unknown_attribute_set",
{"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"missing_name", {"Ein Name fehlt.", "A name is missing."}},
{"missing_birthday", {"Das Geburtsdatum ist unbekannt.", "The date of birth is unknown."}},
{"review_open", {"Eine Quellenfrage ist noch offen.", "A source decision is still open."}},
@@ -392,7 +537,8 @@ std::string tr(const std::string &language, const std::string &key) {
"The record is still referenced. Please update its links first."}},
{"record_missing", {"Der Datensatz wurde nicht gefunden.", "The record was not found."}},
{"immutable_id",
{"Kennungen können nicht nachträglich geändert werden.", "Identifiers cannot be changed after creation."}},
{"Kennungen können nicht nachträglich geändert werden.",
"Identifiers cannot be changed after creation."}},
{"stale_revision",
{"Die Daten wurden inzwischen geändert. Bitte die Ansicht "
"aktualisieren.",
@@ -404,7 +550,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"invalid_settings", {"Die Optionen sind ungültig.", "The options are invalid."}},
{"output_parent_missing", {"Der Zielordner existiert nicht.", "The output folder does not exist."}},
{"destination_exists", {"Die Zieldatei existiert bereits.", "The destination file already exists."}},
{"duplicate_entry", {"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"duplicate_entry",
{"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"server_failed",
{"MCP konnte nicht gestartet werden. Bitte den Port prüfen.",
"MCP could not be started. Please check the port."}},
+250
View File
@@ -0,0 +1,250 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/regulations.hpp"
#include "editor/world.hpp"
#include <algorithm>
namespace bmh::editor {
namespace {
Json object(const Json &value, const char *key) {
const auto found = value.find(key);
return found != value.end() && found->is_object() ? *found : Json::object();
}
Json array(const Json &value, const char *key) {
const auto found = value.find(key);
return found != value.end() && found->is_array() ? *found : Json::array();
}
std::optional<int> number(const Json &value) {
if (!value.is_number_integer() || value.get<double>() < 0 || value.get<double>() > 100000)
return {};
return value.get<int>();
}
int count_teams(const Json &comp) {
if (comp.value("members", Json()).is_array() && !comp["members"].empty())
return int(comp["members"].size());
for (const auto &stage : array(comp, "stages"))
if (auto value = number(stage.value("teams", Json())))
return *value;
return 0;
}
} // namespace
Json regulation_view(const World &world, const Json &args) {
const auto language = str(args, "language", "de"), search = folded(str(args, "search")),
nation = str(args, "nation"), chosen = str(args, "competition");
if (language != "de" && language != "en")
throw Error("invalid_change");
std::map<std::string, const Json *> competitions;
std::map<int, const Json *> indexed;
for (const auto &comp : world.rows("competitions")) {
competitions[str(comp, "id")] = &comp;
const auto legacy = object(comp, "x-legacy");
if (const auto index = number(legacy.value("league_index", Json()));
index && str(comp, "type") == "league")
indexed[*index] = &comp;
}
const Json *ladder = nullptr;
bool classic = false;
for (const auto &rule : world.rows("rules")) {
if (str(rule, "type") == "legacy_ladder")
ladder = &rule;
if (str(rule, "type") == "classic_runtime" &&
str(rule, "qualifications") == "classic-season-entrants@1")
classic = true;
}
auto target = [&](const std::string &id) {
return Json{{"id", id},
{"name", competitions.contains(id) ? world.title(*competitions.at(id), language) : id}};
};
std::map<std::string, Json> movement, qualification;
std::set<std::string> movement_known;
// Explicit OBW movement always takes precedence over compatibility policy.
for (const auto &[id, comp] : competitions) {
movement[id] = Json::array();
qualification[id] = Json::array();
if (comp->contains("movement") && (*comp)["movement"].is_array()) {
movement_known.insert(id);
for (const auto &definition : (*comp)["movement"]) {
const auto to = str(definition, "to");
const auto role = str(definition, "role");
std::string kind = role == "challenger" || role == "defender" || role == "incumbent"
? "playoff"
: "movement";
if (kind == "movement" && competitions.contains(to)) {
auto from_tier = number(comp->value("tier", Json()));
auto to_tier = number(competitions.at(to)->value("tier", Json()));
if (from_tier && to_tier && str(*competitions.at(to), "type") == "league")
kind = *to_tier < *from_tier ? "promotion"
: *to_tier > *from_tier ? "relegation"
: "movement";
}
movement[id].push_back({{"kind", kind},
{"ranks", definition.value("ranks", Json())},
{"targets", Json::array({target(to)})},
{"source", "declared"},
{"definition", definition}});
}
}
}
if (classic && ladder) {
auto span = [&](const char *first_key, const char *count_key, int group) {
std::vector<const Json *> result;
const auto first = ladder->value(first_key, Json()), count = ladder->value(count_key, Json());
if (!first.is_array() || !count.is_array() || size_t(group) >= first.size() ||
size_t(group) >= count.size())
return result;
const auto start = number(first[group]), length = number(count[group]);
if (!start || !length || *length < 1 || *length > 24)
return result;
for (int i = *start; i < *start + *length; ++i) {
if (!indexed.contains(i))
return std::vector<const Json *>{};
result.push_back(indexed.at(i));
}
return result;
};
// The versioned Classic ladder has four domestic movement groups.
// Its final group draws newcomers; below[3] is not a foreign league
// destination. License withdrawals can change the actual season result.
for (int group = 0; group < 4; ++group) {
const auto upper = span("first_league", "league_count", group);
const auto lower = group < 3 ? span("below", "below_count", group) : std::vector<const Json *>{};
if (upper.empty() || (group < 3 && lower.empty()))
continue;
int down_total = 0;
bool complete = true;
for (const auto *comp : upper) {
const auto down = number(object(*comp, "x-legacy").value("relegation_places", Json()));
if (!down || *down > count_teams(*comp)) {
complete = false;
break;
}
down_total += *down;
}
if (!complete)
continue;
Json destinations = Json::array(), origins = Json::array();
for (const auto *comp : lower)
destinations.push_back(target(str(*comp, "id")));
for (const auto *comp : upper)
origins.push_back(target(str(*comp, "id")));
for (const auto *comp : upper) {
const auto id = str(*comp, "id");
if (comp->contains("movement"))
continue;
movement_known.insert(id);
const int down = *number(object(*comp, "x-legacy")["relegation_places"]);
if (down)
movement[id].push_back({{"kind", "relegation"},
{"places", down},
{"ranks", {count_teams(*comp) - down + 1, count_teams(*comp)}},
{"targets", destinations},
{"newcomer_pool", group == 3},
{"pool_size", ladder->value("newcomer_count", Json())},
{"conditional_playoffs", lower.size() > 1},
{"source", "classic-ladder@1"}});
}
if (!lower.empty())
for (const auto *comp : lower) {
const auto id = str(*comp, "id");
if (comp->contains("movement"))
continue;
const bool playoffs = lower.size() > 1;
const int up = playoffs ? 1 : down_total;
if (up > count_teams(*comp) || down_total % int(lower.size()) != 0)
continue;
movement_known.insert(id);
if (up)
movement[id].push_back({{"kind", "promotion"},
{"places", up},
{"ranks", {1, up}},
{"targets", origins},
{"source", "classic-ladder@1"}});
if (playoffs)
movement[id].push_back({{"kind", "playoff"},
{"ranks", nullptr},
{"selector", "classic-playoff-winner"},
{"conditional_playoffs", true},
{"targets", origins},
{"source", "classic-ladder@1"}});
}
}
}
auto slots = [&](const std::string &to, const std::string &stage, const Json &definitions) {
if (!definitions.is_array())
return;
for (const auto &definition : definitions) {
const auto from = str(definition, "from"), holder = str(definition, "holder");
// Fixed team lists are already participants, not a qualification
// rule. Keep the untouched stages available separately below.
if (from.empty() && holder.empty() && !definition.contains("winner") &&
!definition.contains("resolver"))
continue;
const auto destination = str(definition, "to", to);
const Json rule{
{"from", target(from)},
{"to", target(destination)},
{"stage", str(definition, "stage", stage)},
{"definition", definition},
{"source", str(definition, "resolver").empty() ? "declared" : str(definition, "resolver")}};
qualification[destination].push_back(rule);
if (competitions.contains(from) && from != destination)
qualification[from].push_back(rule);
}
};
for (const auto &[id, comp] : competitions) {
slots(id, "", comp->value("slots", Json::array()));
for (const auto &stage : array(*comp, "stages"))
slots(id, str(stage, "id"), stage.value("slots", Json::array()));
}
Json items = Json::array();
for (const auto &[id, comp] : competitions) {
const auto label = world.title(*comp, language);
if ((!chosen.empty() && id != chosen) || (!nation.empty() && str(*comp, "nation") != nation) ||
(!search.empty() && folded(label).find(search) == std::string::npos &&
folded(id).find(search) == std::string::npos))
continue;
Json policy;
if (classic) {
const auto index = number(object(*comp, "x-legacy").value("league_index", Json()));
const bool declared =
std::any_of(qualification[id].begin(), qualification[id].end(),
[](const auto &rule) { return str(rule, "source") != "classic-entry@1"; });
// Registry for classic-season-entrants@1, the named format policy
// consumed by the existing Classic adapter. These quotas are not
// the historical x-legacy.europe_places prediction/colouring field.
if (!declared && index && (*index == 0 || (*index >= 5 && *index <= 8)))
policy = {{"id", "classic-season-entrants@1"},
{"uefa_base_places", *index == 8 ? 3 : 4},
{"champion", true},
{"cup_winner_or_finalist", true},
{"titleholder_adjustments", true}};
else if (!declared &&
str(object(*comp, "classic"), "qualification") == "classic-season-entrants@1")
policy = {{"id", "classic-season-entrants@1"}, {"runtime_participants", true}};
if (index && *index >= 5)
movement_known.insert(id); // Closed foreign Classic leagues.
}
items.push_back({{"id", id},
{"name", label},
{"nation", str(*comp, "nation")},
{"type", str(*comp, "type")},
{"tier", comp->value("tier", Json())},
{"teams", count_teams(*comp)},
{"movement_defined", movement_known.contains(id)},
{"movement", movement[id]},
{"qualification", qualification[id]},
{"classic_qualification", policy},
{"stages", array(*comp, "stages")},
{"record", *comp}});
}
std::stable_sort(items.begin(), items.end(), [](const auto &a, const auto &b) {
const auto av = folded(str(a, "name")), bv = folded(str(b, "name"));
return av == bv ? str(a, "id") < str(b, "id") : av < bv;
});
return {{"read_only", true},
{"items", items},
{"rules", world.rows("rules")},
{"classic_policy", classic},
{"date", world.manifest.value("start_date", Json())}};
}
} // namespace bmh::editor
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
class World;
// Presentation of declared rules and versioned Classic policy, never a season
// simulation or an editable replacement for world/rules.json.
Json regulation_view(const World &, const Json &args);
} // namespace bmh::editor
+21
View File
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/session.hpp"
#include "content/digest.hpp"
#include "editor/comparison.hpp"
#include "editor/images.hpp"
#include "editor/regulations.hpp"
#include <algorithm>
#include <limits>
@@ -435,6 +437,20 @@ Json Session::execute(const std::string &command, const Json &args) {
auto &w = world();
if (command == "list")
return w.query(args);
if (command == "compare") {
const Json key{{"table", str(args, "table", "players")},
{"attribute_set", str(args, "attribute_set")},
{"language", str(args, "language", "de")}};
if (comparison_revision_ != revision_ || comparison_key_ != key.dump()) {
auto data = comparison_data(w, key);
comparison_cache_ = std::move(data);
comparison_key_ = key.dump();
comparison_revision_ = revision_;
}
auto result = query_comparison(comparison_cache_, args);
result["revision"] = revision_;
return result;
}
if (command == "get") {
auto name = str(args, "table"), id = str(args, "id");
const auto *found = name == "manifest" ? &w.manifest : w.find(name, id);
@@ -444,6 +460,11 @@ Json Session::execute(const std::string &command, const Json &args) {
}
if (command == "rules")
return w.rows("rules");
if (command == "regulations") {
auto result = regulation_view(w, args);
result["revision"] = revision_;
return result;
}
if (command == "validate")
return {{"diagnostics", w.validate()}, {"revision", revision_}};
if (command == "history") {
+3
View File
@@ -34,6 +34,9 @@ class Session {
fs::path saved_path_;
fs::file_time_type saved_time_{};
uint64_t saved_size_ = 0;
Json comparison_cache_;
std::string comparison_key_;
std::optional<uint64_t> comparison_revision_;
World &world();
bool dirty() const;
Json info() const;
+581 -7
View File
@@ -14,6 +14,7 @@
#include <deque>
#include <functional>
#include <future>
#include <iomanip>
#include <nfd.hpp>
#include <sstream>
@@ -142,6 +143,12 @@ class EditorUi final : public Rml::EventListener {
std::map<std::string, Json> lookup_;
std::string page_ = "overview", selected_id_, search_, nation_, league_, team_, sort_ = "name", remembered_;
bool descending_ = false;
std::string comparison_table_ = "players", comparison_set_, comparison_sort_ = "name";
bool comparison_descending_ = false;
Json comparison_;
std::map<std::string, std::vector<std::string>> comparison_columns_;
bool regulations_game_ = false, regulations_source_ = false;
std::string regulation_id_, game_rule_id_;
int offset_ = 0;
size_t total_ = 0;
struct Field {
@@ -206,6 +213,8 @@ class EditorUi final : public Rml::EventListener {
{"clubs", "M4 3h16v10c0 5-8 9-8 9S4 18 4 13zM8 8h8M8 12h8"},
{"players", "M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0M4 22v-3c0-8 16-8 16 0v3"},
{"roster", "M3 3h18v18H3zM9 3v18M3 9h18M3 15h18"},
{"comparison", "M4 20h17M7 17v-5M12 17V7M17 17V3"},
{"regulations", "M5 3h14v18H5zM8 7h8M8 11h8M8 15h5"},
{"stadiums", "M3 8c0-7 18-7 18 0v8c0 7-18 7-18 0zM3 8c0 7 18 7 18 0M8 "
"13v7M16 13v7"},
{"staff", "M5 22V3h13l-4 5 4 5H5"},
@@ -259,7 +268,7 @@ class EditorUi final : public Rml::EventListener {
lookup_[str(row, "id")] = row;
}
std::string choices(const std::string &name, const std::string &chosen, const std::string &empty = "",
const std::string &nation = "") const {
const std::string &nation = "", const std::string &competition = "") const {
std::string result =
"<option value=\"\"" + std::string(chosen.empty() ? " selected" : "") + ">" + escaped(empty) + "</option>";
std::vector<std::pair<std::string, std::string>> values;
@@ -271,6 +280,9 @@ class EditorUi final : public Rml::EventListener {
: id.starts_with("stadium:");
if (!matches || (!nation.empty() && str(row, "nation") != nation && id != chosen))
continue;
if (name == "clubs" && !competition.empty() && str(row, "competition") != competition &&
id != chosen)
continue;
values.emplace_back(id, title(row));
}
std::stable_sort(values.begin(), values.end(),
@@ -394,14 +406,17 @@ class EditorUi final : public Rml::EventListener {
button("save", t("save"), "primary", info_.value("loaded", false) ? "" : "disabled") +
button("options", t("options"), "quiet"));
std::string nav;
for (const std::string name : {"overview", "nations", "competitions", "clubs", "players", "roster", "stadiums",
"staff", "assets", "review", "changes"})
for (const std::string name :
{"overview", "nations", "competitions", "clubs", "players", "roster", "comparison",
"regulations", "stadiums", "staff", "assets", "review", "changes"})
nav += "<button class=\"nav " + std::string(name == page_ ? "selected" : "") +
"\" data-action=\"navigate\" data-value=\"" + name + "\">" + icon(name) + "<span>" +
escaped(t(name)) + "</span></button>";
html("navigation", nav);
label("page-kicker", "OpenBMH / " + t(page_));
label("page-title", t(page_));
label("page-title", t(page_ == "comparison" ? "comparison_title"
: page_ == "regulations" ? "regulations_title"
: page_));
label("page-subtitle", page_ == "roster" ? t("roster_hint")
: page_ == "review" ? t("review_hint")
: t("subtitle_" + page_));
@@ -590,6 +605,10 @@ class EditorUi final : public Rml::EventListener {
html("page-actions", page_ == "review"
? button("validate", t("validate"))
: button("duplicate", t("duplicate")) + button("add", t("add"), "primary"));
if (table() == "players" || table() == "clubs" || table() == "competitions")
html("page-actions", button("compare-open", t("comparison")) +
button("duplicate", t("duplicate")) +
button("add", t("add"), "primary"));
std::string toolbar = "<input id=\"search\" type=\"text\" value=\"" + escaped(search_) + "\" placeholder=\"" +
escaped(t("search")) + "\"/>";
if (table() == "clubs" || table() == "players" || table() == "competitions")
@@ -679,6 +698,484 @@ class EditorUi final : public Rml::EventListener {
button("next", t("next"), "quiet", size_t(offset_) + listed_.size() < total_ ? "" : "disabled") +
"</div>");
}
std::string comparison_number(const Json &value, bool salary = false) const {
if (!value.is_number())
return "—";
std::string result;
if (salary) {
const auto currency = comparison_.value("currency", Json());
if (!currency.is_object() || str(currency, "code").empty() ||
!currency.value("minor_units", Json()).is_number_integer())
return t("unknown");
const auto decimals = currency["minor_units"].get<int>();
if (decimals < 0 || decimals > 9)
return t("unknown");
auto digits = std::to_string(value.get<int64_t>());
while (digits.size() <= size_t(decimals))
digits.insert(digits.begin(), '0');
const auto fraction = decimals ? digits.substr(digits.size() - decimals) : "";
digits.resize(digits.size() - decimals);
for (int i = int(digits.size()) - 3; i > 0; i -= 3)
digits.insert(size_t(i), options_.language == "de" ? "." : ",");
result = digits + (decimals ? (options_.language == "de" ? "," : ".") + fraction : "");
} else if (value.is_number_integer())
result = value.dump();
else {
std::ostringstream stream;
stream.imbue(std::locale::classic());
stream << std::fixed << std::setprecision(1) << value.get<double>();
result = stream.str();
if (options_.language == "de")
std::replace(result.begin(), result.end(), '.', ',');
}
return result;
}
std::string comparison_attribute(const std::string &key) const {
// In FC-derived systems strength means physical power, not overall.
if (key == "strength")
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == "overall")
return t("physical_strength");
return t(key);
}
std::vector<std::string> &comparison_columns() {
auto key = str(comparison_, "attribute_set");
if (!comparison_columns_.contains(key)) {
auto &columns = comparison_columns_[key];
for (const std::string preferred :
{"overall", "potential", "strength", "technique", "form", "condition", "bonus"}) {
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == preferred && columns.size() < 5)
columns.push_back(preferred);
}
if (columns.empty())
for (const auto &field : comparison_["attributes"])
if (columns.size() < 5)
columns.push_back(str(field, "key"));
}
return comparison_columns_.at(key);
}
void comparison_choose_columns() {
std::string body = "<p>" + escaped(t("comparison_columns_hint")) + "</p><div class=\"button-row\">" +
button("compare-all-columns", t("all_columns")) +
button("compare-no-columns", t("no_columns")) +
"</div><div class=\"comparison-choices\">";
const auto &chosen = comparison_columns();
size_t index = 0;
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
const bool checked = std::find(chosen.begin(), chosen.end(), key) != chosen.end();
const auto id = "comparison-column-" + std::to_string(index++);
body += "<label for=\"" + id + "\"><input type=\"checkbox\" id=\"" + id + "\"" +
(checked ? " checked" : "") + "/><span>" + escaped(comparison_attribute(key)) + "</span></label>";
}
modal(
t("comparison_columns"), body + "</div>", t("apply"),
[this] {
auto &chosen = comparison_columns();
chosen.clear();
size_t index = 0;
for (const auto &field : comparison_["attributes"]) {
if (el("comparison-column-" + std::to_string(index++))->HasAttribute("checked"))
chosen.push_back(str(field, "key"));
}
close_modal();
needs_refresh_ = true;
},
true, true);
}
void comparison() {
if (!info_.value("loaded", false)) {
overview();
return;
}
Json args{{"table", comparison_table_},
{"language", options_.language},
{"attribute_set", comparison_set_},
{"search", search_},
{"nation", nation_},
{"competition", league_},
{"team", team_},
{"sort", comparison_sort_},
{"descending", comparison_descending_},
{"offset", offset_},
{"limit", 200}};
try {
comparison_ = session_.execute("compare", args);
} catch (const Error &error) {
if (error.code != "invalid_attribute_set" && error.code != "invalid_comparison_sort")
throw;
// A world replaced through MCP can have different attribute sets.
comparison_set_.clear();
comparison_sort_ = "name";
args["attribute_set"] = "";
args["sort"] = "name";
comparison_ = session_.execute("compare", args);
}
listed_ = comparison_["items"];
total_ = comparison_["total"].get<size_t>();
if (listed_.empty() && offset_ > 0) {
offset_ = total_ ? int((total_ - 1) / 200 * 200) : 0;
args["offset"] = offset_;
comparison_ = session_.execute("compare", args);
listed_ = comparison_["items"];
}
const bool players = comparison_table_ == "players", leagues = comparison_table_ == "leagues";
std::string tabs;
for (const std::string scope : {"players", "clubs", "leagues"})
tabs += button("compare-scope", t(scope == "clubs" ? "teams" : scope),
scope == comparison_table_ ? "primary" : "", "data-value=\"" + scope + "\"");
html("page-actions", tabs);
std::string toolbar = "<input id=\"search\" type=\"text\" value=\"" + escaped(search_) +
"\" placeholder=\"" + escaped(t("search")) +
"\"/><select id=\"filter-nation\">" +
choices("nations", nation_, t("all_nations")) + "</select>";
if (!leagues)
toolbar += "<select id=\"filter-league\">" +
choices("competitions", league_, t("all_leagues"), nation_) + "</select>";
if (players)
toolbar += "<select id=\"filter-team\">" +
choices("clubs", team_, t("all_clubs"), nation_, league_) + "</select>";
html("toolbar", toolbar);
const auto automatic_profile =
comparison_["attribute_sets"].size() == 1
? str(comparison_, "attribute_set") + " · " + t("comparison_all_players")
: t("comparison_all_sets");
std::string profiles = "<option value=\"\"" +
std::string(comparison_set_.empty() ? " selected" : "") + ">" +
escaped(automatic_profile) + "</option>";
for (const auto &profile : comparison_["attribute_sets"]) {
const auto id = str(profile, "id");
if (!id.empty())
profiles += "<option value=\"" + escaped(id) + "\"" +
(id == comparison_set_ ? " selected" : "") + ">" + escaped(id) + " · " +
profile["players"].dump() + "</option>";
}
std::string body =
"<div class=\"comparison-layout\"><div class=\"comparison-bar\"><label>" +
escaped(t("attribute_set")) + "</label><select id=\"comparison-set\">" + profiles + "</select>" +
button("compare-columns", t("comparison_columns"), "",
comparison_["attributes"].empty() ? "disabled" : "") +
"<span>" + escaped(t(players ? "comparison_player_values" : "comparison_mean_values")) +
"</span></div>";
int width = 0;
std::string header;
struct Column {
std::string key, label;
int width;
};
std::vector<Column> columns{{"name",
t(players ? "players"
: leagues ? "leagues"
: "teams"),
230},
{"context",
t(players ? "team"
: leagues ? "nation"
: "competition"),
players ? 200 : 180}};
if (players)
columns.push_back({"positions", t("positions"), 95});
else {
if (leagues)
columns.push_back({"club_count", t("clubs"), 80});
columns.push_back({"player_count", t("players"), 85});
}
const auto &chosen = comparison_columns();
std::string primary_attribute;
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
if (std::find(chosen.begin(), chosen.end(), key) != chosen.end() &&
(primary_attribute.empty() || key == "strength" || key == "overall"))
primary_attribute = key;
if (primary_attribute == "overall")
break;
}
if (!primary_attribute.empty())
columns.push_back(
{"attributes." + primary_attribute, comparison_attribute(primary_attribute), 120});
const auto currency = str(comparison_.value("currency", Json()), "code", "?");
columns.push_back({players ? "salary" : "salary_total",
t(players ? "salary_season" : "salary_total") + " · " + currency, 165});
if (!players) {
columns.push_back({"salary_average", t("salary_average") + " · " + currency, 165});
columns.push_back({"salary_known", t("salary_coverage"), 105});
}
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
if (key != primary_attribute && std::find(chosen.begin(), chosen.end(), key) != chosen.end())
columns.push_back({"attributes." + key, comparison_attribute(key), 135});
}
for (const auto &column : columns) {
width += column.width;
const bool sortable = column.key != "context" && column.key != "positions";
std::string caption = escaped(column.label);
if (column.key == comparison_sort_)
caption += "<span class=\"comparison-direction" +
std::string(comparison_descending_ ? "" : " ascending") + "\"></span>";
if (column.key.starts_with("attributes."))
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == column.key.substr(11) && field["min"].is_number() &&
field["max"].is_number())
caption += "<small>" + field["min"].dump() + "–" + field["max"].dump() + "</small>";
header += "<button class=\"comparison-cell" +
std::string(column.key == "name" || column.key == "context" ? " text" : "") +
"\" style=\"width:" + std::to_string(column.width) + "dp\"" +
(sortable ? " data-action=\"compare-sort\" data-value=\"" + escaped(column.key) + "\""
: " disabled") +
">" + caption + "</button>";
}
std::string rows;
for (const auto &row : listed_) {
rows += "<button class=\"comparison-row\" data-action=\"compare-edit\" data-value=\"" +
escaped(str(row, "id")) + "\">";
for (const auto &column : columns) {
std::string cell, hint;
if (column.key == "name") {
cell = "<span class=\"comparison-name-text\">" + escaped(str(row, "name")) + "</span>";
hint = str(row, "name") + " · " + str(row, "id");
} else if (column.key == "context")
cell = escaped(ref(row, players ? "team" : leagues ? "nation" : "competition"));
else if (column.key == "positions") {
for (const auto &position : row["positions"])
if (position.is_string())
cell += (cell.empty() ? "" : " / ") + escaped(t(position.get<std::string>()));
} else if (column.key.starts_with("attributes.")) {
const auto key = column.key.substr(11);
cell = comparison_number(row["attributes"].value(key, Json()));
if (!players)
hint =
row["attribute_counts"].value(key, size_t(0)) == row["player_count"].get<size_t>()
? t("comparison_mean_values")
: std::to_string(row["attribute_counts"].value(key, size_t(0))) + "/" +
row["player_count"].dump() + " · " + t("comparison_known_values");
} else if (column.key == "salary_known") {
cell = row["salary_known"].dump() + " / " + row["player_count"].dump();
hint = row["salary_unknown"].dump() + " · " + t("salary_missing") + "; " +
row["salary_ambiguous"].dump() + " · " + t("salary_ambiguous");
} else {
const bool salary = column.key.starts_with("salary");
cell = comparison_number(row.value(column.key, Json()), salary);
if (salary && !players && row.value(column.key, Json()).is_number() &&
!row.value("salary_complete", false))
cell += " *";
if (salary && players && row.value("salary_ambiguous", 0))
hint = t("salary_ambiguous");
}
rows += "<span class=\"comparison-cell" +
std::string(column.key == "name" || column.key == "context" ? " text" : "") +
"\" style=\"width:" + std::to_string(column.width) + "dp\" title=\"" + escaped(hint) +
"\">" + cell + "</span>";
}
rows += "</button>";
}
if (rows.empty())
rows = "<div class=\"empty\">" + escaped(t("empty")) + "</div>";
body += "<div class=\"list-panel comparison-panel\"><div class=\"comparison-x\" "
"id=\"comparison-x\"><div class=\"comparison-table\" style=\"width:" +
std::to_string(width + 20) + "dp\"><div class=\"comparison-head\">" + header +
"</div><div class=\"comparison-body\" id=\"table-scroll\">" + rows +
"</div></div></div></div>";
body += "<div class=\"comparison-note\">" + escaped(t("comparison_salary_note")) + " · " +
escaped(str(comparison_, "date")) + "<br/>" + escaped(t("comparison_scope_note"));
if (comparison_.value("mixed_attribute_sets", false))
body += "<br/>" + escaped(t("comparison_mixed_note"));
if (comparison_.value("excluded_players", size_t(0)))
body += " · " + comparison_["excluded_players"].dump() + " " + escaped(t("comparison_excluded"));
if (comparison_.value("fictional_completion", false))
body += "<br/>" + escaped(t("comparison_fictional"));
html("page-content", body + "</div></div>");
html("pagination", "<span>" + std::to_string(total_) + " " + escaped(t("records")) + " · " +
escaped(t("comparison_sort_hint")) + "</span><div class=\"button-row\">" +
button("previous", t("previous"), "quiet", offset_ > 0 ? "" : "disabled") +
"<span>" + std::to_string(offset_ + (total_ ? 1 : 0)) + "–" +
std::to_string(offset_ + listed_.size()) + "</span>" +
button("next", t("next"), "quiet",
size_t(offset_) + listed_.size() < total_ ? "" : "disabled") +
"</div>");
}
std::string regulation_ranks(const Json &ranks) const {
if (!ranks.is_array() || ranks.empty())
return t("regulation_unspecified");
std::string result = t("regulation_rank") + " " + text(ranks.front());
if (ranks.size() == 2 && ranks.front() != ranks.back())
result += "–" + text(ranks.back());
else if (ranks.size() > 2)
result = t("regulation_rank") + " " + ranks.dump();
return result;
}
std::string regulation_selector(const Json &definition) const {
if (definition.contains("ranks"))
return regulation_ranks(definition["ranks"]);
for (auto key : {"winner", "runner_up", "next_unqualified"})
if (definition.value(key, Json()) == true)
return t("regulation_" + std::string(key));
if (definition.contains("holder"))
return t("regulation_holder") + " · " + ref(definition, "holder");
if (str(definition, "from") == "coefficient")
return t("regulation_coefficient");
if (definition.contains("resolver"))
return t("regulation_runtime");
return t("regulation_unspecified");
}
std::string regulation_type(const Json &row, const std::string &prefix) const {
const auto type = str(row, "type"), key = prefix + type;
const auto translated = t(key);
return translated == key ? type : translated;
}
void regulations() {
html("page-actions", "<span class=\"badge\">" + escaped(t("regulation_readonly")) + "</span>");
html("pagination", "");
html("toolbar",
button("regulations-tab", t("regulation_competitions"), regulations_game_ ? "" : "primary",
"data-value=\"competitions\"") +
button("regulations-tab", t("regulation_game"), regulations_game_ ? "primary" : "",
"data-value=\"game\"") +
"<input id=\"search\" type=\"text\" value=\"" + escaped(search_) + "\" placeholder=\"" +
escaped(t("search")) + "\"/>" +
(regulations_game_ ? ""
: "<select id=\"filter-nation\">" +
choices("nations", nation_, t("all_nations")) + "</select>"));
if (!info_.value("loaded", false)) {
html("page-content", "<div class=\"empty\">" + escaped(t("welcome_hint")) + "</div>");
return;
}
const auto view = session_.execute(
"regulations", {{"language", options_.language}, {"search", search_}, {"nation", nation_}});
Json rows = regulations_game_ ? view["rules"] : view["items"];
if (regulations_game_ && !search_.empty()) {
Json filtered = Json::array();
for (const auto &row : rows)
if (folded(str(row, "id") + " " + str(row, "type")).find(folded(search_)) !=
std::string::npos)
filtered.push_back(row);
rows = std::move(filtered);
}
auto &chosen = regulations_game_ ? game_rule_id_ : regulation_id_;
const Json *selected = nullptr;
for (const auto &row : rows)
if (str(row, "id") == chosen)
selected = &row;
if (!selected && !rows.empty()) {
selected = &rows.front();
chosen = str(*selected, "id");
}
std::string body = "<div class=\"regulation-layout\"><div class=\"list-panel regulation-list\"><div "
"class=\"table-scroll\">";
for (const auto &row : rows) {
const auto id = str(row, "id");
body += "<button class=\"regulation-choice " + std::string(id == chosen ? "primary" : "quiet") +
"\" data-action=\"regulation-select\" data-value=\"" + escaped(id) + "\">" +
escaped(regulations_game_ ? regulation_type(row, "rule_type_") : str(row, "name")) +
"<small>" + escaped(regulations_game_ ? id : ref(row, "nation")) + "</small></button>";
}
body += "</div></div><div class=\"list-panel regulation-detail\"><div class=\"regulation-scroll\">";
auto section = [&](const std::string &key, const std::string &content) {
return "<div class=\"regulation-section\"><h2>" + escaped(t(key)) + "</h2>" + content + "</div>";
};
auto paragraph = [&](const std::string &value) { return "<p>" + escaped(value) + "</p>"; };
auto source = [&](const Json &value) {
return "<div class=\"source-json\">" + escaped(value.dump(2)) + "</div>";
};
if (!selected)
body += "<div class=\"empty\">" + escaped(t("empty")) + "</div>";
else if (regulations_game_) {
body += "<h2>" + escaped(regulation_type(*selected, "rule_type_")) + "</h2><small>" +
escaped(chosen) + "</small>" + paragraph(t("regulation_preserved")) + source(*selected);
} else {
const auto &row = *selected;
body += "<h2>" + escaped(str(row, "name")) + "</h2><small>" + escaped(chosen) + "</small>" +
paragraph(ref(row, "nation") + " · " + regulation_type(row, "regulation_type_") + " · " +
std::to_string(row.value("teams", 0)) + " " + t("teams"));
std::string movement;
for (const auto &entry : row["movement"]) {
std::string destinations;
for (const auto &target : entry["targets"]) {
if (!destinations.empty())
destinations += " / ";
destinations += str(target, "name");
}
if (entry.value("newcomer_pool", false))
destinations = t("regulation_amateur_pool");
movement +=
"<div class=\"regulation-clause\"><strong>" +
escaped(t("regulation_" + str(entry, "kind"))) + "</strong>" +
paragraph((str(entry, "selector") == "classic-playoff-winner"
? t("regulation_playoff_winner")
: regulation_ranks(entry.value("ranks", Json()))) +
" · " + t("regulation_to") + " " + destinations) +
"<small>" +
escaped(t(str(entry, "source") == "declared" ? "regulation_declared"
: "regulation_classic")) +
"</small>" +
(entry.value("conditional_playoffs", false) ? paragraph(t("regulation_classic_playoffs"))
: "") +
(regulations_source_ ? source(entry) : "") + "</div>";
}
if (movement.empty())
movement = paragraph(
t(row.value("movement_defined", false) ? "regulation_closed" : "regulation_unspecified"));
if (std::any_of(row["movement"].begin(), row["movement"].end(),
[](const auto &entry) { return str(entry, "source") == "classic-ladder@1"; }))
movement += "<small>" + escaped(t("regulation_classic_movement_note")) + "</small>";
body += section("regulation_movement_title", movement);
std::string qualification;
const auto policy = row["classic_qualification"];
if (!policy.is_null()) {
qualification = "<div class=\"regulation-clause\"><span class=\"badge\">" +
escaped(t("regulation_classic")) + "</span>" +
paragraph(t("regulation_classic_intro"));
if (policy.value("runtime_participants", false))
qualification += paragraph(t("regulation_runtime"));
else
qualification +=
paragraph(t("regulation_classic_champion")) + paragraph(t("regulation_classic_cup")) +
paragraph("UEFA-Cup · " + std::to_string(policy.value("uefa_base_places", 0)) + " " +
t("regulation_classic_uefa")) +
paragraph(t("regulation_classic_holders"));
qualification += "<small>classic-season-entrants@1</small></div>";
}
for (const auto &entry : row["qualification"]) {
const auto &definition = entry["definition"];
if (!policy.is_null() && str(entry, "source") == "classic-entry@1")
continue;
auto from = str(entry["from"], "name");
auto to = str(entry["to"], "name");
qualification += "<div class=\"regulation-clause\"><strong>" +
escaped((from.empty() ? "" : from + " · " + t("regulation_to") + " ") + to) +
"</strong>" + paragraph(regulation_selector(definition));
if (definition.contains("fallback"))
qualification +=
paragraph(t("regulation_fallback") + ": " + ref(definition["fallback"], "from") +
" · " + regulation_selector(definition["fallback"]));
if (!str(entry, "stage").empty())
qualification +=
"<small>" + escaped(t("regulation_stage") + ": " + str(entry, "stage")) + "</small>";
qualification += (regulations_source_ ? source(definition) : "") + "</div>";
}
if (qualification.empty())
qualification = paragraph(t("regulation_unspecified"));
body += section("regulation_qualification_title", qualification);
std::string stages;
for (auto stage : row["stages"]) {
// Participants can be large; the source toggle exposes them.
if (!regulations_source_) {
stage.erase("slots");
stage.erase("fixtures");
}
stages += source(stage);
}
if (stages.empty())
stages = paragraph(t("regulation_unspecified"));
body +=
section("regulation_stages", stages) +
button("regulation-source",
t(regulations_source_ ? "regulation_hide_source" : "regulation_show_source"), "quiet");
if (regulations_source_)
body += source(row["record"]);
}
html("page-content", body + "</div></div></div>");
}
void changes() {
html("toolbar", "");
html("pagination", "");
@@ -698,6 +1195,8 @@ class EditorUi final : public Rml::EventListener {
html("page-content", body + "</div>");
}
void refresh() {
const float comparison_scroll =
doc_->GetElementById("comparison-x") ? el("comparison-x")->GetScrollLeft() : 0;
const auto *focus = context_->GetFocusElement();
const bool search_focused = focus && focus->GetId() == "search";
int selection_start = 0, selection_end = 0;
@@ -716,8 +1215,16 @@ class EditorUi final : public Rml::EventListener {
overview();
else if (page_ == "changes")
changes();
else if (page_ == "comparison")
comparison();
else if (page_ == "regulations")
regulations();
else
records();
if (page_ == "comparison" && doc_->GetElementById("comparison-x")) {
context_->Update();
el("comparison-x")->SetScrollLeft(comparison_scroll);
}
if (search_focused && doc_->GetElementById("search")) {
auto *input = dynamic_cast<Rml::ElementFormControlInput *>(el("search"));
input->Focus();
@@ -983,9 +1490,70 @@ class EditorUi final : public Rml::EventListener {
selected_id_.clear();
offset_ = 0;
search_.clear();
if (arg == "comparison" || arg == "regulations") {
nation_.clear();
league_.clear();
team_.clear();
}
needs_refresh_ = true;
});
else if (action == "select")
else if (action == "regulations-tab") {
regulations_game_ = arg == "game";
search_.clear();
nation_.clear();
needs_refresh_ = true;
} else if (action == "regulation-select") {
(regulations_game_ ? game_rule_id_ : regulation_id_) = arg;
needs_refresh_ = true;
} else if (action == "regulation-source") {
regulations_source_ = !regulations_source_;
needs_refresh_ = true;
} else if (action == "compare-open" || action == "compare-scope")
leave_fields([this, action, arg] {
comparison_table_ =
action == "compare-open" ? (table() == "competitions" ? "leagues" : table()) : arg;
page_ = "comparison";
fields_.clear();
selected_id_.clear();
search_.clear();
nation_.clear();
league_.clear();
team_.clear();
offset_ = 0;
comparison_sort_ = "name";
comparison_descending_ = false;
needs_refresh_ = true;
});
else if (action == "compare-sort") {
comparison_descending_ = arg == comparison_sort_ ? !comparison_descending_ : true;
comparison_sort_ = arg;
offset_ = 0;
needs_refresh_ = true;
} else if (action == "compare-columns")
comparison_choose_columns();
else if (action == "compare-all-columns" || action == "compare-no-columns") {
for (size_t i = 0; i < comparison_["attributes"].size(); ++i) {
auto *checkbox = el("comparison-column-" + std::to_string(i));
if (action == "compare-all-columns")
checkbox->SetAttribute("checked", "");
else
checkbox->RemoveAttribute("checked");
}
} else if (action == "compare-set") {
if (value("comparison-set") != comparison_set_) {
comparison_set_ = value("comparison-set");
comparison_sort_ = "name";
offset_ = 0;
needs_refresh_ = true;
}
} else if (action == "compare-edit") {
page_ = comparison_table_ == "leagues" ? "competitions" : comparison_table_;
selected_id_ = arg;
sort_ = "name";
offset_ = 0;
search_.clear();
needs_refresh_ = true;
} else if (action == "select")
leave_fields([this, arg] {
selected_id_ = arg;
needs_refresh_ = true;
@@ -1061,9 +1629,11 @@ class EditorUi final : public Rml::EventListener {
} else if (action == "sort") {
descending_ = arg == sort_ ? !descending_ : false;
sort_ = arg;
offset_ = 0;
needs_refresh_ = true;
} else if (action == "next" || action == "previous") {
offset_ = std::max(0, offset_ + (action == "next" ? 1 : -1) * (roster24_ ? 24 : 200));
offset_ = std::max(0, offset_ + (action == "next" ? 1 : -1) *
(page_ != "comparison" && roster24_ ? 24 : 200));
needs_refresh_ = true;
} else if (action == "filters") {
const auto next_nation = doc_->GetElementById("filter-nation") ? value("filter-nation") : "";
@@ -1075,6 +1645,7 @@ class EditorUi final : public Rml::EventListener {
if (next_nation == nation_ && next_league == league_ && next_team == team_ && next_search == search_)
return;
auto old_nation = nation_;
auto old_league = league_;
nation_ = next_nation;
league_ = next_league;
team_ = next_team;
@@ -1082,7 +1653,8 @@ class EditorUi final : public Rml::EventListener {
if (old_nation != nation_) {
league_.clear();
team_.clear();
}
} else if (old_league != league_)
team_.clear();
selected_id_.clear();
offset_ = 0;
needs_refresh_ = true;
@@ -1270,6 +1842,8 @@ class EditorUi final : public Rml::EventListener {
auto id = target->GetId();
if (id.starts_with("filter-") || id == "search")
pending_.emplace_back("filters", "");
else if (id == "comparison-set")
pending_.emplace_back("compare-set", "");
else if (id == "image-aspect")
pending_.emplace_back("aspect", "");
else if (id.starts_with("image-") && id != "edit-preview")
+11
View File
@@ -532,6 +532,17 @@ World World::demo() {
{"attribute_set", "demo@1"},
{"attributes",
{{"strength", 68 + (n % 15)}, {"technique", 65 + n % 20}, {"condition", 90}, {"form", 70}}}});
// Synthetic per-season salaries make the comparison demo useful.
// The last player deliberately has no known contract.
if (n != 25)
w.rows("contracts")
.push_back({{"id", "contract:demo-" + std::to_string(i * 26 + n)},
{"name", "Demo contract"},
{"person", "player:demo-" + std::to_string(i * 26 + n)},
{"team", id},
{"start", "2026-07-01"},
{"end", "2027-06-30"},
{"salary", (40000 + 5000 * n + 10000 * i) * 100}});
}
}
w.rows("staff").push_back({{"id", "staff:referee-demo"},
+258
View File
@@ -0,0 +1,258 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/mcp.hpp"
#include "editor/session.hpp"
#include <cmath>
#include <iostream>
#include <limits>
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool value, const char *message) {
++checks;
if (!value)
throw std::runtime_error(message);
}
template <class Fn> void rejects(const char *code, Fn fn) {
try {
fn();
} catch (const Error &error) {
check(error.code == code, "unexpected rejection");
return;
}
throw std::runtime_error(std::string("accepted: ") + code);
}
Json find(const Json &items, const std::string &id) {
for (const auto &row : items)
if (str(row, "id") == id)
return row;
throw std::runtime_error("missing fixture row " + id);
}
World fixture() {
auto world = World::blank("Synthetic comparison");
world.rows("nations").push_back({{"id", "nation:de"}, {"name", "Testland"}});
world.rows("competitions") = Json::array({{{"id", "comp:first"},
{"name", {{"de", "Testliga"}, {"en", "Test league"}}},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:north", "club:south"}}},
{{"id", "comp:empty"},
{"name", "Empty league"},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:empty"}}},
{{"id", "comp:cup"},
{"name", "Not a league"},
{"nation", "nation:de"},
{"type", "cup"},
{"members", {"club:north"}}}});
for (const std::string id : {"north", "south", "empty"})
world.rows("clubs").push_back(
{{"id", "club:" + id}, {"name", id}, {"type", "club"}, {"nation", "nation:de"}});
// No club.competition: membership-only imported worlds must work too.
world.rows("rules").push_back(
{{"id", "rule:bmh-classic@1"},
{"type", "attribute_set"},
{"fields", {{"strength", {{"min", 0}, {"max", 99}}}, {"form", {{"min", 0}, {"max", 127}}}}}});
const Json ratings{90, 70, 50, nullptr, 90, 99};
const std::vector<std::string> ids{"a", "b", "c", "d", "free", "duplicate"};
for (size_t i = 0; i < ids.size(); ++i) {
const auto team = i < 2 || i == 5 ? Json("club:north") : i < 4 ? Json("club:south") : Json();
world.rows("players").push_back(
{{"id", "player:" + ids[i]},
{"name", ids[i]},
{"team", team},
{"born", "2000-01-01"},
{"positions", {"mid"}},
{"attribute_set", "bmh-classic@1"},
{"attributes", {{"strength", ratings[i]}, {"form", i ? Json(100) : Json()}}}});
}
world.rows("players")[1]["x-simulation"]["squad_role"] = "source-reserve";
world.rows("players")[5]["x-simulation"]["squad_role"] = "source-only-duplicate";
auto contract = [&](std::string id, std::string person, std::string team, int64_t salary,
std::string start = "2026-07-01", std::string end = "2027-06-30") {
world.rows("contracts")
.push_back({{"id", "contract:" + id},
{"name", id},
{"person", "player:" + person},
{"team", "club:" + team},
{"salary", salary},
{"start", start},
{"end", end}});
};
contract("a", "a", "north", 9000);
contract("b", "b", "north", 10000);
contract("c", "c", "south", 50000);
contract("c-conflict", "c", "south", 60000);
contract("d", "d", "south", 0); // Explicit zero is known, not missing.
contract("duplicate", "duplicate", "north", 99999999);
contract("a-expired", "a", "north", 1000000, "2025-07-01", "2026-06-30");
contract("a-future", "a", "north", 2000000, "2026-07-02", "2027-06-30");
contract("a-old-team", "a", "south", 3000000);
world.rows("staff").push_back({{"id", "staff:test"}, {"name", "Staff"}});
world.rows("contracts")
.push_back({{"id", "contract:staff"},
{"name", "Staff contract"},
{"person", "staff:test"},
{"team", "club:north"},
{"salary", 9999999}});
return world;
}
Json compare(const World &world, Json args = Json::object()) {
return query_comparison(comparison_data(world, args), args);
}
} // namespace
int main() {
const auto root = fs::temp_directory_path() / new_id("comparison-tests-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
auto world = fixture();
const auto original_players = world.rows("players"), original_contracts = world.rows("contracts");
auto players = compare(world, {{"sort", "salary"}, {"descending", true}});
check(players["total"] == 5 && players["excluded_players"] == 1,
"all real rows, reserve included, source duplicate excluded");
check(players["items"][0]["id"] == "player:b" && players["items"][1]["salary"] == 9000,
"numeric salary sort and active current-team contracts");
check(players["items"][2]["salary"] == 0 && players["items"][3]["salary"].is_null(),
"zero before missing salary descending");
check(find(players["items"], "player:c")["salary_ambiguous"] == 1,
"conflicting active contracts stay unknown");
check(players["currency"]["minor_units"] == 2, "integer currency units retained");
players = compare(world, {{"sort", "salary"}});
check(players["items"][0]["id"] == "player:d" && players["items"][4]["salary"].is_null(),
"missing salary last ascending too");
auto rating = compare(
world, {{"sort", "attributes.strength"}, {"descending", true}, {"offset", 1}, {"limit", 1}});
check(rating["items"][0]["id"] == "player:free" && rating["total"] == 5,
"stable tie by ID and full-result sort before paging");
check(compare(world, {{"team", "club:north"}})["total"] == 2,
"team filter excludes source duplicate");
check(compare(world, {{"nation", "nation:de"}, {"competition", "comp:first"}})["total"] == 4,
"league and nation follow membership fallback");
auto teams =
compare(world, {{"table", "clubs"}, {"sort", "attributes.strength"}, {"descending", true}});
auto north = find(teams["items"], "club:north"), south = find(teams["items"], "club:south");
check(north["attributes"]["strength"] == 80 && north["salary_total"] == 19000,
"club means and player-only payroll");
check(north["salary_average"] == 9500 && north["salary_complete"] == true,
"mean wage and coverage complete");
check(south["attributes"]["strength"] == 50 && south["attribute_counts"]["strength"] == 1,
"unknown attributes excluded from mean denominator");
check(south["salary_total"] == 0 && south["salary_known"] == 1 && south["salary_unknown"] == 1 &&
south["salary_complete"] == false,
"partial payroll distinguished from complete zero");
check(find(teams["items"], "club:empty")["salary_total"].is_null(),
"empty team is not a zero-payroll team");
auto leagues = compare(world, {{"table", "leagues"}, {"language", "en"}});
auto league = find(leagues["items"], "comp:first");
check(leagues["total"] == 2 && league["club_count"] == 2 && league["player_count"] == 4,
"cups excluded; exact unique league population");
check(league["attributes"]["strength"] == 70,
"league strength is player-weighted, not a mean of club means");
check(league["salary_total"] == 19000 && league["salary_average"] == 6333 &&
league["salary_known"] == 3,
"league payroll uses known contracts once and integer rounded mean");
check(league["name"] == "Test league", "localized names");
check(world.rows("players") == original_players && world.rows("contracts") == original_contracts,
"comparison never changes source records");
auto classic = world;
classic.rows("contracts") = Json::array();
classic.manifest["currency"] = {{"code", "GBP"}, {"minor_units", 0}};
check(compare(classic)["items"][0]["salary"].is_null() &&
compare(classic)["currency"]["code"] == "GBP",
"Classic without contracts remains unknown in its actual currency");
world.rows("rules").push_back(
{{"id", "rule:fc@1"},
{"type", "attribute_set"},
{"attribute_set", "fc@1"},
{"fields", {{"overall", {{"min", 0}, {"max", 99}}}, {"strength", {{"min", 0}, {"max", 99}}}}}});
auto &modern = world.rows("players")[1];
modern["attribute_set"] = "fc@1";
modern["attributes"] = {{"overall", 85}, {"strength", 35}};
check(compare(world)["mixed_attribute_sets"] == true && compare(world)["attributes"].empty(),
"different strength systems are never implicitly combined");
rejects("invalid_comparison_sort", [&] { compare(world, {{"sort", "attributes.strength"}}); });
auto fc = compare(world, {{"table", "clubs"}, {"attribute_set", "fc@1"}});
check(find(fc["items"], "club:north")["attributes"]["overall"] == 85 &&
find(fc["items"], "club:north")["player_count"] == 1,
"attribute system filter also defines aggregation population");
rejects("invalid_attribute_set", [&] { compare(world, {{"attribute_set", "unknown@1"}}); });
rejects("unknown_table", [&] { compare(world, {{"table", "staff"}}); });
auto many = fixture();
many.rows("players") = Json::array();
many.rows("contracts") = Json::array();
for (int i = 0; i < 231; ++i)
many.rows("players").push_back({{"id", "player:" + std::to_string(i)},
{"name", std::to_string(i)},
{"attribute_set", "synthetic@1"},
{"attributes", {{"rating", i}}}});
const auto second_page =
compare(many, {{"sort", "attributes.rating"}, {"descending", true}, {"offset", 200}});
check(second_page["total"] == 231 && second_page["items"].size() == 31 &&
second_page["items"][0]["attributes"]["rating"] == 30,
"sorting spans all pages, no 200-row truncation");
auto overflow = fixture();
overflow.rows("contracts")[0]["salary"] = std::numeric_limits<int64_t>::max();
const auto extreme = find(compare(overflow, {{"table", "clubs"}})["items"], "club:north");
check(extreme["salary_overflow"] == true && extreme["salary_total"].is_null(),
"payroll overflow never wraps into a plausible negative value");
auto invalid = fixture();
invalid.rows("contracts")[0]["start"] = 20260701;
check(find(compare(invalid)["items"], "player:a")["salary"].is_null(),
"malformed contract dates are not silently treated as open bounds");
invalid.rows("contracts")[1]["salary"] = -1;
check(find(compare(invalid)["items"], "player:b")["salary"].is_null(),
"invalid salary is unknown, not a negative payroll credit");
invalid.manifest["start_date"] = nullptr;
check(find(compare(invalid)["items"], "player:d")["salary"].is_null(),
"unknown world date does not substitute the wall clock");
invalid.manifest["x-simulation"] = nullptr;
check(compare(invalid)["fictional_completion"] == false,
"unrecognized optional extension metadata does not break comparisons");
auto saved = fixture();
saved.save(root / "fixture.obw");
Session session;
session.execute("open", {{"path", utf8(root / "fixture.obw")}});
const auto info = session.execute("info");
const auto projection = session.execute("compare", {{"table", "clubs"}});
check(info == session.execute("info") && info["dirty"] == false,
"session comparison is read-only including revision and undo state");
session.execute("apply", {{"changes", Json::array({{{"table", "players"},
{"id", "player:a"},
{"set", {{"/attributes/strength", 80}}}}})}});
check(find(session.execute("compare", {{"table", "clubs"}})["items"],
"club:north")["attributes"]["strength"] == 75,
"cached comparison refreshes after an edit");
session.execute("undo");
check(session.execute("compare", {{"table", "clubs"}})["items"] == projection["items"],
"cached comparison refreshes after undo");
McpServer server(session);
const auto reply =
server.dispatch({{"jsonrpc", "2.0"},
{"id", 1},
{"method", "tools/call"},
{"params",
{{"name", "editor_compare"},
{"arguments", {{"table", "leagues"}, {"sort", "salary_total"}}}}}});
check(!reply["result"].value("isError", false) && reply["result"]["structuredContent"]["total"] == 2,
"MCP uses the same comparison projection");
bool read_only = false;
for (const auto &tool : McpServer::tools())
if (tool["name"] == "editor_compare")
read_only = tool["annotations"]["readOnlyHint"] == true;
check(read_only, "MCP comparison advertises read-only semantics");
std::cout << checks << " editor comparison checks passed\n";
return 0;
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+49 -1
View File
@@ -89,7 +89,55 @@ def main():
tool('editor_save', {'path': str(root / 'world.obw')})
assert (root / 'world.obw').is_file()
assert tool('editor_info')['dirty'] is False
print('Native RmlUI edit, JSON fields, search focus, shared undo/redo and OBW save passed.')
# Exercise the native comparison, not just its MCP projection:
# sort, open the first displayed row, edit its first property,
# and observe which stable record actually changed via MCP.
def compare_open():
click(100, 460); time.sleep(.25)
def first_property(table, identifier, expected, first_name=False):
click(330, 402); time.sleep(.2)
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', expected)
click(1300, 741)
for _ in range(40):
record = tool('editor_get', {'table': table, 'id': identifier})['record']
if record['name']['first' if first_name else 'default'] == expected:
break
time.sleep(.05)
else:
raise AssertionError('Comparison opened the wrong row: ' + identifier)
tool('editor_undo'); time.sleep(.3)
compare_open()
click(730, 288) # Attribute chooser: hide all, select Strength via its label.
click(495, 405)
click(900, 461)
click(1080, 575)
click(835, 345) # Sort the remaining rating column descending.
first_property('players', 'player:demo-14', 'Rating Descending', True)
compare_open()
click(978, 345) # Salary descending: highest known demo wage.
first_property('players', 'player:demo-50', 'Salary Descending', True)
compare_open()
click(978, 345) # Ascending; missing salary must remain last.
first_property('players', 'player:demo-0', 'Salary Ascending', True)
compare_open()
click(1274, 153) # Teams.
click(946, 345) # Total salary descending.
first_property('clubs', 'club:south', 'Payroll Descending')
compare_open()
click(1378, 153) # Leagues; its row opens the competition editor.
first_property('competitions', 'comp:demo', 'League Comparison')
assert tool('editor_info')['dirty'] is False
before_rules = tool('editor_info')
click(100, 509) # New read-only Regulations page.
click(475, 232) # Game rules.
click(325, 232) # Leagues & competitions.
click(650, 233); x('type', '--clearmodifiers', 'League')
time.sleep(.2); x('key', 'ctrl+a'); x('key', 'BackSpace')
rules = tool('editor_regulations', {'competition': 'comp:demo', 'language': 'en'})
assert rules['read_only'] is True and len(rules['items']) == 1
assert rules['items'][0]['movement_defined'] is False
assert tool('editor_info') == before_rules
print('Native edit, search, undo/save, sorted comparisons and read-only regulations passed.')
except Exception:
log.flush()
print((root / 'app.log').read_text())
+164
View File
@@ -0,0 +1,164 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/mcp.hpp"
#include "editor/regulations.hpp"
#include "editor/session.hpp"
#include <iostream>
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool result, const char *message) {
++checks;
if (!result)
throw std::runtime_error(message);
}
Json find(const Json &items, const std::string &id) {
for (const auto &row : items)
if (str(row, "id") == id)
return row;
throw std::runtime_error("missing fixture " + id);
}
Json view(const World &world, const std::string &id) {
return find(regulation_view(world, Json::object())["items"], id);
}
World fixture() {
auto world = World::blank("Synthetic regulations");
world.rows("nations").push_back({{"id", "nation:test"}, {"name", "Testland"}});
for (int i = 0; i < 9; ++i)
world.rows("competitions")
.push_back(
{{"id", "comp:league-" + std::to_string(i)},
{"name", {{"default", "League " + std::to_string(i)}, {"de", "Liga " + std::to_string(i)}}},
{"nation", "nation:test"},
{"type", "league"},
{"tier", i + 1},
{"stages",
Json::array({{{"id", "regular"}, {"format", "league"}, {"teams", 18}, {"legs", 2}}})}});
world.rows("competitions")
.push_back({{"id", "comp:cup"}, {"name", "Test Cup"}, {"type", "club_international"}});
return world;
}
} // namespace
int main() {
const auto root = fs::temp_directory_path() / new_id("regulations-tests-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
auto world = fixture();
auto &league = world.rows("competitions")[1];
league["movement"] = Json::array({{{"ranks", {1, 2}}, {"to", "comp:league-0"}},
{{"ranks", {3}}, {"to", "comp:playoff"}, {"role", "challenger"}},
{{"ranks", {16, 18}}, {"to", "comp:league-2"}}});
const Json selector{{"from", "comp:league-1"},
{"ranks", {1, 4}},
{"stage", "main"},
{"fallback", {{"from", "comp:league-0"}, {"next_unqualified", true}}}};
world.rows("competitions").back()["slots"] =
Json::array({selector,
{{"holder", "comp:cup"}},
{{"from", "coefficient"}, {"nation_rank", {1, 4}}, {"places", 4}}});
const Json cup_winner{{"from", "comp:league-0"}, {"winner", true}, {"to", "comp:cup"}};
world.rows("competitions")[0]["stages"][0]["slots"] = Json::array({cup_winner});
auto row = view(world, "comp:league-1");
check(row["movement"][0]["kind"] == "promotion" && row["movement"][0]["ranks"] == Json({1, 2}),
"rank ranges preserved");
check(row["movement"][1]["kind"] == "playoff" && row["movement"][2]["kind"] == "relegation",
"explicit movement kinds");
check(row["qualification"][0]["definition"] == selector && row["qualification"][0]["stage"] == "main",
"outbound qualification retains fallback and stage");
const auto cup = view(world, "comp:cup");
check(cup["qualification"].size() == 4 && cup["qualification"][3]["definition"] == cup_winner,
"competition and stage slots; explicit destination");
check(!view(world, "comp:league-2")["movement_defined"].get<bool>() &&
view(world, "comp:league-2")["classic_qualification"].is_null(),
"no invented modern rules");
const auto filtered =
regulation_view(world, {{"language", "de"}, {"nation", "nation:test"}, {"search", "Liga 1"}});
check(filtered["items"].size() == 1 && filtered["items"][0]["name"] == "Liga 1",
"localized search and country filter");
const auto classic = fixture();
world = classic;
const int down[] = {3, 4, 2, 2, 3, 0, 0, 0, 0};
for (int i = 0; i < 9; ++i)
world.rows("competitions")[i]["x-legacy"] = {
{"league_index", i}, {"relegation_places", down[i]}, {"europe_places", 99}};
world.rows("rules").push_back({{"id", "rule:ladder"},
{"type", "legacy_ladder"},
{"first_league", {0, 1, 2, 4}},
{"league_count", {1, 1, 2, 1}},
{"below", {1, 2, 4, 5}},
{"below_count", {1, 2, 1, 1}},
{"newcomer_count", 30}});
world.rows("rules").push_back({{"id", "rule:runtime"},
{"type", "classic_runtime"},
{"qualifications", "classic-season-entrants@1"}});
auto first = view(world, "comp:league-0"), second = view(world, "comp:league-1");
check(first["movement"][0]["ranks"] == Json({16, 18}), "classic relegation reads loaded counts");
check(first["classic_qualification"]["uefa_base_places"] == 4 &&
view(world, "comp:league-8")["classic_qualification"]["uefa_base_places"] == 3,
"classic quotas use named policy, not europe_places");
check(second["movement"][0]["kind"] == "promotion" && second["movement"][1]["targets"].size() == 2 &&
second["movement"][1]["conditional_playoffs"] == true,
"parallel lower leagues and conditional playoff exchange");
auto third = view(world, "comp:league-2");
check(third["movement"][0]["ranks"] == Json({1, 1}) &&
third["movement"][1]["selector"] == "classic-playoff-winner",
"parallel league champion plus playoff; no invented automatic runner-up");
auto bottom = view(world, "comp:league-4");
check(bottom["movement"].back()["newcomer_pool"] == true &&
bottom["movement"].back()["targets"].empty(),
"bottom uses newcomer pool, never the foreign below index");
check(view(world, "comp:league-5")["movement_defined"] == true &&
view(world, "comp:league-5")["movement"].empty(),
"classic foreign league closed");
world.rows("competitions")[0]["movement"] = Json::array();
world.rows("competitions")[0]["slots"] =
Json::array({{{"from", "comp:league-0"}, {"to", "comp:cup"}, {"ranks", {1, 2}}}});
check(view(world, "comp:league-0")["movement"].empty() &&
view(world, "comp:league-0")["classic_qualification"].is_null(),
"declared rules take precedence over Classic summaries");
world.rows("competitions")[8]["x-legacy"] = nullptr;
world.rows("competitions")[8]["classic"] = nullptr;
world.rows("competitions")[8]["stages"] = nullptr;
check(view(world, "comp:league-8")["classic_qualification"].is_null(), "null optional metadata safe");
// Only synthetic data enters public archives or tests.
world = fixture();
const auto records = world.rows("competitions"), rules = world.rows("rules");
regulation_view(world, Json::object());
check(records == world.rows("competitions") && rules == world.rows("rules"),
"projection leaves documents untouched");
world.save(root / "fixture.obw");
Session session;
session.execute("open", {{"path", utf8(root / "fixture.obw")}});
const auto info = session.execute("info"), history = session.execute("history");
session.execute("regulations");
check(info == session.execute("info") && history == session.execute("history"),
"session read-only including revision and undo");
McpServer server(session);
const auto reply =
server.dispatch({{"jsonrpc", "2.0"},
{"id", 1},
{"method", "tools/call"},
{"params",
{{"name", "editor_regulations"},
{"arguments", {{"competition", "comp:league-1"}, {"language", "en"}}}}}});
check(reply["result"]["structuredContent"]["items"].size() == 1 &&
reply["result"]["structuredContent"]["read_only"] == true,
"MCP shares projection");
bool readonly = false;
for (const auto &tool : McpServer::tools())
if (tool["name"] == "editor_regulations")
readonly = tool["annotations"]["readOnlyHint"] == true;
check(readonly, "MCP read-only annotation");
std::cout << checks << " editor regulations checks passed\n";
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+2 -2
View File
@@ -116,8 +116,8 @@ def main():
(stage / 'dependencies.cmake').write_text('\n'.join(cache) + '\n')
(stage / 'SOURCE_MANIFEST.json').write_text(json.dumps(manifest, indent=2) + '\n')
(stage / 'BUILD_SOURCE.txt').write_text('cmake -S project -B build -C dependencies.cmake -G Ninja -DCMAKE_BUILD_TYPE=Release\n'
'cmake --build build --target openbmh_editor editor_core_tests\n'
'ctest --test-dir build -R "^editor_(core_tests|version)$" --output-on-failure\n'
'cmake --build build --target openbmh_editor editor_core_tests editor_comparison_tests editor_regulations_tests\n'
'ctest --test-dir build -R "^editor_(core_tests|comparison_tests|regulations_tests|version)$" --output-on-failure\n'
'Native compiler, CMake and OS development libraries: see project/docs/EDITOR.md.\n')
zip_tree(stage, args.out / (source_name + '.zip'))
print(args.out / (source_name + '.zip'))
+36
View File
@@ -45,6 +45,42 @@ SKIP_DIRECTORIES = {".git", "__pycache__", ".cache", "_deps", "node_modules"}
# The latter are reviewed against docs/qa/editor-poc/README.md; no game material.
# Keep prior reviewed hashes if an asset is intentionally revised in history.
PROJECT_ARTWORK = {
"docs/qa/editor-regulations/before-competitions-0.5.1.png": {
"cffa594e4d5ee942e086ab24fe7744a53dab4d5083dc1659f5e4b3ebdaee1f0b",
},
"docs/qa/editor-regulations/game-rules-midnight-de.png": {
"b8778c35f4c94c327086198f765296698a401f4ef43029bb018e88c05fc7848f",
},
"docs/qa/editor-regulations/qualification-midnight-de.png": {
"c1fa59f416db2ee56ac661b1c21101da645bc6d00ca2c1656438455a48b55295",
},
"docs/qa/editor-regulations/rules-matchday-de.png": {
"45d09f05a7a4cf86bf465775f276c4f71790a053fa85a0e4bc42124d34702a34",
},
"docs/qa/editor-regulations/rules-midnight-de.png": {
"f067fe69dd08c6f849fba3bae518727cc1252702494d077d2b7561c9aee3ed01",
},
"docs/qa/editor-regulations/rules-silver-en.png": {
"e4e0f5269f23b4757b1bded384eb37857212236b626df7bc1352281f5eb5da1d",
},
"docs/qa/editor-comparison/before-players-0.5.0.png": {
"e061cf1fcbafffc2950037f2f4bf24f28c00fe835988b56b198d88bce33b97e2",
},
"docs/qa/editor-comparison/players-midnight-de.png": {
"ab1debb1e282d5462eab1a570137477884b2c773a900ec45a74783d50693367d",
},
"docs/qa/editor-comparison/teams-silver-en.png": {
"ad8e8274f21465686b8c499ad44344ea4705cbec520560b12f8d7dde878204ea",
},
"docs/qa/editor-comparison/leagues-matchday-de.png": {
"f24cd278b30ce3ccecc7320ae105ea5d0394e759c8045a76e75851259a487ada",
},
"docs/qa/editor-comparison/columns-midnight-de.png": {
"74d825609b862c7dc60dc5182a32c010df73177b10d849079b02a2b4dc2d1620",
},
"docs/qa/editor-comparison/players-scroll-midnight-de.png": {
"8e23a0fe6ea31ca6050fd5f157016948e0bad2f83093dcc3c53a3ba855c3bb40",
},
"docs/qa/editor-poc/clubs-midnight-de.png": {
"2921aa67a870633c96f46328a82bc3022e5489b38d551c5314f13c7e59446070",
"aa53e9cdd9ac8f6bf18b514862ac704ff9003bd1b62466cad2ebc329b09703dc",