diff --git a/.github/workflows/editor.yml b/.github/workflows/editor.yml index 2f01b54..e82cc25 100644 --- a/.github/workflows/editor.yml +++ b/.github/workflows/editor.yml @@ -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 editor_comparison_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|comparison_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: | diff --git a/README.md b/README.md index da0fc6d..3ba6d58 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # OpenBMH -The separate [OpenBMH Editor 0.5.1](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.1` 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. diff --git a/assets/editor/theme.rcss b/assets/editor/theme.rcss index 8de7c09..6e9ff17 100644 --- a/assets/editor/theme.rcss +++ b/assets/editor/theme.rcss @@ -237,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); } diff --git a/docs/EDITOR.md b/docs/EDITOR.md index 75cbc96..ebe9a8f 100644 --- a/docs/EDITOR.md +++ b/docs/EDITOR.md @@ -1,10 +1,10 @@ -# OpenBMH Editor 0.5.1 +# 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.1 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.1`; 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.1-.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-.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. @@ -63,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_compare`, `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 @@ -71,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 editor_comparison_tests --parallel 2 -ctest --test-dir build-editor -C Release -R '^editor_(core_tests|comparison_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. @@ -95,8 +112,10 @@ Extract the complete package and run **OpenBMHEditor**. Open an OBW archive or a 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.1 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. diff --git a/docs/formats/OBW.md b/docs/formats/OBW.md index c1f6a0f..53d7f52 100644 --- a/docs/formats/OBW.md +++ b/docs/formats/OBW.md @@ -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: [], selection: "random-on-creation", +fallback: }`. 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//photo`) resolve in this order: 1. A photo from an active pack. diff --git a/docs/formats/obw/classic-v1.md b/docs/formats/obw/classic-v1.md index b6e0245..d104ab0 100644 --- a/docs/formats/obw/classic-v1.md +++ b/docs/formats/obw/classic-v1.md @@ -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 diff --git a/docs/formats/obw/editor-v1.md b/docs/formats/obw/editor-v1.md index abcb9eb..2913096 100644 --- a/docs/formats/obw/editor-v1.md +++ b/docs/formats/obw/editor-v1.md @@ -83,6 +83,33 @@ 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 diff --git a/docs/qa/editor-regulations/README.md b/docs/qa/editor-regulations/README.md new file mode 100644 index 0000000..b46851d --- /dev/null +++ b/docs/qa/editor-regulations/README.md @@ -0,0 +1,41 @@ + +# 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. diff --git a/docs/qa/editor-regulations/before-competitions-0.5.1.png b/docs/qa/editor-regulations/before-competitions-0.5.1.png new file mode 100644 index 0000000..436fd86 Binary files /dev/null and b/docs/qa/editor-regulations/before-competitions-0.5.1.png differ diff --git a/docs/qa/editor-regulations/game-rules-midnight-de.png b/docs/qa/editor-regulations/game-rules-midnight-de.png new file mode 100644 index 0000000..f87d735 Binary files /dev/null and b/docs/qa/editor-regulations/game-rules-midnight-de.png differ diff --git a/docs/qa/editor-regulations/make_fixture.py b/docs/qa/editor-regulations/make_fixture.py new file mode 100644 index 0000000..a0b6ba4 --- /dev/null +++ b/docs/qa/editor-regulations/make_fixture.py @@ -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() diff --git a/docs/qa/editor-regulations/qualification-midnight-de.png b/docs/qa/editor-regulations/qualification-midnight-de.png new file mode 100644 index 0000000..bd814c3 Binary files /dev/null and b/docs/qa/editor-regulations/qualification-midnight-de.png differ diff --git a/docs/qa/editor-regulations/rules-matchday-de.png b/docs/qa/editor-regulations/rules-matchday-de.png new file mode 100644 index 0000000..2d8c744 Binary files /dev/null and b/docs/qa/editor-regulations/rules-matchday-de.png differ diff --git a/docs/qa/editor-regulations/rules-midnight-de.png b/docs/qa/editor-regulations/rules-midnight-de.png new file mode 100644 index 0000000..3f79eb7 Binary files /dev/null and b/docs/qa/editor-regulations/rules-midnight-de.png differ diff --git a/docs/qa/editor-regulations/rules-silver-en.png b/docs/qa/editor-regulations/rules-silver-en.png new file mode 100644 index 0000000..a7a03fa Binary files /dev/null and b/docs/qa/editor-regulations/rules-silver-en.png differ diff --git a/docs/release/editor-0.5/RELEASE_NOTES.md b/docs/release/editor-0.5/RELEASE_NOTES.md index 27d0d5e..f89bee5 100644 --- a/docs/release/editor-0.5/RELEASE_NOTES.md +++ b/docs/release/editor-0.5/RELEASE_NOTES.md @@ -1,5 +1,21 @@ -# OpenBMH Editor 0.5.1 +# 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. diff --git a/src/editor/CMakeLists.txt b/src/editor/CMakeLists.txt index 40409b9..c444ca5 100644 --- a/src/editor/CMakeLists.txt +++ b/src/editor/CMakeLists.txt @@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-3.0-only include(FetchContent) -set(OPENBMH_EDITOR_VERSION "0.5.1") +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 comparison.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 @@ -91,5 +91,11 @@ 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}") diff --git a/src/editor/mcp.cpp b/src/editor/mcp.cpp index 44c97a0..c685c2c 100644 --- a/src/editor/mcp.cpp +++ b/src/editor/mcp.cpp @@ -53,6 +53,7 @@ const std::map commands{{"editor_info", "info"}, {"editor_new", "new"}, {"editor_list", "list"}, {"editor_compare", "compare"}, + {"editor_regulations", "regulations"}, {"editor_get", "get"}, {"editor_apply", "apply"}, {"editor_validate", "validate"}, @@ -168,6 +169,18 @@ Json McpServer::tools() { {"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", diff --git a/src/editor/options.cpp b/src/editor/options.cpp index 2537bd8..5afd697 100644 --- a/src/editor/options.cpp +++ b/src/editor/options.cpp @@ -89,6 +89,92 @@ std::string tr(const std::string &language, const std::string &key) { using Pair = std::pair; static const std::map 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", diff --git a/src/editor/regulations.cpp b/src/editor/regulations.cpp new file mode 100644 index 0000000..e91b587 --- /dev/null +++ b/src/editor/regulations.cpp @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/regulations.hpp" +#include "editor/world.hpp" +#include + +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 number(const Json &value) { + if (!value.is_number_integer() || value.get() < 0 || value.get() > 100000) + return {}; + return value.get(); +} +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 competitions; + std::map indexed; + for (const auto &comp : world.rows("competitions")) { + competitions[str(comp, "id")] = ∁ + const auto legacy = object(comp, "x-legacy"); + if (const auto index = number(legacy.value("league_index", Json())); + index && str(comp, "type") == "league") + indexed[*index] = ∁ + } + 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 movement, qualification; + std::set 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 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{}; + 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{}; + 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 diff --git a/src/editor/regulations.hpp b/src/editor/regulations.hpp new file mode 100644 index 0000000..cc82dcc --- /dev/null +++ b/src/editor/regulations.hpp @@ -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 diff --git a/src/editor/session.cpp b/src/editor/session.cpp index 7494c34..46eded5 100644 --- a/src/editor/session.cpp +++ b/src/editor/session.cpp @@ -3,6 +3,7 @@ #include "content/digest.hpp" #include "editor/comparison.hpp" #include "editor/images.hpp" +#include "editor/regulations.hpp" #include #include @@ -459,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") { diff --git a/src/editor/ui.cpp b/src/editor/ui.cpp index 2a852f3..cdf33c9 100644 --- a/src/editor/ui.cpp +++ b/src/editor/ui.cpp @@ -147,6 +147,8 @@ class EditorUi final : public Rml::EventListener { bool comparison_descending_ = false; Json comparison_; std::map> 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 { @@ -212,6 +214,7 @@ class EditorUi final : public Rml::EventListener { {"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"}, @@ -403,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", - "comparison", "stadiums", "staff", "assets", "review", "changes"}) + for (const std::string name : + {"overview", "nations", "competitions", "clubs", "players", "roster", "comparison", + "regulations", "stadiums", "staff", "assets", "review", "changes"}) nav += ""; html("navigation", nav); label("page-kicker", "OpenBMH / " + t(page_)); - label("page-title", t(page_ == "comparison" ? "comparison_title" : 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_)); @@ -988,6 +994,188 @@ class EditorUi final : public Rml::EventListener { size_t(offset_) + listed_.size() < total_ ? "" : "disabled") + ""); } + 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", "" + escaped(t("regulation_readonly")) + ""); + 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\"") + + "" + + (regulations_game_ ? "" + : "")); + if (!info_.value("loaded", false)) { + html("page-content", "
" + escaped(t("welcome_hint")) + "
"); + 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 = "
"; + for (const auto &row : rows) { + const auto id = str(row, "id"); + body += ""; + } + body += "
"; + auto section = [&](const std::string &key, const std::string &content) { + return "

" + escaped(t(key)) + "

" + content + "
"; + }; + auto paragraph = [&](const std::string &value) { return "

" + escaped(value) + "

"; }; + auto source = [&](const Json &value) { + return "
" + escaped(value.dump(2)) + "
"; + }; + if (!selected) + body += "
" + escaped(t("empty")) + "
"; + else if (regulations_game_) { + body += "

" + escaped(regulation_type(*selected, "rule_type_")) + "

" + + escaped(chosen) + "" + paragraph(t("regulation_preserved")) + source(*selected); + } else { + const auto &row = *selected; + body += "

" + escaped(str(row, "name")) + "

" + escaped(chosen) + "" + + 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 += + "
" + + escaped(t("regulation_" + str(entry, "kind"))) + "" + + paragraph((str(entry, "selector") == "classic-playoff-winner" + ? t("regulation_playoff_winner") + : regulation_ranks(entry.value("ranks", Json()))) + + " · " + t("regulation_to") + " " + destinations) + + "" + + escaped(t(str(entry, "source") == "declared" ? "regulation_declared" + : "regulation_classic")) + + "" + + (entry.value("conditional_playoffs", false) ? paragraph(t("regulation_classic_playoffs")) + : "") + + (regulations_source_ ? source(entry) : "") + "
"; + } + 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 += "" + escaped(t("regulation_classic_movement_note")) + ""; + body += section("regulation_movement_title", movement); + std::string qualification; + const auto policy = row["classic_qualification"]; + if (!policy.is_null()) { + qualification = "
" + + escaped(t("regulation_classic")) + "" + + 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 += "classic-season-entrants@1
"; + } + 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 += "
" + + escaped((from.empty() ? "" : from + " · " + t("regulation_to") + " ") + to) + + "" + 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 += + "" + escaped(t("regulation_stage") + ": " + str(entry, "stage")) + ""; + qualification += (regulations_source_ ? source(definition) : "") + "
"; + } + 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 + "
"); + } void changes() { html("toolbar", ""); html("pagination", ""); @@ -1029,6 +1217,8 @@ class EditorUi final : public Rml::EventListener { changes(); else if (page_ == "comparison") comparison(); + else if (page_ == "regulations") + regulations(); else records(); if (page_ == "comparison" && doc_->GetElementById("comparison-x")) { @@ -1300,14 +1490,25 @@ class EditorUi final : public Rml::EventListener { selected_id_.clear(); offset_ = 0; search_.clear(); - if (arg == "comparison") { + if (arg == "comparison" || arg == "regulations") { nation_.clear(); league_.clear(); team_.clear(); } needs_refresh_ = true; }); - else if (action == "compare-open" || action == "compare-scope") + 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; diff --git a/tests/editor_gui_smoke.py b/tests/editor_gui_smoke.py index 83a3ec3..c1edd65 100644 --- a/tests/editor_gui_smoke.py +++ b/tests/editor_gui_smoke.py @@ -127,7 +127,17 @@ def main(): click(1378, 153) # Leagues; its row opens the competition editor. first_property('competitions', 'comp:demo', 'League Comparison') assert tool('editor_info')['dirty'] is False - print('Native RmlUI edit, search, undo/save and sorted player/team/league comparison passed.') + 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()) diff --git a/tests/editor_regulations_tests.cpp b/tests/editor_regulations_tests.cpp new file mode 100644 index 0000000..86c1bba --- /dev/null +++ b/tests/editor_regulations_tests.cpp @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "editor/mcp.hpp" +#include "editor/regulations.hpp" +#include "editor/session.hpp" +#include + +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() && + 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; + } +} diff --git a/tools/package/make_editor_package.py b/tools/package/make_editor_package.py index e1d0388..36e8b2b 100644 --- a/tools/package/make_editor_package.py +++ b/tools/package/make_editor_package.py @@ -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 editor_comparison_tests\n' - 'ctest --test-dir build -R "^editor_(core_tests|comparison_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')) diff --git a/tools/public_release/check_public_tree.py b/tools/public_release/check_public_tree.py index 79ec9c2..22da212 100644 --- a/tools/public_release/check_public_tree.py +++ b/tools/public_release/check_public_tree.py @@ -45,6 +45,24 @@ 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", },