Compare commits

..
47 changed files with 1166 additions and 84 deletions

No files matched your search

+13
View File
@@ -84,6 +84,19 @@ jobs:
subprocess.run([str(build / ('OpenBMH' + suffix)), '--version'], check=True)
- name: Package products and licenses
run: python3 tools/package/make_package.py --build build --out dist --platform ${{ matrix.platform }}
- name: Package native Windows editor
if: runner.os == 'Windows'
shell: pwsh
run: |
$game = (Get-ChildItem dist/OpenBMH-*-windows-x64.zip | Select-Object -First 1).FullName
python3 tools/package/make_editor_package.py --build build --game $game --out editor-dist
- name: Upload native editor
if: runner.os == 'Windows'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: obdeddi-windows-x64
path: editor-dist/*.zip
if-no-files-found: error
- name: Package corresponding source and pinned dependencies
if: runner.os == 'Linux'
run: python3 tools/package/make_source_package.py --source . --build build --out source-dist
+37 -1
View File
@@ -5,7 +5,7 @@ if(APPLE)
# Enable native languages before dependencies/subdirectories inherit rules.
enable_language(OBJC OBJCXX)
endif()
set(OPENBMH_PRERELEASE "poc.1" CACHE STRING "Prerelease identifier; empty for final release")
set(OPENBMH_PRERELEASE "beta.2" CACHE STRING "Prerelease identifier; empty for final release")
set(OPENBMH_PRODUCT_VERSION "${PROJECT_VERSION}")
if(OPENBMH_PRERELEASE)
string(APPEND OPENBMH_PRODUCT_VERSION "-${OPENBMH_PRERELEASE}")
@@ -207,6 +207,7 @@ bmh_add_data_test(NAME highscore_tests REQUIRED_OPTIONS BMH_TEST_HIGHSCORE_TESTS
# Engine core: file formats and game logic, no platform dependencies
add_library(bmhcore STATIC
src/formats/binary.cpp
src/formats/resource_bundle.cpp
src/formats/palette.cpp
src/formats/vga.cpp
src/formats/font.cpp
@@ -305,6 +306,7 @@ FetchContent_MakeAvailable(miniz lzma_sdk nfd)
add_library(bmh_miniz STATIC ${miniz_SOURCE_DIR}/miniz.c)
target_include_directories(bmh_miniz PUBLIC ${miniz_SOURCE_DIR})
target_link_libraries(bmhcore PRIVATE bmh_miniz)
set(BMH_LZMA_C ${lzma_sdk_SOURCE_DIR}/C)
add_library(bmh_7z STATIC
${BMH_LZMA_C}/7zAlloc.c ${BMH_LZMA_C}/7zArcIn.c ${BMH_LZMA_C}/7zBuf.c ${BMH_LZMA_C}/7zCrc.c
@@ -1158,3 +1160,37 @@ bmh_add_data_test(NAME desktop_feedback_tests COMMAND desktop_feedback_tests "${
add_executable(data_profile_tests tests/data_profile_tests.cpp)
target_link_libraries(data_profile_tests PRIVATE bmhcore)
add_test(NAME data_profile_tests COMMAND data_profile_tests)
# Offline private package preparation; never installs Original data.
add_executable(export_community_runtime tools/poc/export_runtime.cpp)
target_link_libraries(export_community_runtime PRIVATE bmhcore)
add_executable(resource_bundle_tests tests/resource_bundle_tests.cpp)
target_link_libraries(resource_bundle_tests PRIVATE bmhcore bmh_miniz)
add_test(NAME resource_bundle_tests COMMAND resource_bundle_tests)
# Small native OBD editor. Its model is tested on every platform; UI is Win32 only.
add_library(obdeddi_hash STATIC ${BMH_LZMA_C}/Sha256.c ${BMH_LZMA_C}/Sha256Opt.c)
target_include_directories(obdeddi_hash PUBLIC ${BMH_LZMA_C})
target_link_libraries(obdeddi_hash PRIVATE bmh_7z)
add_library(obdeddi_model STATIC src/obdeddi/document.cpp src/cli/json.cpp)
target_include_directories(obdeddi_model PUBLIC src)
target_link_libraries(obdeddi_model PUBLIC bmhcore PRIVATE bmh_miniz obdeddi_hash)
if(WIN32)
add_executable(obdeddi WIN32 src/obdeddi/main_win32.cpp src/obdeddi/logo_win32.cpp src/obdeddi/logo_transform_win32.cpp)
target_link_libraries(obdeddi PRIVATE obdeddi_model comctl32 comdlg32 user32 gdi32 shell32 gdiplus)
if(MSVC)
target_compile_options(obdeddi PRIVATE /utf-8)
target_compile_options(obdeddi_model PRIVATE /utf-8)
endif()
install(TARGETS obdeddi RUNTIME DESTINATION . COMPONENT Editor)
endif()
add_executable(obdeddi_tests tests/obdeddi_tests.cpp)
target_link_libraries(obdeddi_tests PRIVATE obdeddi_model bmh_miniz)
add_test(NAME obdeddi_tests COMMAND obdeddi_tests)
if(WIN32)
add_executable(obdeddi_logo_tests tests/obdeddi_logo_tests.cpp src/obdeddi/logo_transform_win32.cpp)
target_include_directories(obdeddi_logo_tests PRIVATE src)
target_link_libraries(obdeddi_logo_tests PRIVATE gdiplus)
add_test(NAME obdeddi_logo_tests COMMAND obdeddi_logo_tests)
endif()
+2
View File
@@ -1,5 +1,7 @@
# OpenBMH
This is the **1.1 community development branch**. A prepared community package starts directly from `COMMUNITY.OBD`, without BMH.exe or a DOS installation. Original loose Classic installations remain supported. The stable 1.0 line stays on main. See [standalone community data](docs/poc-1.1/STANDALONE.md).
A faithful, standalone community reconstruction of *Bundesliga Manager Hattrick*, using the player's original installation and SDL2 interface.
OpenBMH 1.0 builds on v0.1.2 with reviewed bug fixes and starts directly with the original game data. Original game files, graphics, audio and manuals are not distributed. German CD-compatible BMH and verified Diamond editions are the primary release targets. Football Limited remains experimental; the older floppy executable is not supported.
+28
View File
@@ -0,0 +1,28 @@
# obdeddi 0.1.0
A small native Windows data editor for the standalone OpenBMH 1.1 COMMUNITY.OBD format. It uses Win32/common controls, not SDL, RmlUI or a browser. The model and archive-writing tests build on all supported platforms; the graphical editor is Windows x64 only.
## Use
Extract the separate editor package and start `obdeddi.exe`. Open a COMMUNITY.OBD with the Open button or Ctrl+O. A file path may also be passed on the command line. Search and sortable virtual lists cover players and clubs; the club filter applies to players. Artwork is decoded only on demand in the separate club-logo dialog.
Player fields include names, position, nationality, age, form/technique/condition, bonus and the seven Classic skills. Displayed strength is derived, not a second independent field. Club fields include names, the stored short-name span and existing kit selectors. League sizes and record counts stay fixed. Country rows and rules are not editable. Club logos can be imported from PNG/JPEG/BMP, cropped by source-pixel coordinates, freely rotated and mirrored. The before/after preview uses the actual 38×38 Original palette and bright background; shared crest cells are cloned into a free cell. Other artwork is not editable. League players can move between squads or swap places; temporary/reserve-table players cannot be reassigned as if they were ordinary roster members.
Classic new-career generation is deliberately retained: many stored player values are randomized/recalculated when a career starts. Editing the database does not modify an existing saved game. This limitation is visible in the player form.
Apply commits the current form to the in-memory document. Changing selection also validates the draft form. Ctrl+S writes the document to its original OBD after verification and backup. Closing or opening another file asks about unsaved changes.
## Save safety
- ZIP/resource limits and supplied hashes are checked on open. Original database order, IDs, unknown player bits and non-database resource bytes are preserved.
- The M3D writer validates a decode/encode roundtrip. Unsupported characters and full 16-bit string pools are rejected rather than silently replaced.
- Save serializes a temporary sibling archive and reopens it for validation. A cooperating editor lock prevents overlapping saves.
- The complete prior archive is copied to `backups/` and read back for verification. External modifications are checked before the transaction and again before replacement.
- Only then does the OS atomically replace the original. A failed backup, validation or replacement leaves the original intact; a temporary file is cleaned up. Successful saves update resource hashes and append an editor-history record.
- Saving an unchanged document is a no-op. Backups are independent OBD bytes and can be copied back while the application is closed.
## Performance and delivery
Owner-data lists request only visible cell text. Search is debounced, forms update on selection/change, and the native message loop does not render continuously while idle. Assets are retained as bytes for integrity and save roundtrips, without image/font/audio decoding.
The editor has its own ZIP/release. It is not inserted into the small Windows community game package. Corresponding full sources are offered separately. OpenBMH 1.1 Beta keeps a fixed `OpenBMH 1.1` window caption, fits 18/20-team strengths views above the controls and uses a 25% longer default scene-frame delay (at least 16 ms). Explicit frame-delay overrides remain available; simulation clocks and random streams are not changed.
+21
View File
@@ -0,0 +1,21 @@
# Standalone community data
The 1.1 community edition can start from `COMMUNITY.OBD` without an installed DOS game. The stable main line and loose Classic installation support remain separate.
`COMMUNITY.OBD` is a compressed read-only resource bundle. It contains the master database, text, palette, formations, desktop layout, fonts, indexed pictures/crests and audio containers required by OpenBMH. These are game content, not application code. Saves, highscores and user layouts remain normal writable files outside the bundle.
The bundle's `RUNTIME.DAT` uses the `OBMHDAT1` schema: data-segment base/length, calendar epoch, resolved badge/environment policies, data-segment bytes and explicitly named auxiliary labels. The exporter discards the DOS header, DOS/4GW loader and machine-code objects. Calendar and verified edition policies are values, rather than retained code fingerprints. This is not a renamed or embedded BMH executable.
The Classic address-view adapter still supplies the existing engine/UI table readers. It reads resource entries directly from the compressed bundle, without unpacking original executables or a cached DOS installation. Bundle paths are case-insensitive and reject duplicate/path-traversal entries; compressed/uncompressed limits bound allocations. Original loose installations retain their loading path.
Offline preparation from privately supplied resources:
```sh
cmake --build build --target export_community_runtime
python3 tools/poc/bundle_community.py --source /path/to/prepared-data \
--exporter /path/to/build/export_community_runtime --out /path/to/new/community-data
```
Only required resource types are included. DOS programs, installers, editor executables, original saves, backup directories, manuals and unused picture formats are excluded. Import provenance stays in `IMPORT-REPORT.json`; `PACKAGE.json` records the hashes of the bundled resources. A bundled `OBMHPROF.INI` selects the expanded league profile, so no additional loose Original files are needed.
Generated foreign crests now use the supplied Original domestic crest background texture. Transparent edges are composited onto that bright texture before palette reduction; actual black logo details remain black. The previous black rectangles and the light-on-dark monochrome workaround are removed.
+3 -1
View File
@@ -15,6 +15,8 @@ Implemented:
Local integration evidence so far: the expanded career completed 180 turns with seed 1 (three season ends), and another 180 with seed 11 (two season ends). No simulator invariant violations or contract-policy errors were reported. These are automated manager-policy runs, not claims of complete human gameplay QA or validation of all editions/platforms.
The prepared private dataset has 445 club/country entries, 3,334 players and 263 individual foreign club crests. Original German rosters and all 2,574 Original player word records are preserved by assertions during preparation. The visual review identified 175 usable supplied foreign crests and 88 missing/shared Original placeholders. Those 88 now have explicit fictional club-specific monograms instead of the computer symbol; very dark monochrome crests receive a documented contrast variant. Donor fields retain their real/fictional provenance. No original game content is committed here.
The prepared private dataset has 445 club/country entries, 3,334 players and 263 individual foreign club crests. Original German rosters and all 2,574 Original player word records are preserved by assertions during preparation. The visual review identified 175 usable supplied foreign crests and 88 missing/shared Original placeholders. Those 88 now have explicit fictional club-specific monograms instead of the computer symbol; the updated crest preparation uses the bright Original background texture and preserves black logo details. Donor fields retain their real/fictional provenance. No original game content is committed here.
Validation: 37 configured synthetic tests executed successfully, with 158 external-input tests explicitly skipped; four offline preparation tests passed. Extended save/reload and both cross-profile rejection paths passed. Two separate season-end snapshots each contain every fixture in all nine leagues. A Classic 80-turn run produces a byte-identical save to stable 1.0.2. Screenshots and saves are archived privately. Native platform CI also builds and tests Windows x64, macOS ARM64 and Linux x64; release QA receipts identify the exact successful revision. See [FORMAT.md](FORMAT.md) for dimensions, preparation and distribution boundaries. A development commit is not a completed release claim.
The next community package uses a data-only `COMMUNITY.OBD` bundle and no DOS executables. See [STANDALONE.md](STANDALONE.md). The Windows community ZIP omits source archives and loose PNG/JPEG studies; corresponding sources remain available separately.
+9
View File
@@ -0,0 +1,9 @@
# OpenBMH 1.1 Beta 2
Bei Rückfragen zum Bau von Stadionplätzen und Peripherie bleibt die aktuelle Stadionansicht jetzt sichtbar. Das gilt auch für gedrückte Schaltflächen und nachfolgende Zahlungs-, Zuschuss- und Entschädigungshinweise. Der zuvor schwarze Hintergrund ist behoben.
Die Änderung betrifft die Darstellung; Baupreise, Bauzeiten und Spielstände bleiben unverändert. Bestehende 1.1-Daten und Spielstände können weiterverwendet werden. Bei einem bestehenden Community-Paket die Programmdateien aktualisieren und die eigene `COMMUNITY.OBD` sowie Spielstände behalten.
Downloads für Windows x64, macOS ARM64 und Linux x64 sowie ein passendes Source-Archiv. Originale Spieldaten sind nicht enthalten. Der Dateneditor `obdeddi` bleibt ein separater Download. Die stabile Classic-Linie 1.0 bleibt unabhängig; 1.2 wird weiterhin separat entwickelt und ist kein Bestandteil dieses Releases.
Der Fix wurde unter Linux mit Original-Assets, Pixelvergleichen und Bauablauf-Tests geprüft. Native Plattform-Builds und synthetische Tests sind über `QA-REPORT.json` und `SHA256SUMS` dokumentiert. Eine vollständige menschliche Spielprüfung auf allen Plattformen wird damit nicht behauptet.
+54 -52
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/badge_policy.hpp"
#include "formats/executable_layout.hpp"
#include "app/scene_timing.hpp"
#include "formats/data_profile.hpp"
#include "game/profile_runtime.hpp"
#include "ui/live_timing.hpp"
@@ -208,8 +209,7 @@ int main(int argc, char** argv) {
playback.set_volume(volume);
std::optional<uint64_t> audio_session;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
const std::string window_title = std::string("OpenBMH ") + bmh::kOpenBmhVersion +
(english_game ? " - Football Limited (experimental)" : "");
const std::string window_title = "OpenBMH 1.1";
SDL_Window* window = SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE);
if (!window) throw FormatError(SDL_GetError());
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
@@ -331,7 +331,7 @@ int main(int argc, char** argv) {
std::optional<Image> season_backdrop;
auto present_season = [&](const Image& image, const char* title,
const Palette* palette_override = nullptr) {
SDL_SetWindowTitle(window, title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
season_backdrop = image;
const Palette& frame_palette = palette_override ? *palette_override : palette;
const Image painted = process_timer_image(image);
@@ -598,7 +598,7 @@ int main(int argc, char** argv) {
"_" + std::to_string(fixture.fixture) + "_" + std::to_string(sportschau_step_index++);
present_season(sportschau_replay_screen->render_report(step), title.c_str());
const int raw = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField4) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField4) : 0;
if (step.minute_wait) source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw));
if (step.minute_wait) source_tick_wait(unsigned((app::scene_frame_delay((raw < 6 ? raw / 2 : raw)*20)+19)/20));
if (step.chance_wait) source_tick_wait(50);
return skip;
};
@@ -619,7 +619,7 @@ int main(int argc, char** argv) {
const auto delay = [&](int row) {
const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(row * 9);
const int raw = state.memory.has(address) ? state.memory.u8(address) : 0;
source_tick_wait(unsigned(raw < 6 ? raw / 2 : raw));
source_tick_wait(unsigned((app::scene_frame_delay((raw < 6 ? raw / 2 : raw)*20)+19)/20));
};
present_season(backdrop, ("OpenBMH - sportschau_scene_header_" + id).c_str(), &colors);
delay(12); // AdvanceStep(12), header preview in ShotAnimation
@@ -630,7 +630,7 @@ int main(int argc, char** argv) {
std::to_string(i)).c_str(), &colors);
const unsigned retraces = i == 0 ? 40u :
(state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2) : 0u);
wait_source_retraces(retraces); // FirstThen: first40, then F8
SDL_Delay(Uint32(live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(int(retraces)*1000/70))); // FirstThen: first40, then F8
}
}
const auto frames = live_screen.render_shot(frame, scene.shot, &backdrop);
@@ -638,7 +638,7 @@ int main(int argc, char** argv) {
present_season(frames[i], ("OpenBMH - sportschau_shot_" + id + "_" +
std::to_string(i)).c_str(), &colors);
const int speed = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ? int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField))) : 0;
wait_source_retraces(unsigned(std::max(0, speed)));
SDL_Delay(Uint32(live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(std::max(0,speed)*1000/70)));
}
source_tick_wait(10); // LiveMatchdayFrame's final ten ticks
if (!running) return;
@@ -1361,7 +1361,7 @@ int main(int argc, char** argv) {
auto page=staged.current_league_table_dispatch(error);
if(!page)throw FormatError(error);
const auto present=[&](const Image& frame,const std::string& title) {
SDL_SetWindowTitle(window,title.c_str());season_backdrop=frame;
SDL_SetWindowTitle(window, "OpenBMH 1.1");season_backdrop=frame;
const auto painted=process_timer_image(frame);
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[painted.pixels[i]];
if(SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4)!=0 ||
@@ -1750,7 +1750,7 @@ int main(int argc, char** argv) {
"OpenBMH - live_substitution_notice") == PendingOfferAnswer::unsupported)
throw FormatError("live substitution notice presenter stopped");
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, parent_title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
bool completed = false;
const int selected_manager = selected_team >= 0 ? state.manager_of(selected_team) : -1;
@@ -1780,7 +1780,7 @@ int main(int argc, char** argv) {
return (screen.extras().native_display_word & 8)
? "OpenBMH - live_pitch" : "OpenBMH - live_lineup";
};
SDL_SetWindowTitle(window, live_title());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
bool closed = false;
const auto apply_live_pitch = [&](const ui::PitchRequest& action) {
if (action.kind == ui::PitchRequestKind::none) return;
@@ -1819,7 +1819,7 @@ int main(int argc, char** argv) {
? "Der Spielerwechsel ist nicht freigegeben." : result.error);
}
}
SDL_SetWindowTitle(window, live_title());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
bool left_held = false, left_release_consumed = false, right_held = false;
while (running && !closed) {
@@ -1883,7 +1883,7 @@ int main(int argc, char** argv) {
scope_finished = true;
completed = true;
}
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} catch (const std::exception& e) {
if (scope_started && !scope_finished)
dispatch_scope(app::LiveInterventionBoundary::abort, 2,
@@ -1967,7 +1967,7 @@ int main(int argc, char** argv) {
const Image image = table_screen ? table_screen->render()
: pairings_screen ? pairings_screen->render()
: strengths_screen ? strengths_screen->render() : cup_screen->render();
SDL_SetWindowTitle(window, overview_title().c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -1989,7 +1989,7 @@ int main(int argc, char** argv) {
std::optional<ui::TableRangeDialogOutcome> outcome;
const auto show_dialog = [&] {
const Image image = dialog.render();
SDL_SetWindowTitle(window, "OpenBMH - live_table_range");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2170,7 +2170,7 @@ int main(int argc, char** argv) {
if (!live_skipped) {
const auto frame = ui::live_matchday_frame(minute, groups, state);
if (!frame.matches.empty()) {
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image live_image = live_screen.render(frame);
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[live_image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2191,7 +2191,7 @@ int main(int argc, char** argv) {
ui::IncomingTransferScreen offer_screen(data,
ui::incoming_transfer_decision_from_game(state, view),
state.memory.u8(::bmh::layout::TextGradientDisabled) == 0);
SDL_SetWindowTitle(window, "OpenBMH - incoming_transfer");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Uint32 notice_started = SDL_GetTicks();
bool offer_dirty = true;
// Keep the original synchronous decision stack suspended here.
@@ -2260,7 +2260,7 @@ int main(int argc, char** argv) {
decision_screen.begin_outcome(decision.offers.offer_count,
decision.accepted ? decision.selected_bid_index : -1, state.memory.u8(::bmh::layout::OutcomeDelayDisabled));
}
SDL_SetWindowTitle(window, confirmation ? "OpenBMH - transfer_confirmation" : "OpenBMH - transfer_evaluation");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Uint32 started = SDL_GetTicks();
uint64_t rendered_phase = UINT64_MAX;
// The observer only presents the engine's settled decision. Keep
@@ -2299,7 +2299,7 @@ int main(int argc, char** argv) {
// Other season animations remain separate implementation work.
for (auto view : ui::season_entrants_from_game(state, season_exe, season_texts)) {
ui::SeasonEntrantsScreen entrants_screen(data, std::move(view));
SDL_SetWindowTitle(window, "OpenBMH - season_entrants");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image image = entrants_screen.render();
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2341,11 +2341,13 @@ int main(int argc, char** argv) {
// after the tip question has returned, before the outer ACK.
const Image backdrop = flow.stadium()->construction_notice_backdrop();
auto view = ui::construction_notice_dialog(staged, season_exe, notice);
std::optional<ui::GameEndRenderOptions> effective_options;
const auto& stadium_owner = flow.stadium()->state();
std::optional<ui::GameEndRenderOptions> effective_options =
ui::GameEndRenderOptions{stadium_owner.plain_background, stadium_owner.gradient_text, true};
if (flow.stadium()->state().block_expansion || flow.stadium()->state().quoted_object) {
const auto& owner = flow.stadium()->state();
view.compact_dialog_frame = owner.compact_dialog_frame;
effective_options = ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text};
effective_options = ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text, true};
}
const char* title = notice.kind == ConstructionNoticeKind::InsufficientFunds
? "OpenBMH - stadium_funds_notice" : "OpenBMH - stadium_sponsor_notice";
@@ -2359,7 +2361,7 @@ int main(int argc, char** argv) {
view.compact_dialog_frame = owner.compact_dialog_frame;
if (present_pending_dialog(staged, view, backdrop,
"OpenBMH - stadium_ticket_compensation_notice",
ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text}) == PendingOfferAnswer::unsupported)
ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text, true}) == PendingOfferAnswer::unsupported)
throw std::runtime_error("compensation notice presenter stopped");
}, sportschau_presenter,
[&](const GameState& staged, const AdvertisingRenewal& renewal, const Image& backdrop)
@@ -2423,7 +2425,7 @@ int main(int argc, char** argv) {
// SDLFlushEvents3 is a timed Source notice. Do not let its release
// event become another click in the resumed parent screen.
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, parent_title);
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto open_live_tactics = [&](int side, int y) {
const auto frame = ui::live_matchday_frame(minute, groups, state);
@@ -2449,7 +2451,7 @@ int main(int argc, char** argv) {
tactics_game.memory.set8(::bmh::layout::ActiveManager, uint8_t(selected_manager));
ui::TacticsScreen screen(data,
ui::tactics_from_game(tactics_game, season_exe, live_revision));
SDL_SetWindowTitle(window, "OpenBMH - live_tactics");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
bool closed = false;
std::optional<SDL_MouseButtonEvent> tactics_down;
bool source_completed = false;
@@ -2503,7 +2505,7 @@ int main(int argc, char** argv) {
selected_manager, selected_team, scope_error);
scope_active = false;
}
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} catch (const std::exception& e) {
if (scope_active)
dispatch_scope(app::LiveInterventionBoundary::abort, 8,
@@ -2522,7 +2524,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_SetWindowTitle(window, "OpenBMH - live_paused");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
SDL_RenderPresent(renderer);
bool resumed = false;
@@ -2541,12 +2543,12 @@ int main(int argc, char** argv) {
}
if (!resumed && running) SDL_Delay(8);
}
if (running) SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
if (running) SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto restore_live_frame = [&] {
if (!running) return;
const Image image = live_screen.render(ui::live_matchday_frame(minute, groups, state));
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2611,7 +2613,7 @@ int main(int argc, char** argv) {
std::unique_ptr<ui::SettingsReadmeScreen> readme;
const auto render_settings = [&] {
const Image image = readme ? readme->render() : screen.render();
SDL_SetWindowTitle(window, readme ? "OpenBMH - settings_readme" : "OpenBMH - live_settings");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2632,7 +2634,7 @@ int main(int argc, char** argv) {
ui::SaveLoadFileKind::settings, menu_request.origin_item_id);
const auto render_file = [&] {
const Image image = file_screen.render();
SDL_SetWindowTitle(window, "OpenBMH - live_settings_file");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i)
pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2778,7 +2780,7 @@ int main(int argc, char** argv) {
screen.consume_release();
settings_down.reset();
SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP);
SDL_SetWindowTitle(window, "OpenBMH - live_settings");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
} else {
screen.reject(error.empty() ? "Diese Einstellung wurde nicht übernommen." : error);
std::fprintf(stderr, "live settings: %s\n", error.c_str());
@@ -2933,7 +2935,7 @@ int main(int argc, char** argv) {
const std::string title = "OpenBMH - live_ball_" + std::to_string(event.minute) + "_" +
std::to_string(event.group) + "_" + std::to_string(event.match) + "_" +
std::to_string(event.displacement) + "_" + std::to_string(index);
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto* chance = live_chance_context &&
live_chance_context->minute == event.minute &&
live_chance_context->group == event.group &&
@@ -2948,13 +2950,13 @@ int main(int argc, char** argv) {
// AdvanceStep(5) reads a252c; DecodeTaxAnimationScript2 uses 20ms ticks.
// Retain key/mouse events for the live-minute input boundary.
const int delay = live_frame_ms_explicit ? live_frame_ms :
source_delay(5);
app::scene_frame_delay(source_delay(5));
if (delay > 0) SDL_Delay(Uint32(delay));
}
if (running) {
const int final_delay = live_frame_ms_explicit ? live_frame_ms : source_delay(6);
const int final_delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay(source_delay(6));
if (final_delay > 0) SDL_Delay(Uint32(final_delay));
SDL_SetWindowTitle(window, "OpenBMH - live_matchday");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
present(live_screen.render(frame));
}
}, [&](const LiveChanceEvent& event, const std::vector<MatchGroup>& groups,
@@ -2969,7 +2971,7 @@ int main(int argc, char** argv) {
std::to_string(event.minute) + "_" + std::to_string(event.group) + "_" +
std::to_string(event.match) + "_" + std::to_string(event.side) + "_" +
std::to_string(event.kind) + "_" + std::to_string(int(event.goal));
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const Image image = live_screen.render_chance(frame, chance);
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
@@ -2987,7 +2989,7 @@ int main(int argc, char** argv) {
const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9);
const int saved = state.memory.has(address) ? state.memory.u8(address) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms :
(saved < 6 ? saved / 2 : saved) * 20;
app::scene_frame_delay((saved < 6 ? saved / 2 : saved) * 20);
if (delay > 0) SDL_Delay(Uint32(delay));
if (event.stage == LiveChanceStage::result) live_chance_context.reset();
}, [&](const LiveShotEvent& event, const std::vector<MatchGroup>& groups,
@@ -3002,7 +3004,7 @@ int main(int argc, char** argv) {
std::to_string(event.acting_side) + "_" + std::to_string(int(event.miss));
for (size_t index = 0; index < frames.size() && running; ++index) {
const std::string title = "OpenBMH - live_shot_" + identity + "_" + std::to_string(index);
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = shot_colors.argb[frames[index].pixels[i]];
SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4);
SDL_RenderClear(renderer);
@@ -3017,7 +3019,7 @@ int main(int argc, char** argv) {
// Source waits Main_FormatError_RuntimeField vertical retraces after each frame (70 Hz).
const int retraces = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField) ?
std::max(0, int(int8_t(state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField)))) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms : retraces * 1000 / 70;
const int delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay(retraces * 1000 / 70);
if (delay > 0) SDL_Delay(Uint32(delay));
}
if (!running) return;
@@ -3027,7 +3029,7 @@ int main(int argc, char** argv) {
if (state.memory.has(::bmh::layout::Main_FormatError_RuntimeField5) && state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField5) == 0) {
// SDLFlushEvents2 accepts a fresh left/right press, not a keyboard skip.
const std::string title = "OpenBMH - live_shot_wait_" + identity;
SDL_SetWindowTitle(window, title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP);
SDL_Event input;
bool acknowledged = false;
@@ -3045,7 +3047,7 @@ int main(int argc, char** argv) {
} else {
// AdvanceStep(15): the ordinary saved pause instead of a click.
const int saved = state.memory.has(::bmh::layout::Main_FormatError_RuntimeField7) ? state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField7) : 0;
const int delay = live_frame_ms_explicit ? live_frame_ms : (saved < 6 ? saved / 2 : saved) * 20;
const int delay = live_frame_ms_explicit ? live_frame_ms : app::scene_frame_delay((saved < 6 ? saved / 2 : saved) * 20);
if (delay > 0) SDL_Delay(Uint32(delay));
}
}, [&](const LiveSetPieceEvent& event, const std::vector<MatchGroup>& groups,
@@ -3062,7 +3064,7 @@ int main(int argc, char** argv) {
std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+
std::to_string(event.source_side)+"_"+std::to_string(event.kind)+"_"+
std::to_string(index)+"_"+std::to_string(images.size());
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[images[index].pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
@@ -3071,7 +3073,7 @@ int main(int argc, char** argv) {
// FirstThen holds the first frame for 40 retraces; later frames
// use saved Main_FormatError_RuntimeField2. Keyboard/mouse input remains for the minute hook.
const int retraces=index==0?40:(state.memory.has(::bmh::layout::Main_FormatError_RuntimeField2)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField2):0);
const int delay=live_frame_ms_explicit?live_frame_ms:retraces*1000/70;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(retraces*1000/70);
if (delay>0) SDL_Delay(Uint32(delay));
}
if (running && !live_frame_ms_explicit) SDL_Delay(200); // LiveMatchdayFrame
@@ -3089,7 +3091,7 @@ int main(int argc, char** argv) {
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
};
SDL_SetWindowTitle(window,title.c_str());present(live_screen.render_booking(frame,booking));
SDL_SetWindowTitle(window, "OpenBMH 1.1");present(live_screen.render_booking(frame,booking));
if (event.kind != 2 && app::match_sound_enabled(state))
app::original_audio_command(playback, 17); // EventImpl/SDLPumpEvents, no injury whistle.
SDL_PumpEvents();SDL_Event input;
@@ -3097,10 +3099,10 @@ int main(int argc, char** argv) {
const int pause=event.kind==0?3:4;
const uint32_t address=::bmh::layout::Main_FormatError_ExecutableFieldUnsigned+uint32_t(pause*9);
const int saved=state.memory.has(address)?state.memory.u8(address):0;
const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
if (delay>0) SDL_Delay(Uint32(delay));
// EventImpl clears the box after its pause; no Source click wait here.
SDL_SetWindowTitle(window,"OpenBMH - live_matchday");present(live_screen.render(frame));
SDL_SetWindowTitle(window, "OpenBMH 1.1");present(live_screen.render(frame));
}, [&](const LiveShootoutEvent& event, const std::vector<MatchGroup>& groups,
const GameState& state) {
if (!running || live_skipped) return;
@@ -3111,7 +3113,7 @@ int main(int argc, char** argv) {
std::to_string(event.group)+"_"+std::to_string(event.match)+"_"+
std::to_string(event.side)+"_"+std::to_string(event.round)+"_"+
std::to_string(event.of)+"_"+std::to_string(event.player);
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto image=live_screen.render_shootout(frame,projection);
for (size_t i=0;i<pixels.size();++i) pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
@@ -3120,21 +3122,21 @@ int main(int argc, char** argv) {
if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) { running=false;return; }
const int repeats=event.stage==LiveShootoutStage::preview?4:2;
const int saved=state.memory.has(::bmh::layout::Main_FormatError_RuntimeField6)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField6):0;
const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int delay=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
for (int i=0;i<repeats && running;++i) if (delay>0) SDL_Delay(Uint32(delay));
}, [&](const LiveRealityEvent& event, const std::vector<MatchGroup>& groups,
const GameState& state) -> bool {
if (!running || live_skipped) return false;
const auto frame = ui::live_matchday_frame(event.minute,groups,state);
const auto present = [&](const Image& image,const Palette& colors,const std::string& title) {
SDL_SetWindowTitle(window,title.c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
for (size_t i=0;i<pixels.size();++i) pixels[i]=colors.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
SDL_RenderClear(renderer);SDL_RenderCopy(renderer,texture,nullptr,nullptr);SDL_RenderPresent(renderer);
};
const auto delay = [&](uint32_t address) {
const int saved=state.memory.has(address)?state.memory.u8(address):0;
const int ms=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20;
const int ms=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay((saved<6?saved/2:saved)*20);
if (ms>0) SDL_Delay(Uint32(ms));
};
const std::string identity=std::to_string(event.minute)+"_"+std::to_string(event.group)+"_"+
@@ -3154,7 +3156,7 @@ int main(int argc, char** argv) {
}
if (event.stage==LiveRealityStage::settling) {
reality_field.reset();
const int ms=live_frame_ms_explicit?live_frame_ms:200; // DecodeTaxAnimationScript2(10)
const int ms=live_frame_ms_explicit?live_frame_ms:app::scene_frame_delay(200); // DecodeTaxAnimationScript2(10)
if (ms>0) SDL_Delay(Uint32(ms));
return false;
}
@@ -3229,7 +3231,7 @@ int main(int argc, char** argv) {
}
}
if(!flow.timed_notice_open())timed_notice_presented_at.reset();
SDL_SetWindowTitle(window, ("OpenBMH - " + flow.screen_name()).c_str());
SDL_SetWindowTitle(window, "OpenBMH 1.1");
};
const auto present_formation_save_feedback = [&] {
for (bool restored : {false, true}) {
@@ -3731,7 +3733,7 @@ int main(int argc, char** argv) {
} else if (flow.desktop() && flow.desktop()->socket_confirmation_armed()) {
// SDLSetWindowTitle paints its pressed socket sprite before
// DeskDate waits for the physical release.
SDL_SetWindowTitle(window, "OpenBMH - desktop");
SDL_SetWindowTitle(window, "OpenBMH 1.1");
const auto image=process_timer_image(flow.render());
for(size_t i=0;i<pixels.size();++i)pixels[i]=palette.argb[image.pixels[i]];
SDL_UpdateTexture(texture,nullptr,pixels.data(),320*4);
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <algorithm>
namespace bmh::app {
// Presentation only: 25% more time per scene frame, without gameplay/RNG changes.
constexpr int scene_frame_delay(int milliseconds) { return std::max(16,(milliseconds*5+3)/4); }
}
+1
View File
@@ -12,6 +12,7 @@ inline int original_foreign_badge_end = 138;
inline bool expanded_badges = false;
inline int original_badge_gate(const LeImage& exe) {
if(const auto* policy=exe.runtime_policy())return int(policy->badge_end);
constexpr auto instruction = layout::ForeignBadgeGateInstruction;
if (exe.contains(instruction) && exe.contains(instruction + 6) &&
exe.u8(instruction) == 0x66 && exe.u8(instruction + 1) == 0x81 &&
+3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/binary.hpp"
#include "formats/resource_bundle.hpp"
#include <fstream>
#include <iterator>
@@ -7,6 +8,8 @@
namespace bmh {
Bytes read_file(const std::filesystem::path& path) {
if (!std::filesystem::exists(path))
if (auto bytes=bundled_resource(path)) return std::move(*bytes);
std::ifstream in(path, std::ios::binary);
if (!in) throw FormatError("cannot open " + path.string());
return Bytes(std::istreambuf_iterator<char>(in), {});
+6 -2
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/data_profile.hpp"
#include "formats/resource_bundle.hpp"
#include <fstream>
#include <numeric>
#include <set>
@@ -24,8 +25,11 @@ void DataProfile::validate() const {
}
DataProfile load_data_profile(const std::filesystem::path& directory) {
const auto file=directory/"OBMHPROF.INI";
if(!std::filesystem::exists(file))return {};
std::ifstream input(file);if(!input)throw FormatError("profile: cannot read metadata");
if(!resource_exists(file))return {};
return decode_data_profile(read_file(file));
}
DataProfile decode_data_profile(const Bytes& raw) {
std::istringstream input(std::string(raw.begin(),raw.end()));
std::string line,id;bool section=false,seen=false;
while(std::getline(input,line)) {
if(!line.empty()&&line.back()=='\r')line.pop_back();
+1
View File
@@ -20,5 +20,6 @@ struct DataProfile {
void validate() const;
static DataProfile international_11();
};
DataProfile decode_data_profile(const Bytes&);
DataProfile load_data_profile(const std::filesystem::path& directory);
}
+43
View File
@@ -18,6 +18,10 @@ struct Object {
} // namespace
std::string LeImage::cstring(uint32_t address) const {
if (runtime_policy_) {
const auto label=runtime_policy_->labels.find(address);
if(label!=runtime_policy_->labels.end())return label->second;
}
std::string s;
while (contains(address) && u8(address) != 0) s.push_back(char(u8(address++)));
return s;
@@ -37,6 +41,25 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
if (!file) throw FormatError("cannot write the OpenBMH image");
}
void save_runtime_image(const LeImage& image, const RuntimePolicy& policy, const std::filesystem::path& path) {
constexpr uint32_t start=layout::GermanDataSegmentBegin;
if(!image.contains(start) || policy.year<1600 || policy.year>9999 || policy.weekday>6 ||
(policy.badge_end!=90 && policy.badge_end!=138) || policy.environment_verified>1 || policy.labels.size()>16)
throw FormatError("runtime data: unsupported source policies");
const uint32_t size=image.base()+image.size()-start;
if(size>1024*1024)throw FormatError("runtime data: data segment too large");
Bytes out{'O','B','M','H','D','A','T','1'};
const auto put=[&](uint32_t value){for(int b=0;b<4;++b)out.push_back(uint8_t(value>>(8*b)));};
for(uint32_t value:{start,size,policy.year,policy.weekday,policy.badge_end,policy.environment_verified,uint32_t(policy.labels.size())})put(value);
out.insert(out.end(),image.data(start),image.data(start)+size);
for(const auto& [address,text]:policy.labels) {
if(text.size()>1024)throw FormatError("runtime data: label too long");
put(address);put(uint32_t(text.size()));out.insert(out.end(),text.begin(),text.end());
}
std::ofstream file(path,std::ios::binary|std::ios::trunc);file.write(reinterpret_cast<const char*>(out.data()),std::streamsize(out.size()));
if(!file)throw FormatError("cannot write runtime data");
}
LeImage load_le(const std::filesystem::path& path) {
const auto profile = load_data_profile(path.parent_path());
const auto apply_profile = [&](LeImage img) {
@@ -89,6 +112,26 @@ LeImage load_le(const std::filesystem::path& path) {
return img;
};
const Bytes raw = read_file(path);
if(raw.size()>=8 && std::string(raw.begin(),raw.begin()+8)=="OBMHDAT1") {
if(raw.size()<36)throw FormatError("runtime data: truncated header");
const uint32_t base=le32(raw,8),size=le32(raw,12),labels=le32(raw,32);
RuntimePolicy policy{le32(raw,16),le32(raw,20),le32(raw,24),le32(raw,28),{}};
if(base!=layout::GermanDataSegmentBegin || size>1024*1024 || size_t(size)+36>raw.size() || labels>16 ||
policy.year<1600 || policy.year>9999 || policy.weekday>6 || (policy.badge_end!=90 && policy.badge_end!=138) || policy.environment_verified>1)
throw FormatError("runtime data: invalid dimensions or policies");
auto image=LeImage::from_bytes(base,Bytes(raw.begin()+36,raw.begin()+36+size));
size_t at=36+size;
for(uint32_t i=0;i<labels;++i) {
if(at+8>raw.size())throw FormatError("runtime data: truncated label");
const auto address=le32(raw,at),length=le32(raw,at+4);at+=8;
if(length>1024 || at+length>raw.size() || !policy.labels.emplace(address,std::string(raw.begin()+at,raw.begin()+at+length)).second)
throw FormatError("runtime data: invalid label");
at+=length;
}
if(at!=raw.size())throw FormatError("runtime data: trailing bytes");
image.runtime_policy_=std::move(policy);
return apply_profile(std::move(image));
}
if (raw.size() >= sizeof kImageMagic + 8 && std::equal(kImageMagic, kImageMagic + sizeof kImageMagic, raw.begin())) {
const auto word = [&](size_t at) { return uint32_t(raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16) | uint32_t(raw[at + 3]) << 24; };
const uint32_t base = word(sizeof kImageMagic), size = word(sizeof kImageMagic + 4);
+11
View File
@@ -11,11 +11,18 @@
#include <cstdint>
#include <filesystem>
#include <string>
#include <map>
#include <optional>
#include "formats/binary.hpp"
namespace bmh {
// Resolved edition policies, not copied machine instructions.
struct RuntimePolicy {
uint32_t year=0, weekday=0, badge_end=0, environment_verified=0;
std::map<uint32_t,std::string> labels;
};
class LeImage {
public:
uint32_t base() const { return base_; }
@@ -44,10 +51,12 @@ public:
}
const Bytes& bytes() const { return bytes_; }
bool expanded_profile() const { return expanded_profile_; }
const RuntimePolicy* runtime_policy() const { return runtime_policy_ ? &*runtime_policy_ : nullptr; }
friend LeImage load_le(const std::filesystem::path& path);
private:
std::optional<RuntimePolicy> runtime_policy_;
bool expanded_profile_ = false;
uint32_t base_ = 0;
Bytes bytes_;
@@ -60,5 +69,7 @@ LeImage load_le(const std::filesystem::path& path);
// The OpenBMH image format: "OPENBMH-IMAGE" NUL, u32 base, u32 size, the bytes. load_le()
// reads it as well, so a translated image can stand in for BMH.exe in a data directory.
void save_image(const LeImage& image, const std::filesystem::path& path);
// Exports only the data segment and resolved policy values, never DOS/LE/code objects.
void save_runtime_image(const LeImage&, const RuntimePolicy&, const std::filesystem::path&);
} // namespace bmh
+17 -1
View File
@@ -40,7 +40,10 @@ Database load_database(const std::filesystem::path& path) {
}
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
Bytes d = read_file(path);
return decode_database(read_file(path),c);
}
Database decode_database(const Bytes& d,const DbCounts& c) {
Reader r{d};
Bytes lens = r.take(8);
size_t len_clubs = le16(lens, 0), len_players = le16(lens, 2), len_refs = le16(lens, 4), len_stadiums = le16(lens, 6);
@@ -74,4 +77,17 @@ Database load_database(const std::filesystem::path& path, const DbCounts& c) {
return db;
}
Bytes encode_database(const Database& db) {
Bytes out;
const auto put=[&](uint32_t value,int width){for(int i=0;i<width;++i)out.push_back(uint8_t(value>>(8*i)));};
const auto append=[&](const Bytes& bytes){out.insert(out.end(),bytes.begin(),bytes.end());};
for(const auto& pool:db.pools){if(pool.size()>65535)throw FormatError("M3D: string pool exceeds 16-bit offsets");put(uint32_t(pool.size()),2);}
append(db.raw_player_bonus_values);for(const auto& pool:db.pools)append(pool);
for(const auto* bytes:{&db.raw_club_name_offsets,&db.raw_player_name_offsets,&db.raw_database_metadata,&db.raw_club_auxiliary_words,
&db.raw_club_badge_selectors,&db.raw_foreign_club_strength,&db.raw_league_auxiliary_bytes,&db.raw_referee_properties,&db.raw_club_kit_selectors,&db.raw_club_short_name_offsets,&db.squad_list})append(*bytes);
for(int word=0;word<3;++word)for(const auto& player:db.players)put(word==0?player.w35c:word==1?player.w368:player.w364,4);
(void)decode_database(out,db.counts);
return out;
}
} // namespace bmh
+2
View File
@@ -78,5 +78,7 @@ struct Database {
Database load_database(const std::filesystem::path& path, const DbCounts& counts);
Database load_database(const std::filesystem::path& path);
Database decode_database(const Bytes&, const DbCounts&);
Bytes encode_database(const Database&);
} // namespace bmh
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/resource_bundle.hpp"
#include "miniz.h"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
namespace bmh {
namespace {
std::string folded(std::string name) {
std::transform(name.begin(),name.end(),name.begin(),[](unsigned char ch){return char(std::toupper(ch));});
return name;
}
struct Bundle {
Bytes file;
mz_zip_archive zip{};
std::map<std::string,mz_uint> entries;
explicit Bundle(const std::filesystem::path& path) {
const auto size=std::filesystem::file_size(path);
if(size>64*1024*1024)throw FormatError("community bundle exceeds size limit");
std::ifstream input(path,std::ios::binary);
file.assign(std::istreambuf_iterator<char>(input),{});
if(!input.is_open() || file.size()!=size || !mz_zip_reader_init_mem(&zip,file.data(),file.size(),0))
throw FormatError("cannot read community bundle");
try {
uint64_t total=0;
const auto count=mz_zip_reader_get_num_files(&zip);
if(count>4096)throw FormatError("community bundle has too many entries");
for(mz_uint i=0;i<count;++i) {
mz_zip_archive_file_stat st{};
if(!mz_zip_reader_file_stat(&zip,i,&st))throw FormatError("invalid community directory");
if(st.m_is_directory)continue;
const std::string name=st.m_filename;
const std::filesystem::path relative(name);
if(name.empty()||name.find('\\')!=std::string::npos||name.find(':')!=std::string::npos||relative.is_absolute())
throw FormatError("unsafe community resource name");
for(const auto& part:relative)if(part==".."||part==".")throw FormatError("unsafe community resource path");
total+=st.m_uncomp_size;
if(st.m_uncomp_size>32*1024*1024 || total>128*1024*1024 ||
!entries.emplace(folded(name),i).second)throw FormatError("ambiguous or oversized community resources");
}
}catch(...){mz_zip_reader_end(&zip);throw;}
}
~Bundle(){mz_zip_reader_end(&zip);}
};
std::mutex bundle_mutex;
struct Cached { std::filesystem::file_time_type modified; uintmax_t size; std::shared_ptr<Bundle> bundle; };
std::map<std::filesystem::path,Cached> cache;
std::pair<std::shared_ptr<Bundle>,std::string> locate(const std::filesystem::path& requested) {
auto path=std::filesystem::absolute(requested).lexically_normal();
auto root=path.parent_path();
for(int depth=0;depth<4 && !root.empty();++depth) {
const auto archive=root/kCommunityBundle;
std::error_code ec;
if(std::filesystem::is_regular_file(archive,ec)) {
const auto modified=std::filesystem::last_write_time(archive);
const auto size=std::filesystem::file_size(archive);
auto found=cache.find(archive);
if(found==cache.end()||found->second.modified!=modified||found->second.size!=size) {
auto bundle=std::make_shared<Bundle>(archive);
if(cache.size()>=4)cache.clear();
found=cache.insert_or_assign(archive,Cached{modified,size,std::move(bundle)}).first;
}
auto name=folded(path.lexically_relative(root).generic_string());
// Compatibility address-view API; the archive contains no EXE image.
if(name=="BMH.EXE")name="RUNTIME.DAT";
return {found->second.bundle,std::move(name)};
}
const auto parent=root.parent_path();if(parent==root)break;root=parent;
}
return {};
}
}
std::optional<Bytes> bundled_resource(const std::filesystem::path& path) {
std::lock_guard lock(bundle_mutex);
auto [bundle,name]=locate(path);if(!bundle)return std::nullopt;
const auto found=bundle->entries.find(name);if(found==bundle->entries.end())return std::nullopt;
mz_zip_archive_file_stat st{};mz_zip_reader_file_stat(&bundle->zip,found->second,&st);
Bytes result(size_t(st.m_uncomp_size));
if(!mz_zip_reader_extract_to_mem(&bundle->zip,found->second,result.data(),result.size(),0))
throw FormatError("damaged community resource: "+name);
return result;
}
bool resource_exists(const std::filesystem::path& path) {
std::error_code ec;if(std::filesystem::is_regular_file(path,ec))return true;
std::lock_guard lock(bundle_mutex);auto [bundle,name]=locate(path);
return bundle && bundle->entries.count(name)!=0;
}
}
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/binary.hpp"
#include <optional>
namespace bmh {
inline constexpr const char* kCommunityBundle = "COMMUNITY.OBD";
// Read-only package lookup. Loose user saves always remain outside the bundle.
std::optional<Bytes> bundled_resource(const std::filesystem::path& path);
bool resource_exists(const std::filesystem::path& path);
}
+1
View File
@@ -5,6 +5,7 @@
namespace bmh {
namespace { CalendarEpoch installed_epoch{2026, 2}; }
CalendarEpoch calendar_epoch_from_executable(const LeImage& exe) {
if(const auto* policy=exe.runtime_policy())return {int(policy->year),int(policy->weekday)};
constexpr auto setup = layout::CalendarDateSetup;
constexpr uint8_t weekday_prefix[] = {0xc6,0x44,0x24,0x04};
constexpr uint8_t month_and_year_prefix[] = {0xc6,0x44,0x24,0x0c,0x07,0xc7,0x04,0x24};
+1
View File
@@ -38,6 +38,7 @@ void install_environment_rules(const LeImage& exe) {
if (!exe.contains(at) || exe.u8(at)==0) { supported_environment=false; return; }
kEnvironmentStep[i]=int32_t(exe.u8(at))*1000;
}
if(const auto* policy=exe.runtime_policy()) { supported_environment=policy->environment_verified!=0;return; }
uint64_t fingerprint = 14695981039346656037ull;
for (const auto [first,last] : {std::pair{layout::EnvironmentVerifiedCodeBegin,layout::EnvironmentVerifiedCodeEnd},std::pair{layout::EnvironmentVerifiedHookBegin,layout::EnvironmentVerifiedHookEnd}}) {
if (!exe.contains(first) || !exe.contains(last-1)) { supported_environment=false; return; }
+1 -1
View File
@@ -14,7 +14,7 @@ std::optional<std::filesystem::path> choose_game_file(const std::string& title)
NFD::Guard guard;
NFD::UniquePathU8 path;
// one filter with all accepted kinds; the check after the choice decides
const nfdu8filteritem_t filters[] = {{"BMH game (ZIP, 7z, BMH.EXE, FLTD.EXE)", "zip,7z,exe"}};
const nfdu8filteritem_t filters[] = {{"BMH game (ZIP, 7z, BMH.EXE, FLTD.EXE)", "zip,7z,exe,obd"}};
const nfdresult_t result = NFD::OpenDialog(path, filters, 1);
if (result == NFD_CANCEL) return std::nullopt;
if (result != NFD_OKAY) throw std::runtime_error(std::string("no file dialog: ") + NFD::GetError());
+13 -5
View File
@@ -11,6 +11,8 @@
#include <system_error>
#include "formats/binary.hpp"
#include "formats/resource_bundle.hpp"
#include "formats/data_profile.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/textd.hpp"
@@ -52,6 +54,7 @@ struct Family {
const char* database;
};
constexpr Family kFamilies[] = {
{GameFamily::german, "COMMUNITY.OBD", 0, "TEXTD.BLK", "M3D.MAN"},
{GameFamily::german, "BMH.EXE", 602527, "TEXTD.BLK", "M3D.MAN"},
{GameFamily::english, "FLTD.EXE", 507925, "TEXTE.BLK", "M3E.MAN"},
{GameFamily::disk1994, "M3.EXE", 0, "", "M3PC.MAN"},
@@ -82,7 +85,7 @@ void require(GameCheck& c, const fs::path& dir, const std::string& name, uint64_
return;
}
std::error_code ec;
const uint64_t actual = fs::file_size(*p, ec);
const uint64_t actual = fs::exists(*p,ec) ? fs::file_size(*p, ec) : read_file(*p).size();
if (ec || actual == 0) c.problems.push_back(shown + " is empty or unreadable");
else if (size != 0 && actual != size)
c.problems.push_back(shown + " has " + std::to_string(actual) + " bytes instead of " + std::to_string(size));
@@ -90,7 +93,9 @@ void require(GameCheck& c, const fs::path& dir, const std::string& name, uint64_
// The shared picture/font/sound files of the sub directories KB, W, F and S.
void require_media(GameCheck& c) {
const bool bundled=fs::is_regular_file(c.directory/kCommunityBundle);
const auto sub = [&](const char* name) -> std::optional<fs::path> {
if(bundled)return c.directory/name;
auto p = find_file(c.directory, name);
if (!p || !fs::is_directory(*p)) {
c.problems.push_back(std::string("the directory ") + name + " is missing");
@@ -142,14 +147,15 @@ std::string text_title(const std::string& raw) {
void check_german(GameCheck& c) {
// (a translated English game has BMH.exe in the OpenBMH image format, launch/fltd.hpp)
const bool bundled=fs::is_regular_file(c.directory/kCommunityBundle);
bool image = false;
if (const auto exe = find_file(c.directory, "BMH.EXE")) {
if (const auto exe = find_file(c.directory, "BMH.EXE"); exe && !bundled) {
std::ifstream in(*exe, std::ios::binary);
char head[13] = {};
in.read(head, sizeof head);
image = std::string(head, sizeof head) == "OPENBMH-IMAGE";
}
require(c, c.directory, "BMH.EXE", image ? 0 : 602527, "BMH.EXE");
require(c, c.directory, "BMH.EXE", (image || bundled) ? 0 : 602527, bundled ? "RUNTIME.DAT" : "BMH.EXE");
require(c, c.directory, "TEXTD.BLK", 0, "TEXTD.BLK");
require(c, c.directory, "M3D.MAN", 0, "M3D.MAN");
for (const Required& r : kCommon) require(c, c.directory, r.name, r.size, r.name);
@@ -158,7 +164,8 @@ void check_german(GameCheck& c) {
// the files must also load: the engine reads tables from the EXE, the texts and the
// database of clubs and players
try {
load_le(*find_file(c.directory, "BMH.EXE"));
const auto runtime=load_le(*find_file(c.directory, "BMH.EXE"));
if(bundled && (!runtime.runtime_policy() || !runtime.expanded_profile()))throw FormatError("unsupported standalone runtime/profile");
} catch (const std::exception& e) {
c.problems.push_back(std::string("BMH.EXE cannot be read: ") + e.what());
}
@@ -212,7 +219,7 @@ bool is_game_file(const std::string& relative) {
const size_t dot = base.find_last_of('.');
if (dot == std::string::npos) return false;
const std::string ext = base.substr(dot + 1);
for (const char* e : {"EXE", "BLK", "MAN", "DAT", "MEN", "COL", "VGA", "FNT", "LBM", "EIN", "CFG", "FBM", "WAP"})
for (const char* e : {"EXE", "BLK", "MAN", "DAT", "MEN", "COL", "VGA", "FNT", "LBM", "EIN", "CFG", "FBM", "WAP", "OBD"})
if (ext == e) return true;
return false;
}
@@ -315,6 +322,7 @@ ResolvedGame resolve_game_unchecked(const fs::path& input, const fs::path& cache
std::optional<fs::path> find_file(const fs::path& directory, const std::string& name) {
std::error_code ec;
const fs::path exact = directory / path_from_utf8(name);
if(resource_exists(exact))return exact;
if (fs::exists(exact, ec)) return exact;
const std::string wanted = upper(name);
for (const auto& e : fs::directory_iterator(directory, ec))
+176
View File
@@ -0,0 +1,176 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "obdeddi/document.hpp"
#include "cli/json.hpp"
#include "formats/palette.hpp"
#include "miniz.h"
#include "Sha256.h"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <sstream>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>
#endif
namespace bmh::obdeddi {
namespace {
using Entries=std::map<std::string,Bytes>;
std::string upper(std::string s){for(char&c:s)if(c>='a'&&c<='z')c=char(c-'a'+'A');return s;}
std::string key(const Entries& entries,std::string name){for(const auto&[k,v]:entries)if(upper(k)==upper(name))return k;throw FormatError("Fehlende OBD-Ressource: "+name);}
Entries unpack(const Bytes& bytes) {
mz_zip_archive zip{};
if(bytes.size()>64*1024*1024 || !mz_zip_reader_init_mem(&zip,bytes.data(),bytes.size(),0))throw FormatError("OBD-Archiv ist ungueltig oder zu gross.");
Entries result;std::vector<std::string> names;uint64_t total=0;
try {
const auto count=mz_zip_reader_get_num_files(&zip);if(count>4096)throw FormatError("Zu viele OBD-Eintraege.");
for(mz_uint i=0;i<count;++i){mz_zip_archive_file_stat st{};if(!mz_zip_reader_file_stat(&zip,i,&st))throw FormatError("OBD-Verzeichnis beschaedigt.");if(st.m_is_directory)continue;
std::string name=st.m_filename;const std::filesystem::path path(name);
if(path.is_absolute()||name.find('\\')!=std::string::npos||name.find(':')!=std::string::npos)throw FormatError("Ungueltiger Ressourcenpfad.");
for(const auto&part:path)if(part==".."||part==".")throw FormatError("Ungueltiger Ressourcenpfad.");
if(std::find(names.begin(),names.end(),upper(name))!=names.end())throw FormatError("Doppelte OBD-Ressource.");names.push_back(upper(name));
total+=st.m_uncomp_size;if(st.m_uncomp_size>32*1024*1024||total>128*1024*1024)throw FormatError("OBD-Ressourcen zu gross.");
Bytes data(size_t(st.m_uncomp_size));if(!mz_zip_reader_extract_to_mem(&zip,i,data.data(),data.size(),0))throw FormatError("OBD-Pruefsumme fehlerhaft.");result.emplace(name,std::move(data));
}
}catch(...){mz_zip_reader_end(&zip);throw;}
mz_zip_reader_end(&zip);return result;
}
Bytes pack(const Entries& entries){
mz_zip_archive zip{};if(!mz_zip_writer_init_heap(&zip,0,0))throw FormatError("Archiv kann nicht erstellt werden.");
void*data=nullptr;size_t size=0;
try{for(const auto&[name,value]:entries)if(!mz_zip_writer_add_mem(&zip,name.c_str(),value.data(),value.size(),MZ_BEST_COMPRESSION))throw FormatError("Ressource kann nicht gespeichert werden.");
if(!mz_zip_writer_finalize_heap_archive(&zip,&data,&size))throw FormatError("Archivabschluss fehlgeschlagen.");
}catch(...){mz_zip_writer_end(&zip);throw;}
Bytes result(static_cast<uint8_t*>(data),static_cast<uint8_t*>(data)+size);mz_free(data);mz_zip_writer_end(&zip);return result;
}
void write(const std::filesystem::path& path,const Bytes& bytes){std::ofstream f(path,std::ios::binary|std::ios::trunc);f.write(reinterpret_cast<const char*>(bytes.data()),std::streamsize(bytes.size()));if(!f)throw FormatError("Datei kann nicht geschrieben werden.");f.close();if(!f)throw FormatError("Dateiabschluss fehlgeschlagen.");}
void word(Bytes& data,size_t pos,uint16_t value){data.at(pos)=uint8_t(value);data.at(pos+1)=uint8_t(value>>8);}
void rename(Bytes& pool,Bytes& offsets,size_t index,const std::string& name){
if(name.empty()||name.size()>255||std::any_of(name.begin(),name.end(),[](unsigned char c){return c<32||c>=127;}))throw FormatError("Name muss 1 bis 255 darstellbare Original-Zeichen enthalten.");
const size_t at=le16(offsets,index*2);std::string old;for(size_t i=at;i<pool.size()&&pool[i];++i)old+=char(pool[i]);if(old==name)return;
if(pool.size()+name.size()+1>65535)throw FormatError("Namenspool ist voll.");
word(offsets,index*2,uint16_t(pool.size()));pool.insert(pool.end(),name.begin(),name.end());pool.push_back(0);
}
struct Lock {
#ifdef _WIN32
HANDLE handle=INVALID_HANDLE_VALUE;
explicit Lock(std::filesystem::path path){path+=".obdeddi.lock";handle=CreateFileW(path.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_ALWAYS,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);if(handle==INVALID_HANDLE_VALUE)throw FormatError("Datei ist gesperrt oder nicht beschreibbar.");}
~Lock(){CloseHandle(handle);}
#else
int fd=-1;std::filesystem::path path;
explicit Lock(std::filesystem::path p):path(std::move(p)){path+=".obdeddi.lock";fd=open(path.c_str(),O_CREAT|O_RDWR,0600);if(fd<0)throw FormatError("Datei ist nicht beschreibbar.");if(flock(fd,LOCK_EX|LOCK_NB)){close(fd);fd=-1;throw FormatError("Datei ist gesperrt.");}}
~Lock(){if(fd>=0){unlink(path.c_str());close(fd);}}
#endif
};
}
std::string sha256(const Bytes& bytes){CSha256 state;Sha256_Init(&state);Sha256_Update(&state,bytes.data(),bytes.size());Byte digest[SHA256_DIGEST_SIZE];Sha256_Final(&state,digest);std::ostringstream text;for(auto b:digest)text<<std::hex<<std::setw(2)<<std::setfill('0')<<unsigned(b);return text.str();}
Document::Document(const std::filesystem::path& path):path_(std::filesystem::absolute(path)),original_(read_file(path)),entries_(unpack(original_)){
profile_=decode_data_profile(entries_.at(key(entries_,"OBMHPROF.INI")));profile_.validate();
const auto&raw=entries_.at(key(entries_,"PACKAGE.JSON"));const auto manifest=cli::parse_json(std::string(raw.begin(),raw.end()));
if(!manifest.object())throw FormatError("Ungueltiges OBD-Manifest.");
const auto it=manifest.object()->find("files");if(it==manifest.object()->end()||!it->second.object())throw FormatError("OBD-Pruefsummen fehlen.");
for(const auto&[name,hash]:*it->second.object())if(!hash.string()||sha256(entries_.at(key(entries_,name)))!=*hash.string())throw FormatError("OBD-Ressource wurde extern veraendert: "+name);
const auto& runtime=entries_.at(key(entries_,"RUNTIME.DAT"));if(runtime.size()<36 || std::string(runtime.begin(),runtime.begin()+8)!="OBMHDAT1")throw FormatError("Kein unterstuetztes eigenstaendiges OBD-Datenpaket.");
db_=decode_database(entries_.at(key(entries_,"M3D.MAN")),profile_.counts);refresh_owners();
}
void Document::refresh_owners(){owners_.assign(db_.players.size(),-1);for(uint32_t team=0;team<profile_.counts.league_teams;++team)for(uint32_t row=0;row<24;++row){int id=le16(db_.squad_list,(team*24+row)*2)&4095;if(id!=4095){if(size_t(id)>=owners_.size()||owners_[size_t(id)]!=-1)throw FormatError("Ungueltige oder doppelte Kaderzuordnung.");owners_[size_t(id)]=int(team);}}}
int Document::club_of(size_t id)const{return owners_.at(id);}
PlayerValues Document::player(size_t id)const{const auto&p=db_.players.at(id);PlayerValues v;v.name=p.name;v.position=p.position();v.nation=p.nationality()+((db_.raw_player_bonus_values.at(id)&128)?32:0);v.age=p.age();v.form=p.form();v.technique=p.technique();v.condition=p.condition();v.bonus=db_.raw_player_bonus_values.at(id)&127;for(int i=0;i<7;++i)v.skills[i]=p.skill(Player::Skill(i));return v;}
void Document::set_player(size_t id,const PlayerValues& v){
if(v.position<0||v.position>3||v.nation<0||v.nation>=62||v.age<16||v.age>47||v.form<0||v.form>99||v.technique<0||v.technique>99||v.condition<0||v.condition>99||v.bonus<0||v.bonus>127)throw FormatError("Spielerwert ausserhalb des Original-Bereichs.");
for(auto skill:v.skills)if(skill<0||skill>3)throw FormatError("Faehigkeiten liegen zwischen 0 und 3.");
auto next=db_;auto&p=next.players.at(id);rename(next.pools[1],next.raw_player_name_offsets,id,v.name);p.name=v.name;
p.w35c=(p.w35c&~0x1fffffu)|uint32_t(v.form)|uint32_t(v.technique)<<7|uint32_t(v.condition)<<14;
p.w364=(p.w364&~(3u|(31u<<21)))|uint32_t(v.position)|uint32_t(v.age-16)<<21;
uint32_t skills=0;for(int i=0;i<7;++i)skills|=uint32_t(v.skills[i])<<(i*2);
p.w368=(p.w368&0x07ffc000u)|skills|uint32_t(v.nation&31)<<27;
next.raw_player_bonus_values.at(id)=uint8_t(v.bonus|((v.nation>>5)<<7));
if(encode_database(next)!=encode_database(db_)){db_=std::move(next);dirty_=true;changes_.push_back("player:"+std::to_string(id));}
}
void Document::set_club(size_t id,std::string name,int kit,int start,int length){
if(kit<0||kit>255||start<0||start>15||length<1||length>16||size_t(start+length)>name.size())throw FormatError("Ungueltige Farbe oder Kurznamens-Auswahl.");
auto next=db_;rename(next.pools[0],next.raw_club_name_offsets,id,name);next.club_names.at(id)=std::move(name);next.raw_club_kit_selectors.at(id)=uint8_t(kit);
if(id<next.counts.n42)next.raw_club_short_name_offsets.at(id)=uint8_t((start<<4)|(length-1));
if(encode_database(next)!=encode_database(db_)){db_=std::move(next);dirty_=true;changes_.push_back("club:"+std::to_string(id));}
}
void Document::move_player(size_t id,int destination,int swap){
const int source=club_of(id);if(source<0||destination<0||destination>=int(profile_.counts.league_teams)||source==destination)throw FormatError("Kaderwechsel nur zwischen zwei Ligavereinen moeglich.");
auto find=[&](int team,int pid){for(int row=0;row<24;++row)if((le16(db_.squad_list,size_t(team*24+row)*2)&4095)==pid)return team*24+row;return -1;};
int from=find(source,int(id)),to=find(destination,swap<0?4095:swap);
if(to<0)throw FormatError("Zielkader ist voll; Tauschpartner auswaehlen.");
if(swap>=0 && (size_t(swap)>=owners_.size()||club_of(size_t(swap))!=destination))throw FormatError("Ungueltiger Tauschpartner.");
if(swap<0 && std::count(owners_.begin(),owners_.end(),source)<=11)throw FormatError("Der Quellverein braucht mindestens elf Spieler.");
auto slots=db_.squad_list;
if(swap>=0){const auto a=le16(slots,size_t(from)*2),b=le16(slots,size_t(to)*2);word(slots,size_t(from)*2,uint16_t((a&0xf000)|(b&4095)));word(slots,size_t(to)*2,uint16_t((b&0xf000)|(a&4095)));}
else{word(slots,size_t(to)*2,le16(slots,size_t(from)*2));word(slots,size_t(from)*2,4095);for(int team:{source,destination}){std::vector<uint16_t> list;for(int row=0;row<24;++row){auto v=le16(slots,size_t(team*24+row)*2);if((v&4095)!=4095)list.push_back(v);}for(int row=0;row<24;++row)word(slots,size_t(team*24+row)*2,row<int(list.size())?uint16_t((list[size_t(row)]&0x7fff)|(row<11?0x8000:0)):4095);}}
db_.squad_list=std::move(slots);refresh_owners();dirty_=true;changes_.push_back("roster:player:"+std::to_string(id)+":"+std::to_string(source)+">"+std::to_string(destination));
}
std::array<uint32_t,256> Document::palette() const {
const auto& data=entries_.at(key(entries_,"M3PC.COL"));if(data.size()!=768)throw FormatError("Ungueltige Palette.");
std::array<uint32_t,256> colors{};for(size_t i=0;i<256;++i)colors[i]=0xff000000u|uint32_t(vga_dac_rgb8(data[i*3]))<<16|uint32_t(vga_dac_rgb8(data[i*3+1]))<<8|vga_dac_rgb8(data[i*3+2]);return colors;
}
Image Document::logo_sheet(int page) const {
const auto name="W/"+std::to_string(page)+".VGA";
const auto changed=changed_assets_.find(name);if(changed!=changed_assets_.end())return decode_vga(changed->second);
return decode_vga(entries_.at(key(entries_,name)));
}
std::array<uint32_t,1444> Document::logo(size_t club) const {
if(club>=profile_.national_first)throw FormatError("Kein Vereinslogo.");
const int cell=le16(db_.raw_club_badge_selectors,club*2)&511;const auto sheet=logo_sheet(cell/8);if(sheet.width!=304||sheet.height!=38)throw FormatError("Ungueltiger Wappenbogen.");
const auto colors=palette();std::array<uint32_t,1444> out{};for(int y=0;y<38;++y)for(int x=0;x<38;++x)out[size_t(y*38+x)]=colors[sheet.pixels[size_t(y*304+(cell%8)*38+x)]];return out;
}
Image Document::convert_logo(const std::array<uint32_t,1444>& rgba) const {
const auto colors=palette();Image image(38,38,94);std::map<int,Image> sheets;
for(int y=0;y<38;++y)for(int x=0;x<38;++x){int votes[4]{};for(int club=0;club<90;++club){int cell=le16(db_.raw_club_badge_selectors,size_t(club)*2)&511;auto it=sheets.find(cell/8);if(it==sheets.end())it=sheets.emplace(cell/8,logo_sheet(cell/8)).first;if(it->second.width!=304||it->second.height!=38)throw FormatError("Ungueltiger Wappenbogen.");auto value=it->second.pixels[size_t(y*304+(cell%8)*38+x)];if(value>=92&&value<=95)++votes[value-92];}
const int background=92+int(std::max_element(votes,votes+4)-votes);auto c=rgba[size_t(y*38+x)];int alpha=int(c>>24);int red=(int(c>>16&255)*alpha+int(colors[size_t(background)]>>16&255)*(255-alpha)+127)/255;int green=(int(c>>8&255)*alpha+int(colors[size_t(background)]>>8&255)*(255-alpha)+127)/255;int blue=(int(c&255)*alpha+int(colors[size_t(background)]&255)*(255-alpha)+127)/255;
int best=0,distance=2147483647;for(int i=0;i<256;++i){int dr=int(colors[size_t(i)]>>16&255)-red,dg=int(colors[size_t(i)]>>8&255)-green,db=int(colors[size_t(i)]&255)-blue;int d=dr*dr+dg*dg+db*db;if(d<distance){best=i;distance=d;}}image.at(x,y)=uint8_t(best);
}return image;
}
std::array<uint32_t,1444> Document::preview_logo(const std::array<uint32_t,1444>& rgba) const {auto image=convert_logo(rgba);auto colors=palette();std::array<uint32_t,1444> out{};for(size_t i=0;i<1444;++i)out[i]=colors[image.pixels[i]];return out;}
void Document::set_logo(size_t club,const std::array<uint32_t,1444>& rgba){
if(club>=profile_.national_first)throw FormatError("Kein Vereinslogo.");
auto selectors=db_.raw_club_badge_selectors;const auto old=le16(selectors,club*2);int cell=old&511;int references=0;bool used[512]{};
for(size_t i=0;i<db_.counts.clubs;++i){int c=le16(selectors,i*2)&511;used[c]=true;references+=c==cell;}
if(references>1){auto free=std::find(used,used+512,false);if(free==used+512)throw FormatError("Keine freie Wappenzelle vorhanden.");cell=int(free-used);}
Image sheet;try{sheet=logo_sheet(cell/8);}catch(const std::out_of_range&){sheet=Image(304,38,94);}catch(const FormatError&){if(entries_.count("W/"+std::to_string(cell/8)+".VGA"))throw;sheet=Image(304,38,94);}
if(sheet.width!=304||sheet.height!=38)throw FormatError("Ungueltiger Wappenbogen.");auto image=convert_logo(rgba);
for(int y=0;y<38;++y)for(int x=0;x<38;++x)sheet.at((cell%8)*38+x,y)=image.at(x,y);
Bytes encoded;const auto put=[&](uint32_t v,int count){for(int i=0;i<count;++i)encoded.push_back(uint8_t(v>>(8*i)));};Bytes payload;
for(size_t i=0;i<sheet.pixels.size();i+=128){auto count=std::min(size_t(128),sheet.pixels.size()-i);payload.push_back(uint8_t(count-1));payload.insert(payload.end(),sheet.pixels.begin()+i,sheet.pixels.begin()+i+count);}payload.push_back(0);put(304,2);put(38,2);put(uint32_t(payload.size()),4);encoded.insert(encoded.end(),payload.begin(),payload.end());
const auto name="W/"+std::to_string(cell/8)+".VGA";changed_assets_[name]=std::move(encoded);word(db_.raw_club_badge_selectors,club*2,uint16_t((old&~511)|cell));dirty_=true;changes_.push_back("logo:club:"+std::to_string(club));
}
std::filesystem::path Document::save(){
if(!dirty_)return {};
Lock lock(path_);if(read_file(path_)!=original_)throw FormatError("OBD wurde seit dem Oeffnen extern geaendert. Bitte neu oeffnen.");
const auto master=encode_database(db_);
if(changed_assets_.empty()&&master==entries_.at(key(entries_,"M3D.MAN"))){dirty_=false;changes_.clear();return {};}
auto changed=entries_;changed[key(changed,"M3D.MAN")]=master;for(const auto&[name,data]:changed_assets_){auto found=std::find_if(changed.begin(),changed.end(),[&](const auto& item){return upper(item.first)==upper(name);});if(found==changed.end())changed[name]=data;else found->second=data;}
auto&manifestBytes=changed.at(key(changed,"PACKAGE.JSON"));auto manifest=cli::parse_json(std::string(manifestBytes.begin(),manifestBytes.end()));cli::Json::Object hashes;
for(const auto&[name,bytes]:changed)if(upper(name)!="PACKAGE.JSON")hashes.emplace(name,sha256(bytes));
(*manifest.object())["files"]=std::move(hashes);
const auto token=std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
cli::Json::Array records;for(const auto& change:changes_)records.emplace_back(change);
auto& history=(*manifest.object())["editor_history"];
if(!history.array())history=cli::Json::Array{};
std::get<cli::Json::Array>(history.value).emplace_back(cli::Json::Object{{"editor","obdeddi"},{"timestamp_epoch_ticks",token},{"source_sha256",sha256(original_)},{"changes",std::move(records)}});
const auto text=cli::dump_json(manifest);manifestBytes=Bytes(text.begin(),text.end());
const auto output=pack(changed);auto temp=path_;temp+=".tmp-"+token;
std::filesystem::path backup;
try{
write(temp,output);Document verified(temp);if(encode_database(verified.database())!=encode_database(db_))throw FormatError("Pruefung des neuen Archivs fehlgeschlagen.");
const auto backups=path_.parent_path()/"backups";std::filesystem::create_directories(backups);auto backupName=path_.filename();backupName+="."+token+".bak";backup=backups/backupName;
std::filesystem::copy_file(path_,backup);if(read_file(backup)!=original_)throw FormatError("Backup-Pruefung fehlgeschlagen.");
if(read_file(path_)!=original_)throw FormatError("OBD wurde waehrend des Speicherns extern geaendert.");
#ifdef _WIN32
if(!ReplaceFileW(path_.c_str(),temp.c_str(),nullptr,0,nullptr,nullptr))throw FormatError("OBD konnte nicht atomar ersetzt werden. Original und Backup bleiben erhalten.");
#else
std::filesystem::rename(temp,path_);
#endif
}catch(...){std::error_code ec;std::filesystem::remove(temp,ec);throw;}
entries_=std::move(changed);original_=output;dirty_=false;changes_.clear();changed_assets_.clear();return backup;
}
}
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/m3d.hpp"
#include "formats/data_profile.hpp"
#include <map>
#include <array>
#include "formats/vga.hpp"
namespace bmh::obdeddi {
struct PlayerValues {
std::string name;
int position=0,nation=0,age=16,form=0,technique=0,condition=0,bonus=0;
int skills[7]{};
};
class Document {
public:
explicit Document(const std::filesystem::path&);
const Database& database() const {return db_;}
const DataProfile& profile() const{return profile_;}
const std::filesystem::path& path() const{return path_;}
bool dirty() const{return dirty_;}
PlayerValues player(size_t) const;
int club_of(size_t player) const;
void set_player(size_t,const PlayerValues&);
void set_club(size_t,std::string name,int kit,int short_start,int short_length);
std::array<uint32_t,1444> logo(size_t club) const;
std::array<uint32_t,1444> preview_logo(const std::array<uint32_t,1444>& rgba) const;
void set_logo(size_t club,const std::array<uint32_t,1444>& rgba);
void move_player(size_t player,int club,int swap_player=-1);
// Returns the verified backup path, or an empty path for a no-op.
std::filesystem::path save();
private:
std::filesystem::path path_;
Bytes original_;
std::map<std::string,Bytes> entries_;
Database db_;
DataProfile profile_;
bool dirty_=false;
std::vector<int> owners_;
std::vector<std::string> changes_;
std::map<std::string,Bytes> changed_assets_;
Image logo_sheet(int page) const;
Image convert_logo(const std::array<uint32_t,1444>&) const;
std::array<uint32_t,256> palette() const;
void refresh_owners();
};
std::string sha256(const Bytes&);
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-only
#define NOMINMAX
#include "obdeddi/logo_transform_win32.hpp"
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <memory>
namespace bmh::obdeddi {
std::array<uint32_t,1444> transform_logo(Gdiplus::Bitmap& source,int x,int y,int width,int height,float angle,bool mirror_x,bool mirror_y){
if(x<0||y<0||width<=0||height<=0||int64_t(x)+width>source.GetWidth()||int64_t(y)+height>source.GetHeight()||!std::isfinite(angle)||std::abs(angle)>360)throw std::runtime_error("invalid logo transform");
std::unique_ptr<Gdiplus::Bitmap> cropped(source.Clone(Gdiplus::Rect(x,y,width,height),PixelFormat32bppARGB));if(!cropped||cropped->GetLastStatus()!=Gdiplus::Ok)throw std::runtime_error("logo crop failed");
Gdiplus::ImageAttributes edges;edges.SetWrapMode(Gdiplus::WrapModeTileFlipXY);
Gdiplus::Bitmap target(38,38,PixelFormat32bppARGB);
{Gdiplus::Graphics g(&target);g.Clear(Gdiplus::Color(0,0,0,0));g.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);g.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHighQuality);float radians=angle*3.14159265358979323846f/180,w=float(width),h=float(height);float extent=std::max(std::abs(std::cos(radians))*w+std::abs(std::sin(radians))*h,std::abs(std::sin(radians))*w+std::abs(std::cos(radians))*h);float scale=36/extent;g.TranslateTransform(19,19);g.RotateTransform(angle);g.ScaleTransform(mirror_x?-1.f:1.f,mirror_y?-1.f:1.f);if(g.DrawImage(cropped.get(),Gdiplus::RectF(-w*scale/2,-h*scale/2,w*scale,h*scale),0.f,0.f,w,h,Gdiplus::UnitPixel,&edges)!=Gdiplus::Ok)throw std::runtime_error("logo render failed");g.Flush(Gdiplus::FlushIntentionSync);}
std::array<uint32_t,1444> rgba{};for(int py=0;py<38;++py)for(int px=0;px<38;++px){Gdiplus::Color color;if(target.GetPixel(px,py,&color)!=Gdiplus::Ok)throw std::runtime_error("logo pixel read failed");rgba[size_t(py*38+px)]=color.GetValue();}return rgba;
}
}
+9
View File
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <windows.h>
#include <gdiplus.h>
#include <array>
#include <cstdint>
namespace bmh::obdeddi {
std::array<uint32_t,1444> transform_logo(Gdiplus::Bitmap&,int x,int y,int width,int height,float angle,bool mirror_x,bool mirror_y);
}
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-only
#define UNICODE
#define _UNICODE
#define NOMINMAX
#include <windows.h>
#include <commdlg.h>
#include <gdiplus.h>
#include "obdeddi/logo_win32.hpp"
#include "obdeddi/logo_transform_win32.hpp"
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
namespace bmh::obdeddi {
namespace {
struct Dialog {
HWND window=nullptr,owner=nullptr,edits[5]{},after=nullptr,apply=nullptr;HFONT font=nullptr;
Document* document=nullptr;size_t club=0;int dpi=96;bool done=false,accepted=false,mirrorX=false,mirrorY=false;
ULONG_PTR token=0;std::unique_ptr<Gdiplus::Bitmap> source;std::array<uint32_t,1444> before{},preview{},rgba{};
int px(int n)const{return MulDiv(n,dpi,96);}
HWND child(const wchar_t* cls,const wchar_t* text,DWORD style,int id,int x,int y,int w,int h){auto c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,text,WS_CHILD|WS_VISIBLE|style,px(x),px(y),px(w),px(h),window,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;}
std::wstring value(int n){wchar_t text[64]{};GetWindowTextW(edits[n],text,64);return text;}
void set(int n,int v){SetWindowTextW(edits[n],std::to_wstring(v).c_str());}
void whole(){if(!source)return;set(0,0);set(1,0);set(2,int(source->GetWidth()));set(3,int(source->GetHeight()));}
void update(){if(!source)return;try{int crop[4];for(int i=0;i<4;++i){auto s=value(i);size_t used=0;crop[i]=std::stoi(s,&used);if(used!=s.size())throw std::runtime_error("number");}auto angleText=value(4);std::replace(angleText.begin(),angleText.end(),L',',L'.');size_t used=0;float angle=std::stof(angleText,&used);if(used!=angleText.size()||!std::isfinite(angle)||angle < -360||angle>360)throw std::runtime_error("angle");
if(crop[0]<0||crop[1]<0||crop[2]<=0||crop[3]<=0||int64_t(crop[0])+crop[2]>source->GetWidth()||int64_t(crop[1])+crop[3]>source->GetHeight())throw std::runtime_error("crop");
rgba=transform_logo(*source,crop[0],crop[1],crop[2],crop[3],angle,mirrorX,mirrorY);preview=document->preview_logo(rgba);InvalidateRect(after,nullptr,TRUE);EnableWindow(apply,TRUE);
}catch(...){EnableWindow(apply,FALSE);MessageBoxW(window,L"Bitte einen gültigen Ausschnitt innerhalb des Bildes und einen Winkel zwischen -360 und 360 eingeben.",L"Vereinslogo",MB_OK|MB_ICONWARNING);}}
void import(){wchar_t path[32768]{};OPENFILENAMEW f{sizeof(f)};f.hwndOwner=window;f.lpstrFilter=L"Bilder (PNG, JPEG, BMP)\0*.png;*.jpg;*.jpeg;*.bmp\0\0";f.lpstrFile=path;f.nMaxFile=32768;f.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(!GetOpenFileNameW(&f))return;auto image=std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(path,FALSE));if(!image||image->GetLastStatus()!=Gdiplus::Ok||image->GetWidth()==0||image->GetHeight()==0||image->GetWidth()>16384||image->GetHeight()>16384||uint64_t(image->GetWidth())*image->GetHeight()>64000000){MessageBoxW(window,L"Das Bild konnte nicht geladen werden oder ist zu groß.",L"Vereinslogo",MB_OK|MB_ICONERROR);return;}source=std::move(image);mirrorX=mirrorY=false;set(4,0);whole();update();}
};
void draw(DRAWITEMSTRUCT* item,const std::array<uint32_t,1444>& pixels){FillRect(item->hDC,&item->rcItem,GetSysColorBrush(COLOR_WINDOW));BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);info.bmiHeader.biWidth=38;info.bmiHeader.biHeight=-38;info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;int size=std::min(int(item->rcItem.right-item->rcItem.left),int(item->rcItem.bottom-item->rcItem.top));int x=item->rcItem.left+(int(item->rcItem.right-item->rcItem.left)-size)/2,y=item->rcItem.top+(int(item->rcItem.bottom-item->rcItem.top)-size)/2;SetStretchBltMode(item->hDC,COLORONCOLOR);StretchDIBits(item->hDC,x,y,size,size,0,0,38,38,pixels.data(),&info,DIB_RGB_COLORS,SRCCOPY);}
LRESULT CALLBACK proc(HWND window,UINT message,WPARAM w,LPARAM l){auto* d=reinterpret_cast<Dialog*>(GetWindowLongPtrW(window,GWLP_USERDATA));if(message==WM_NCCREATE){d=static_cast<Dialog*>(reinterpret_cast<CREATESTRUCTW*>(l)->lpCreateParams);SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(d));d->window=window;}
if(!d)return DefWindowProcW(window,message,w,l);
if(message==WM_DRAWITEM){auto item=reinterpret_cast<DRAWITEMSTRUCT*>(l);draw(item,item->CtlID==51?d->before:d->preview);return TRUE;}
if(message==WM_COMMAND){switch(LOWORD(w)){case 10:d->import();break;case 11:d->whole();d->update();break;case 12:d->mirrorX=!d->mirrorX;d->update();break;case 13:d->mirrorY=!d->mirrorY;d->update();break;case 14:d->update();break;case IDOK:if(d->source){d->update();if(IsWindowEnabled(d->apply)){try{d->document->set_logo(d->club,d->rgba);d->accepted=true;SendMessageW(window,WM_CLOSE,0,0);}catch(const std::exception&){MessageBoxW(window,L"Das Logo konnte nicht übernommen werden. Bitte die Wappenzuordnung prüfen.",L"Vereinslogo",MB_OK|MB_ICONERROR);}}}break;case IDCANCEL:SendMessageW(window,WM_CLOSE,0,0);break;}return 0;}
if(message==WM_CLOSE){DestroyWindow(window);return 0;}if(message==WM_DESTROY){d->done=true;return 0;}return DefWindowProcW(window,message,w,l);}
}
bool edit_logo(HWND owner,Document& document,size_t club){Dialog d;d.owner=owner;d.document=&document;d.club=club;d.before=document.logo(club);d.preview=d.before;HDC dc=GetDC(owner);d.dpi=GetDeviceCaps(dc,LOGPIXELSX);ReleaseDC(owner,dc);Gdiplus::GdiplusStartupInput startup;if(Gdiplus::GdiplusStartup(&d.token,&startup,nullptr)!=Gdiplus::Ok)throw FormatError("Bildimport kann nicht gestartet werden.");
d.font=CreateFontW(-d.px(14),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.hbrBackground=GetSysColorBrush(COLOR_BTNFACE);wc.lpszClassName=L"obdeddi.logo";RegisterClassW(&wc);
CreateWindowExW(WS_EX_DLGMODALFRAME|WS_EX_CONTROLPARENT,L"obdeddi.logo",L"Vereinslogo",WS_CAPTION|WS_SYSMENU,CW_USEDEFAULT,CW_USEDEFAULT,d.px(560),d.px(580),owner,nullptr,wc.hInstance,&d);
d.child(L"STATIC",L"Bisher",0,0,18,12,230,24);d.child(L"STATIC",L"Vorschau im Originalformat",0,0,286,12,250,24);d.child(L"STATIC",L"",SS_OWNERDRAW|WS_BORDER,51,28,42,190,190);d.after=d.child(L"STATIC",L"",SS_OWNERDRAW|WS_BORDER,52,310,42,190,190);
d.child(L"BUTTON",L"Bild importieren…",WS_TABSTOP,10,18,247,220,28);d.child(L"BUTTON",L"Ganzes Bild",WS_TABSTOP,11,286,247,250,28);
const wchar_t* labels[]={L"Links",L"Oben",L"Breite",L"Höhe"};for(int i=0;i<4;++i){d.child(L"STATIC",labels[i],0,0,18+i*130,290,120,22);d.edits[i]=d.child(L"EDIT",L"0",WS_TABSTOP|ES_AUTOHSCROLL,30+i,18+i*130,315,118,24);}
d.child(L"STATIC",L"Drehung (Grad)",0,0,18,359,120,22);d.edits[4]=d.child(L"EDIT",L"0",WS_TABSTOP|ES_AUTOHSCROLL,34,150,353,86,24);d.child(L"BUTTON",L"Horizontal spiegeln",WS_TABSTOP,12,260,350,276,28);d.child(L"BUTTON",L"Vertikal spiegeln",WS_TABSTOP,13,260,386,276,28);d.child(L"BUTTON",L"Vorschau aktualisieren",WS_TABSTOP,14,18,395,220,28);
d.child(L"STATIC",L"38 × 38 Pixel, Originalpalette, heller Original-Hintergrund. Speichern erfolgt anschließend im Hauptfenster mit Backup.",0,0,18,433,518,38);d.apply=d.child(L"BUTTON",L"Übernehmen",WS_TABSTOP|BS_DEFPUSHBUTTON,IDOK,260,478,132,28);d.child(L"BUTTON",L"Abbrechen",WS_TABSTOP,IDCANCEL,402,478,134,28);EnableWindow(d.apply,FALSE);
EnableWindow(owner,FALSE);ShowWindow(d.window,SW_SHOW);UpdateWindow(d.window);MSG m{};while(!d.done&&GetMessageW(&m,nullptr,0,0)>0){if(!IsDialogMessageW(d.window,&m)){TranslateMessage(&m);DispatchMessageW(&m);}}EnableWindow(owner,TRUE);SetActiveWindow(owner);d.source.reset();DeleteObject(d.font);Gdiplus::GdiplusShutdown(d.token);return d.accepted;
}
}
+5
View File
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <windows.h>
#include "obdeddi/document.hpp"
namespace bmh::obdeddi { bool edit_logo(HWND owner,Document&,size_t club); }
+97
View File
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: GPL-3.0-only
#define UNICODE
#define _UNICODE
#define NOMINMAX
#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#include "obdeddi/document.hpp"
#include "obdeddi/logo_win32.hpp"
#include <algorithm>
#include <cwctype>
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#ifdef _MSC_VER
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
using bmh::obdeddi::Document;
namespace {
HWND window,list,tab,search,filter,panel,status,saveButton,target,swapBox;
HFONT font;int dpi=96,mode=0,selected=-1,sortColumn=0,scrollPos=0;
bool ascending=true,updating=false,formDirty=false;
std::unique_ptr<Document> document;
std::vector<int> visible;std::vector<HWND> fields;std::wstring displayText;
constexpr int Open=100,Save=101,Search=102,Filter=103,Apply=104,Target=105,Swap=106,Move=107,Tabs=108,Logo=109;
int px(int n){return MulDiv(n,dpi,96);}
std::wstring wide(const std::string& text){int n=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),int(text.size()),nullptr,0);std::wstring out(size_t(n),L' ');if(n)MultiByteToWideChar(CP_UTF8,0,text.data(),int(text.size()),out.data(),n);return out;}
std::wstring original(const std::string& text){return wide(bmh::iso646de_to_utf8(text.c_str()));}
std::wstring text(HWND h){int n=GetWindowTextLengthW(h);std::wstring out(size_t(n)+1,L'\0');GetWindowTextW(h,out.data(),n+1);out.resize(size_t(n));return out;}
std::string encode(std::wstring value){std::string out;for(auto c:value){switch(c){case L'Ä':out+='[';break;case L'Ö':out+='\\';break;case L'Ü':out+=']';break;case L'ä':out+='{';break;case L'ö':out+='|';break;case L'ü':out+='}';break;case L'ß':out+='~';break;default:if(c<32||c>=127)throw std::runtime_error("Name enthaelt nicht darstellbare Original-Zeichen.");out+=char(c);}}return out;}
void error(const std::exception& e){MessageBoxW(window,wide(e.what()).c_str(),L"obdeddi",MB_OK|MB_ICONERROR);}
HWND control(const wchar_t* cls,const wchar_t* caption,DWORD style,int id,int x,int y,int w,int h,HWND parent){HWND c=CreateWindowExW(cls==std::wstring(L"EDIT")?WS_EX_CLIENTEDGE:0,cls,caption,WS_CHILD|WS_VISIBLE|style,px(x),px(y),px(w),px(h),parent,reinterpret_cast<HMENU>(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);SendMessageW(c,WM_SETFONT,reinterpret_cast<WPARAM>(font),TRUE);return c;}
int combo(HWND h){return int(SendMessageW(h,CB_GETCURSEL,0,0));}
void add(HWND h,const std::wstring& s){SendMessageW(h,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(s.c_str()));}
int number(HWND h){try{auto value=text(h);size_t used=0;int n=std::stoi(value,&used);if(used!=value.size())throw std::invalid_argument("number");return n;}catch(...){throw std::runtime_error("Bitte eine ganze Zahl im angegebenen Bereich eingeben.");}}
void caption(){SetWindowTextW(window,document&&document->dirty()?L"obdeddi *":L"obdeddi");EnableWindow(saveButton,document!=nullptr);}
void setStatus(const std::wstring& value){SetWindowTextW(status,value.c_str());}
std::wstring clubName(int id){return id<0?L"Pool / Reserve":original(document->database().club_names.at(size_t(id)));}
int league(int team){int first=0;for(int l=0;l<9;++l){first+=document->profile().leagues[size_t(l)];if(team<first)return l;}return 9;}
const wchar_t* leagueName(int id){static const wchar_t* names[]={L"Bundesliga",L"2. Bundesliga",L"Regionalliga A",L"Regionalliga B",L"Oberliga",L"Spanien",L"England",L"Frankreich",L"Italien",L"Pokal / International"};return names[id];}
std::wstring cell(int id,int column){const auto& db=document->database();if(mode==0){const auto&p=db.players.at(size_t(id));switch(column){case 0:return original(p.name);case 1:return clubName(document->club_of(size_t(id)));case 2:{static const wchar_t* positions[]={L"Tor",L"Abwehr",L"Mittelfeld",L"Sturm"};return positions[p.position()];}case 3:return std::to_wstring(p.age());default:return std::to_wstring(p.strength());}}switch(column){case 0:return original(db.club_names.at(size_t(id)));case 1:return leagueName(league(id));case 2:{int count=0;for(size_t p=0;p<db.players.size();++p)count+=document->club_of(p)==id;return std::to_wstring(count);}default:return std::to_wstring(id);}}
void buildForm();void rebuild();bool apply();
void setSwapOptions(){if(!document||!target||!swapBox)return;SendMessageW(swapBox,CB_RESETCONTENT,0,0);add(swapBox,L"Nur verschieben");SendMessageW(swapBox,CB_SETITEMDATA,0,-1);int dest=combo(target);for(size_t i=0;i<document->database().players.size();++i)if(document->club_of(i)==dest){int row=int(SendMessageW(swapBox,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(original(document->database().players[i].name).c_str())));SendMessageW(swapBox,CB_SETITEMDATA,WPARAM(row),LPARAM(i));}SendMessageW(swapBox,CB_SETCURSEL,0,0);}
void formField(const wchar_t* label,int row,const std::wstring& value,bool dropdown=false){control(L"STATIC",label,0,0,8,12+row*27,125,23,panel);HWND h=control(dropdown?L"COMBOBOX":L"EDIT",dropdown?L"":value.c_str(),dropdown?(CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP):(ES_AUTOHSCROLL|WS_TABSTOP),200+row,138,8+row*27,228,dropdown?240:24,panel);fields.push_back(h);}
void buildForm(){updating=true;formDirty=false;selected=selected<0?-1:selected;fields.clear();target=swapBox=nullptr;HWND child=GetWindow(panel,GW_CHILD);while(child){HWND next=GetWindow(child,GW_HWNDNEXT);DestroyWindow(child);child=next;}scrollPos=0;SetScrollPos(panel,SB_VERT,0,TRUE);
if(!document||selected<0){updating=false;return;}
const auto& db=document->database();
if(mode==0){auto p=document->player(size_t(selected));formField(L"Name",0,original(p.name));formField(L"Position",1,L"",true);for(auto s:{L"Tor",L"Abwehr",L"Mittelfeld",L"Sturm"})add(fields[1],s);SendMessageW(fields[1],CB_SETCURSEL,p.position,0);
formField(L"Nationalität",2,L"",true);for(int n=0;n<62;++n)add(fields[2],original(db.club_names.at(document->profile().national_first+uint32_t(n))));SendMessageW(fields[2],CB_SETCURSEL,p.nation,0);
const wchar_t* labels[]={L"Alter (16–47)",L"Form (0–99)",L"Technik (0–99)",L"Kondition (0–99)",L"Bonus (0–127)",L"Teamplay (0–3)",L"Tempo (0–3)",L"Schuss (0–3)",L"Passspiel (0–3)",L"Zweikampf (0–3)",L"Freistoß (0–3)",L"Ecke (0–3)"};int values[]={p.age,p.form,p.technique,p.condition,p.bonus,p.skills[0],p.skills[1],p.skills[2],p.skills[3],p.skills[4],p.skills[5],p.skills[6]};for(int n=0;n<12;++n)formField(labels[n],n+3,std::to_wstring(values[n]));
control(L"STATIC",(L"Berechnete Stärke: "+std::to_wstring(db.players[size_t(selected)].strength())).c_str(),0,0,8,420,350,24,panel);
control(L"BUTTON",L"Werte übernehmen",WS_TABSTOP,Apply,8,451,358,28,panel);
control(L"STATIC",L"Classic-Eigenheit: Beim Karrierestart werden viele Spielerwerte neu erzeugt. Keine Änderung bestehender Spielstände.",0,0,8,490,358,55,panel);
control(L"STATIC",L"Zielverein",0,0,8,555,115,24,panel);target=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Target,138,550,228,240,panel);for(int t=0;t<int(document->profile().counts.league_teams);++t)add(target,clubName(t));SendMessageW(target,CB_SETCURSEL,0,0);
control(L"STATIC",L"Tauschpartner",0,0,8,588,125,24,panel);swapBox=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Swap,138,584,228,240,panel);setSwapOptions();control(L"BUTTON",L"Kaderwechsel",WS_TABSTOP,Move,8,621,358,28,panel);bool assigned=document->club_of(size_t(selected))>=0;EnableWindow(target,assigned);EnableWindow(swapBox,assigned);EnableWindow(GetDlgItem(panel,Move),assigned);
}else{auto id=size_t(selected);formField(L"Vereinsname",0,original(db.club_names[id]));formField(L"Trikot-Farbset",1,L"",true);for(int i=0;i<256;++i){if(std::find(db.raw_club_kit_selectors.begin(),db.raw_club_kit_selectors.end(),uint8_t(i))==db.raw_club_kit_selectors.end())continue;int row=int(SendMessageW(fields[1],CB_ADDSTRING,0,reinterpret_cast<LPARAM>((L"Farbset "+std::to_wstring(i)).c_str())));SendMessageW(fields[1],CB_SETITEMDATA,WPARAM(row),i);if(db.raw_club_kit_selectors[id]==i)SendMessageW(fields[1],CB_SETCURSEL,WPARAM(row),0);}
auto span=id<db.raw_club_short_name_offsets.size()?db.raw_club_short_name_offsets[id]:uint8_t(0);formField(L"Beginn (0–15)",2,std::to_wstring(span>>4));formField(L"Länge (1–16)",3,std::to_wstring((span&15)+1));if(id>=db.raw_club_short_name_offsets.size()){EnableWindow(fields[2],FALSE);EnableWindow(fields[3],FALSE);}
control(L"STATIC",L"Liga und Datensatzanzahlen bleiben fest. Wappen und andere Weitere Assets bleiben unverändert.",0,0,8,130,358,60,panel);control(L"BUTTON",L"Werte übernehmen",WS_TABSTOP,Apply,8,205,358,28,panel);control(L"BUTTON",L"Vereinslogo bearbeiten…",WS_TABSTOP,Logo,8,250,358,28,panel);
}
RECT r;GetClientRect(panel,&r);SCROLLINFO si{sizeof(si),SIF_RANGE|SIF_PAGE|SIF_POS,0,px(mode==0?670:250),UINT(r.bottom),0,0};SetScrollInfo(panel,SB_VERT,&si,TRUE);updating=false;
}
bool apply(){if(updating||!formDirty||!document||selected<0)return true;try{if(mode==0){auto p=document->player(size_t(selected));p.name=encode(text(fields[0]));p.position=combo(fields[1]);p.nation=combo(fields[2]);p.age=number(fields[3]);p.form=number(fields[4]);p.technique=number(fields[5]);p.condition=number(fields[6]);p.bonus=number(fields[7]);for(int i=0;i<7;++i)p.skills[i]=number(fields[size_t(i+8)]);document->set_player(size_t(selected),p);}else{int kit=int(SendMessageW(fields[1],CB_GETITEMDATA,WPARAM(combo(fields[1])),0));document->set_club(size_t(selected),encode(text(fields[0])),kit,number(fields[2]),number(fields[3]));}formDirty=false;caption();InvalidateRect(list,nullptr,FALSE);return true;}catch(const std::exception&e){error(e);return false;}}
void rebuild(){if(!document)return;updating=true;visible.clear();auto query=text(search);std::transform(query.begin(),query.end(),query.begin(),[](wchar_t c){return wchar_t(std::towlower(c));});int chosen=combo(filter);
const int total=mode==0?int(document->database().players.size()):int(document->profile().national_first);
for(int id=0;id<total;++id){if(mode==0&&chosen>0){int owner=document->club_of(size_t(id));if(chosen==1?owner!=-1:owner!=chosen-2)continue;}auto name=cell(id,0);std::transform(name.begin(),name.end(),name.begin(),[](wchar_t c){return wchar_t(std::towlower(c));});if(name.find(query)!=std::wstring::npos)visible.push_back(id);}
std::stable_sort(visible.begin(),visible.end(),[](int a,int b){int compare=0;if(mode==0&&sortColumn>=3){int x=sortColumn==3?document->database().players[size_t(a)].age():document->database().players[size_t(a)].strength(),y=sortColumn==3?document->database().players[size_t(b)].age():document->database().players[size_t(b)].strength();compare=(x>y)-(x<y);}else if(mode==1&&sortColumn>=2){int x=std::stoi(cell(a,sortColumn)),y=std::stoi(cell(b,sortColumn));compare=(x>y)-(x<y);}else compare=CompareStringOrdinal(cell(a,sortColumn).c_str(),-1,cell(b,sortColumn).c_str(),-1,TRUE)-CSTR_EQUAL;return ascending?compare<0:compare>0;});
ListView_SetItemCountEx(list,int(visible.size()),LVSICF_NOSCROLL);ListView_SetItemState(list,-1,0,LVIS_SELECTED|LVIS_FOCUSED);auto found=std::find(visible.begin(),visible.end(),selected);if(found==visible.end())selected=visible.empty()?-1:visible.front();int row=selected<0?-1:int(std::find(visible.begin(),visible.end(),selected)-visible.begin());if(row>=0)ListView_SetItemState(list,row,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED);updating=false;buildForm();setStatus(std::to_wstring(visible.size())+L" Einträge · "+document->path().wstring());
}
void columns(){while(ListView_DeleteColumn(list,0)){};const wchar_t* player[]={L"Spieler",L"Verein",L"Position",L"Alter",L"Stärke"};const wchar_t* clubs[]={L"Verein",L"Liga",L"Kader",L"ID"};for(int i=0;i<(mode==0?5:4);++i){LVCOLUMNW c{};c.mask=LVCF_TEXT|LVCF_WIDTH|LVCF_FMT;c.pszText=const_cast<wchar_t*>(mode==0?player[i]:clubs[i]);c.cx=px(i==0?210:i==1?180:70);c.fmt=i>=3?LVCFMT_RIGHT:LVCFMT_LEFT;ListView_InsertColumn(list,i,&c);}}
bool save(){if(!apply())return false;if(!document)return true;try{SetCursor(LoadCursor(nullptr,IDC_WAIT));auto backup=document->save();setStatus(backup.empty()?L"Keine Änderungen.":L"Gespeichert. Backup: "+backup.wstring());caption();SetCursor(LoadCursor(nullptr,IDC_ARROW));return true;}catch(const std::exception&e){SetCursor(LoadCursor(nullptr,IDC_ARROW));error(e);return false;}}
bool mayClose(){if(!apply())return false;if(!document||!document->dirty())return true;int choice=MessageBoxW(window,L"Änderungen an der OBD speichern?",L"obdeddi",MB_YESNOCANCEL|MB_ICONQUESTION);return choice==IDNO||(choice==IDYES&&save());}
void load(const std::filesystem::path& path){try{auto next=std::make_unique<Document>(path);document=std::move(next);selected=-1;updating=true;SendMessageW(filter,CB_RESETCONTENT,0,0);add(filter,L"Alle Vereine");add(filter,L"Pool / Reserve");for(int t=0;t<int(document->profile().counts.league_teams);++t)add(filter,clubName(t));SendMessageW(filter,CB_SETCURSEL,0,0);updating=false;rebuild();caption();}catch(const std::exception&e){error(e);}}
void open(){if(!mayClose())return;wchar_t path[32768]{};OPENFILENAMEW ofn{sizeof(ofn)};ofn.hwndOwner=window;ofn.lpstrFilter=L"OpenBMH-Daten (*.obd)\0*.obd\0Alle Dateien\0*.*\0";ofn.lpstrFile=path;ofn.nMaxFile=32768;ofn.Flags=OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR;if(GetOpenFileNameW(&ofn))load(path);}
LRESULT CALLBACK formProc(HWND h,UINT m,WPARAM w,LPARAM l){if(m==WM_SIZE){SCROLLINFO si{sizeof(si),SIF_PAGE};si.nPage=UINT(HIWORD(l));SetScrollInfo(h,SB_VERT,&si,TRUE);int next=GetScrollPos(h,SB_VERT);ScrollWindowEx(h,0,scrollPos-next,nullptr,nullptr,nullptr,nullptr,SW_SCROLLCHILDREN|SW_INVALIDATE|SW_ERASE);scrollPos=next;return 0;}if(m==WM_COMMAND)return SendMessageW(window,m,w,l);if(m==WM_VSCROLL||m==WM_MOUSEWHEEL){SCROLLINFO si{sizeof(si),SIF_ALL};GetScrollInfo(h,SB_VERT,&si);int next=scrollPos;if(m==WM_MOUSEWHEEL)next-=GET_WHEEL_DELTA_WPARAM(w)/WHEEL_DELTA*px(60);else switch(LOWORD(w)){case SB_LINEUP:next-=px(27);break;case SB_LINEDOWN:next+=px(27);break;case SB_PAGEUP:next-=int(si.nPage);break;case SB_PAGEDOWN:next+=int(si.nPage);break;case SB_THUMBTRACK:next=si.nTrackPos;break;};next=std::clamp(next,0,std::max(0,si.nMax-int(si.nPage)+1));ScrollWindowEx(h,0,scrollPos-next,nullptr,nullptr,nullptr,nullptr,SW_SCROLLCHILDREN|SW_INVALIDATE|SW_ERASE);scrollPos=next;SetScrollPos(h,SB_VERT,next,TRUE);return 0;}return DefWindowProcW(h,m,w,l);}
LRESULT CALLBACK proc(HWND h,UINT m,WPARAM w,LPARAM l){switch(m){case WM_SIZE:{RECT r;GetClientRect(h,&r);int right=std::max(px(420),int(r.right)-px(400));MoveWindow(list,px(12),px(92),right-px(24),r.bottom-px(132),TRUE);MoveWindow(panel,right,px(92),r.right-right-px(12),r.bottom-px(132),TRUE);MoveWindow(status,px(12),r.bottom-px(30),r.right-px(24),px(24),TRUE);return 0;}
case WM_GETMINMAXINFO:{auto p=reinterpret_cast<MINMAXINFO*>(l);p->ptMinTrackSize={px(940),px(630)};return 0;}
case WM_COMMAND:{int id=LOWORD(w),code=HIWORD(w);if(updating)return 0;if(id==Open){open();return 0;}if(id==Save){save();return 0;}if(id==Apply){if(apply())buildForm();return 0;}if(id==Search&&code==EN_CHANGE){SetTimer(h,1,180,nullptr);return 0;}if(id==Filter&&code==CBN_SELCHANGE){if(apply())rebuild();return 0;}if(id==Target&&code==CBN_SELCHANGE){setSwapOptions();return 0;}if(id==Logo){if(!apply())return 0;try{if(document&&selected>=0&&bmh::obdeddi::edit_logo(window,*document,size_t(selected)))caption();}catch(const std::exception&e){error(e);}return 0;}if(id==Move){if(!apply())return 0;try{int partner=int(SendMessageW(swapBox,CB_GETITEMDATA,WPARAM(combo(swapBox)),0));document->move_player(size_t(selected),combo(target),partner);caption();rebuild();}catch(const std::exception&e){error(e);}return 0;}if(id>=200&&id<220&&(code==EN_CHANGE||code==CBN_SELCHANGE))formDirty=true;return 0;}
case WM_TIMER:KillTimer(h,1);if(apply())rebuild();return 0;
case WM_NOTIFY:{auto hdr=reinterpret_cast<NMHDR*>(l);if(hdr->hwndFrom==tab&&hdr->code==TCN_SELCHANGING)return apply()?FALSE:TRUE;if(hdr->hwndFrom==tab&&hdr->code==TCN_SELCHANGE){mode=TabCtrl_GetCurSel(tab);selected=-1;sortColumn=0;ascending=true;EnableWindow(filter,mode==0);columns();rebuild();return 0;}if(hdr->hwndFrom!=list)return 0;
if(hdr->code==LVN_GETDISPINFOW){auto info=reinterpret_cast<NMLVDISPINFOW*>(l);if(info->item.iItem>=0&&size_t(info->item.iItem)<visible.size()){displayText=cell(visible[size_t(info->item.iItem)],info->item.iSubItem);info->item.pszText=displayText.data();}return 0;}
if(hdr->code==LVN_ITEMCHANGING&&!updating){auto n=reinterpret_cast<NMLISTVIEW*>(l);if((n->uOldState&LVIS_SELECTED)&&!(n->uNewState&LVIS_SELECTED)&&!apply())return TRUE;}
if(hdr->code==LVN_ITEMCHANGED&&!updating){auto n=reinterpret_cast<NMLISTVIEW*>(l);if((n->uNewState&LVIS_SELECTED)&&n->iItem>=0&&size_t(n->iItem)<visible.size()){selected=visible[size_t(n->iItem)];buildForm();}return 0;}
if(hdr->code==LVN_COLUMNCLICK){if(!apply())return 0;auto n=reinterpret_cast<NMLISTVIEW*>(l);ascending=sortColumn==n->iSubItem?!ascending:true;sortColumn=n->iSubItem;rebuild();return 0;}return 0;}
case WM_CLOSE:if(mayClose())DestroyWindow(h);return 0;case WM_DESTROY:PostQuitMessage(0);return 0;}
return DefWindowProcW(h,m,w,l);}
}
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int show){SetProcessDPIAware();HDC dc=GetDC(nullptr);dpi=GetDeviceCaps(dc,LOGPIXELSX);ReleaseDC(nullptr,dc);font=CreateFontW(-px(14),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");INITCOMMONCONTROLSEX init{sizeof(init),ICC_LISTVIEW_CLASSES|ICC_TAB_CLASSES};InitCommonControlsEx(&init);
WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=instance;wc.hCursor=LoadCursor(nullptr,IDC_ARROW);wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);wc.lpszClassName=L"obdeddi.window";RegisterClassW(&wc);wc.lpfnWndProc=formProc;wc.lpszClassName=L"obdeddi.form";wc.hbrBackground=reinterpret_cast<HBRUSH>(COLOR_WINDOW+1);RegisterClassW(&wc);
window=CreateWindowExW(0,L"obdeddi.window",L"obdeddi",WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,CW_USEDEFAULT,CW_USEDEFAULT,px(1180),px(800),nullptr,nullptr,instance,nullptr);
control(L"BUTTON",L"Öffnen…",WS_TABSTOP,Open,12,12,94,28,window);saveButton=control(L"BUTTON",L"Speichern",WS_TABSTOP,Save,114,12,94,28,window);search=control(L"EDIT",L"",ES_AUTOHSCROLL|WS_TABSTOP,Search,228,14,265,25,window);SendMessageW(search,EM_SETCUEBANNER,TRUE,reinterpret_cast<LPARAM>(L"Suchen …"));filter=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL|WS_TABSTOP,Filter,510,12,350,300,window);
tab=control(WC_TABCONTROLW,L"",WS_TABSTOP,Tabs,12,54,300,30,window);for(int i=0;i<2;++i){TCITEMW item{};item.mask=TCIF_TEXT;item.pszText=const_cast<wchar_t*>(i==0?L"Spieler":L"Vereine");TabCtrl_InsertItem(tab,i,&item);}
list=control(WC_LISTVIEWW,L"",LVS_REPORT|LVS_OWNERDATA|LVS_SINGLESEL|LVS_SHOWSELALWAYS|WS_TABSTOP,120,12,92,650,600,window);ListView_SetExtendedListViewStyle(list,LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER|LVS_EX_LABELTIP);
panel=control(L"obdeddi.form",L"",WS_VSCROLL|WS_CLIPCHILDREN,0,780,92,380,600,window);SetWindowLongPtrW(panel,GWL_EXSTYLE,GetWindowLongPtrW(panel,GWL_EXSTYLE)|WS_EX_CONTROLPARENT);status=control(L"STATIC",L"Eine COMMUNITY.OBD öffnen. Weitere Assets bleiben unverändert.",SS_LEFT,0,12,720,1100,24,window);columns();caption();ShowWindow(window,show);SendMessageW(window,WM_SIZE,0,0);UpdateWindow(window);
int argumentCount=0;auto arguments=CommandLineToArgvW(GetCommandLineW(),&argumentCount);if(arguments&&argumentCount>1)load(arguments[1]);if(arguments)LocalFree(arguments);
ACCEL keys[]={{FVIRTKEY|FCONTROL,'O',Open},{FVIRTKEY|FCONTROL,'S',Save}};HACCEL accel=CreateAcceleratorTableW(keys,2);MSG message{};while(GetMessageW(&message,nullptr,0,0)>0){if(!TranslateAcceleratorW(window,accel,&message)&&!IsDialogMessageW(window,&message)){TranslateMessage(&message);DispatchMessageW(&message);}}DestroyAcceleratorTable(accel);DeleteObject(font);return int(message.wParam);}
+7 -5
View File
@@ -277,14 +277,16 @@ GameEndTaxDialog::GameEndTaxDialog(const std::filesystem::path& data,TaxDialogPr
badge_=load_vga(asset_path(data/"W",std::to_string(std::max(0,projection_.badge_sprite)>>3)+".VGA"));
}
Image GameEndTaxDialog::backdrop() const {
if(projection_.compact_dialog_frame)return Image(320,240,0);
if(restored_backdrop_&&restored_backdrop_->width==320&&restored_backdrop_->height==240)return *restored_backdrop_;
const bool restored=restored_backdrop_&&restored_backdrop_->width==320&&restored_backdrop_->height==240;
if(projection_.compact_dialog_frame&&!(options_.preserve_restored_backdrop&&restored))return Image(320,240,0);
if(restored)return *restored_backdrop_;
return source_base(background_,options_.plain_background,false);
}
Image GameEndTaxDialog::render(std::optional<Button> pressed) const {
Image out=backdrop();
draw_source_dialog(out,{widgets_,faces_,&badge_,font_->small,font_->large,
font_->exe,font_->sprite,texts_},projection_,options_.gradient_text,pressed);
font_->exe,font_->sprite,texts_},projection_,options_.gradient_text,pressed,
options_.preserve_restored_backdrop&&restored_backdrop_&&restored_backdrop_->width==320&&restored_backdrop_->height==240);
return out;
}
bool source_badge_fallback(int token) {
@@ -292,11 +294,11 @@ bool source_badge_fallback(int token) {
return original_badge_fallback(club);
}
void draw_source_dialog(Image& out,const SourceDialogAssets& assets,const TaxDialogProjection& p,
bool gradient,std::optional<GameEndTaxDialog::Button> pressed) {
bool gradient,std::optional<GameEndTaxDialog::Button> pressed,bool preserve_backdrop) {
using Button=GameEndTaxDialog::Button;
if(out.width!=320||out.height!=240||(!p.badge_fallback&&!assets.badge))
throw FormatError("Source dialog: invalid backdrop or badge assets");
if(p.compact_dialog_frame)out=Image(320,240,0);
if(p.compact_dialog_frame&&!preserve_backdrop)out=Image(320,240,0);
frame(out,assets.widgets,assets.exe,48,84,217,99,!p.compact_dialog_frame);
const std::string_view header = p.source_system_identity
? text_at(assets.texts,::bmh::layout::SystemManagerNameText) : p.manager_name;
+3 -1
View File
@@ -29,6 +29,7 @@ std::vector<std::string> wrap_source_text(const Font&, const LeImage&,
struct GameEndRenderOptions {
bool plain_background = false; // Original PlainBackground, not its inverse
bool gradient_text = true; // TextGradientDisabled==0 && BMH.exe[TextGradientMode]==2
bool preserve_restored_backdrop = false; // Nested construction notices retain their owning screen.
};
// Rendering-only projection. Names retain the Source ISO646-DE bytes; values and order have
@@ -129,6 +130,7 @@ struct SourceDialogAssets {
};
void draw_source_dialog(Image&, const SourceDialogAssets&, const TaxDialogProjection&,
bool gradient,
std::optional<GameEndTaxDialog::Button> pressed = {});
std::optional<GameEndTaxDialog::Button> pressed = {},
bool preserve_backdrop = false);
} // namespace bmh::ui
+2
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/resource_bundle.hpp"
#include "ui/setup.hpp"
#include <algorithm>
@@ -30,6 +31,7 @@ void copy_rect(Image& dst, const Image& src, int sx, int sy, int dx, int dy,
} // namespace
std::filesystem::path asset_path(const std::filesystem::path& directory, const std::string& name) {
if (!std::filesystem::exists(directory / name) && resource_exists(directory / name)) return directory / name;
std::filesystem::path found;
for (const auto& e : std::filesystem::directory_iterator(directory)) {
if (e.is_regular_file() && folded(e.path().filename().string()) == folded(name)) {
+3 -2
View File
@@ -697,12 +697,13 @@ void StadiumScreen::rebuild_tip_dialog() {
tip_dialog_.reset();
periphery_dialog_.reset();
if (state_.periphery_quote_dialog) {
GameEndRenderOptions options{state_.plain_background, state_.gradient_text};
GameEndRenderOptions options{state_.plain_background, state_.gradient_text, true};
periphery_dialog_.emplace(data_, *state_.periphery_quote_dialog, options, render_scene());
}
if (state_.construction_tip_dialog) {
GameEndRenderOptions options;
options.gradient_text = state_.gradient_text;
options.preserve_restored_backdrop = true;
if (state_.block_expansion) options.plain_background = state_.plain_background;
tip_dialog_.emplace(data_, *state_.construction_tip_dialog,
options, state_.block_expansion
@@ -2029,7 +2030,7 @@ void StadiumScreen::acknowledge(StadiumState updated) {
// therefore leaves the old question retryable.
std::optional<GameEndTaxDialog> staged_tip, staged_periphery;
if (updated.periphery_quote_dialog) {
const GameEndRenderOptions options{updated.plain_background, updated.gradient_text};
const GameEndRenderOptions options{updated.plain_background, updated.gradient_text, true};
staged_periphery.emplace(data_, *updated.periphery_quote_dialog, options, render_scene());
}
if (updated.construction_tip_dialog) {
+9 -4
View File
@@ -60,12 +60,16 @@ void StrengthsScreen::selector(Image& out,int x,int y,int style) const {
if(style<3)copy(out,arrows_,exe_.u8(::bmh::layout::LeaguePairings_Selector_RuntimeField3+uint32_t(style)),0,x+1,y+exe_.u8(::bmh::layout::Strengths_Selector_RuntimeField2),
exe_.u8(::bmh::layout::LeaguePairings_Selector_RuntimeField4+uint32_t(style)),38);
}
int StrengthsScreen::row_step() const {
const int original=exe_.u8(layout::Strengths_PointerDown_RuntimeField+uint32_t(state_.identity.league));
return exe_.expanded_profile() ? std::min(original, 144/int(state_.projection.rows.size())) : original;
}
Image StrengthsScreen::render() const {
Image out=state_.decorated?frame_:Image(320,240);
if(!state_.decorated) {fill(out,0,4,320,13,0x44);fill(out,1,5,318,11,0x39);fill(out,0,228,320,10,0x44);fill(out,1,229,318,8,0x39);}
const auto title=original_to_utf8(state_.title);sprite_.draw(out,SpriteFont::centered_title_x(sprite_.text_width(title)),13,title);
sprite_.draw(out,5,235,original_to_utf8(state_.subtitle));
const int step=exe_.u8(::bmh::layout::Strengths_PointerDown_RuntimeField+uint32_t(state_.identity.league)),bottom=step*int(state_.projection.rows.size())+27;
const int step=row_step(),bottom=step*int(state_.projection.rows.size())+27;
if(state_.original_panel)copy(out,panel_,0,7,1,27,318,bottom-27);
else fill(out,0,26,320,bottom-25,0x42);
fill(out,0,26,320,1,0x46);fill(out,0,26,1,bottom-25,0x46);
@@ -131,9 +135,10 @@ bool StrengthsScreen::pointer_down(int x,int y,bool right) {
if(pending_)return false;
if(right) {post(StrengthsAction::close);return true;}
if(auto selector=selector_at(x,y)) {pending_=*selector;return true;}
const int step=exe_.u8(::bmh::layout::Strengths_PointerDown_RuntimeField+uint32_t(state_.identity.league));
if(y>23&&y<int(state_.projection.rows.size())*step+24) {
const int row=(y-24)/step;post(StrengthsAction::team_info,state_.projection.rows[size_t(row)].runtime_team);return true;
const int step=row_step();
const int top=exe_.expanded_profile()?27:24;
if(y>=top&&y<int(state_.projection.rows.size())*step+top) {
const int row=(y-top)/step;post(StrengthsAction::team_info,state_.projection.rows[size_t(row)].runtime_team);return true;
}
pressed_=button_at(x,y);return pressed_>=0;
}
+1
View File
@@ -38,6 +38,7 @@ public:
const std::optional<StrengthsRequest>& pending() const { return pending_; }
std::string state_json() const;
private:
int row_step() const;
void text(Image&, int x, int baseline, std::string_view bytes, uint8_t color) const;
void selector(Image&, int x, int y, int style) const;
void button(Image&, int x, int y, int width, std::string_view label, bool selected) const;
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-only
#define NOMINMAX
#include "obdeddi/logo_transform_win32.hpp"
#include <iostream>
#include <stdexcept>
void check(bool ok,const char* message){if(!ok)throw std::runtime_error(message);}
int main()try{Gdiplus::GdiplusStartupInput input;ULONG_PTR token=0;check(Gdiplus::GdiplusStartup(&token,&input,nullptr)==Gdiplus::Ok,"GDI startup");
{Gdiplus::Bitmap source(16,8,PixelFormat32bppARGB);for(int y=0;y<8;++y)for(int x=0;x<16;++x)source.SetPixel(x,y,x<8?Gdiplus::Color(255,255,0,0):Gdiplus::Color(255,0,0,255));
auto normal=bmh::obdeddi::transform_logo(source,0,0,16,8,0,false,false);auto mirror=bmh::obdeddi::transform_logo(source,0,0,16,8,0,true,false);auto rotate=bmh::obdeddi::transform_logo(source,0,0,16,8,180,false,false);auto crop=bmh::obdeddi::transform_logo(source,0,0,8,8,0,false,false);
check((normal[19*38+8]&0xffffff)==0xff0000,"normal left color");check((mirror[19*38+8]&0xffffff)==0xff,"horizontal mirror");check((rotate[19*38+8]&0xffffff)==0xff,"rotation");check((crop[19*38+30]&0xffffff)==0xff0000,"crop respects source rectangle");check((normal[0]>>24)==0,"transparent fit border");
bool rejected=false;try{bmh::obdeddi::transform_logo(source,-1,0,16,8,0,false,false);}catch(...){rejected=true;}check(rejected,"invalid crop accepted");}
Gdiplus::GdiplusShutdown(token);std::cout<<"Native logo crop, rotation, mirroring and alpha passed\n";return 0;
}catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
+36
View File
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "obdeddi/document.hpp"
#include "cli/json.hpp"
#include "app/scene_timing.hpp"
#include "miniz.h"
#include <chrono>
#include <fstream>
#include <iostream>
#include <map>
using namespace bmh;
using namespace bmh::obdeddi;
using Files=std::map<std::string,Bytes>;
void check(bool b,const char*s){if(!b)throw std::runtime_error(s);}
Bytes bytes(std::string s){return Bytes(s.begin(),s.end());}
void put(Bytes&data,size_t at,uint16_t x){data.at(at)=uint8_t(x);data.at(at+1)=uint8_t(x>>8);}
Bytes archive(Files entries){cli::Json::Object hashes;for(const auto&[name,data]:entries)hashes.emplace(name,sha256(data));auto manifest=cli::dump_json(cli::Json::Object{{"format","openbmh-community-1"},{"profile","classic-plus-1"},{"files",std::move(hashes)}});entries["PACKAGE.json"]=bytes(manifest);mz_zip_archive zip{};check(mz_zip_writer_init_heap(&zip,0,0),"writer init");for(const auto&[name,data]:entries)check(mz_zip_writer_add_mem(&zip,name.c_str(),data.data(),data.size(),MZ_BEST_COMPRESSION),"writer entry");void*p=nullptr;size_t n=0;check(mz_zip_writer_finalize_heap_archive(&zip,&p,&n),"writer finish");Bytes out(static_cast<uint8_t*>(p),static_cast<uint8_t*>(p)+n);mz_free(p);mz_zip_writer_end(&zip);return out;}
void write(const std::filesystem::path&p,const Bytes&data){std::ofstream f(p,std::ios::binary);f.write(reinterpret_cast<const char*>(data.data()),std::streamsize(data.size()));check(bool(f),"write failed");}
Bytes entry(const std::filesystem::path&path,const char*name){auto data=read_file(path);mz_zip_archive zip{};check(mz_zip_reader_init_mem(&zip,data.data(),data.size(),0),"reader init");size_t n=0;void*p=mz_zip_reader_extract_file_to_heap(&zip,name,&n,0);check(p!=nullptr,"missing fixture entry");Bytes out(static_cast<uint8_t*>(p),static_cast<uint8_t*>(p)+n);mz_free(p);mz_zip_reader_end(&zip);return out;}
Database synthetic(){Database d;d.counts=DataProfile::international_11().counts;d.pools[0]=bytes(std::string("C\0",2));d.pools[1]=bytes(std::string("P\0",2));d.pools[2]=bytes(std::string("R\0",2));d.pools[3]=bytes(std::string("S\0",2));d.club_names.assign(445,"C");d.players.assign(3334,Player{"P",0xa5200000u|42u|(55u<<7)|(65u<<14),0x01234000u,9u<<21});d.raw_player_bonus_values.resize(4154);d.raw_club_name_offsets.resize(890);d.raw_player_name_offsets.resize(6668);d.raw_database_metadata.resize(100);d.raw_club_auxiliary_words.resize(388);d.raw_club_badge_selectors.resize(890);d.raw_foreign_club_strength.resize(251);d.raw_league_auxiliary_bytes.resize(189);d.raw_referee_properties.resize(50);d.raw_club_kit_selectors.resize(445);d.raw_club_short_name_offsets.resize(194);d.squad_list.resize(4154*2);for(size_t i=0;i<4154;++i)put(d.squad_list,i*2,4095);int player=0;for(int team=0;team<164;++team)for(int row=0;row<20;++row)put(d.squad_list,size_t(team*24+row)*2,uint16_t(player++|(row<11?0x8000:0)));return d;}
int main()try{
check(sha256(bytes("abc"))=="ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad","SHA-256 vector failed");
check(app::scene_frame_delay(80)==100&&app::scene_frame_delay(0)==16,"scene pacing mapping");
auto db=synthetic();auto master=encode_database(db);check(encode_database(decode_database(master,db.counts))==master,"master roundtrip");
auto root=std::filesystem::temp_directory_path()/("obdeddi-test-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));std::filesystem::create_directories(root);
auto runtime=bytes("OBMHDAT1");runtime.resize(36);const Bytes asset{3,17,91,0,255};Bytes palette(768,0);for(size_t i=0;i<256;++i)for(int c=0;c<3;++c)palette[i*3+size_t(c)]=uint8_t(std::min(size_t(63),i/4));palette[10*3]=63;palette[10*3+1]=palette[10*3+2]=0;palette[20*3]=palette[20*3+1]=0;palette[20*3+2]=63;Bytes pixels(304*38,94),vga;auto putHeader=[&](uint32_t v,int n){for(int b=0;b<n;++b)vga.push_back(uint8_t(v>>(b*8)));};Bytes payload;for(size_t i=0;i<pixels.size();i+=128){size_t n=std::min(size_t(128),pixels.size()-i);payload.push_back(uint8_t(n-1));payload.insert(payload.end(),pixels.begin()+i,pixels.begin()+i+n);}payload.push_back(0);putHeader(304,2);putHeader(38,2);putHeader(uint32_t(payload.size()),4);vga.insert(vga.end(),payload.begin(),payload.end());auto input=archive({{"M3D.MAN",master},{"RUNTIME.DAT",runtime},{"OBMHPROF.INI",bytes("[OpenBMH]\nprofile=classic-plus-1\n")},{"KB/1.VGA",asset},{"M3PC.COL",palette},{"W/0.VGA",vga}});auto path=root/std::filesystem::path(std::u8string(u8"Saison-ä.obd"));write(path,input);
Document doc(path);check(!doc.dirty()&&doc.save().empty()&&read_file(path)==input,"no-op wrote a file");
auto player=doc.player(0);auto high=db.players[0].w35c&~0x1fffffu;player.name="M}LLER";player.nation=61;player.age=30;player.form=75;player.skills[2]=3;doc.set_player(0,player);check((doc.database().players[0].w35c&~0x1fffffu)==high,"unrelated player bits changed");
auto invalid=player;invalid.skills[0]=4;bool rejected=false;try{doc.set_player(1,invalid);}catch(const FormatError&){rejected=true;}check(rejected,"invalid skill accepted");
doc.set_club(0,"NEUER VEREIN",3,0,12);doc.move_player(0,1);check(doc.club_of(0)==1&&doc.club_of(20)==1,"move failed");doc.move_player(1,1,20);check(doc.club_of(1)==1&&doc.club_of(20)==0,"swap failed");
auto backup=doc.save();check(!backup.empty()&&read_file(backup)==input,"backup not exact");check(entry(path,"KB/1.VGA")==asset,"asset modified");Document loaded(path);check(loaded.player(0).name=="M}LLER"&&loaded.player(0).nation==61&&loaded.database().club_names[0]=="NEUER VEREIN","edited data not persisted");check(loaded.club_of(0)==1&&loaded.club_of(20)==0,"saved roster changed");
auto logoPath=root/"logos.obd";write(logoPath,input);Document logos(logoPath);auto originalSelectors=logos.database().raw_club_badge_selectors;std::array<uint32_t,1444> rgba{};rgba.fill(0xffff0000);auto preview=logos.preview_logo(rgba);logos.set_logo(0,rgba);check(logos.logo(0)==preview,"logo preview differs from stored palette result");check(le16(logos.database().raw_club_badge_selectors,0)==1,"shared logo was not cloned");check(le16(logos.database().raw_club_badge_selectors,2)==0,"neighbour selector changed");logos.save();auto firstMaster=entry(logoPath,"M3D.MAN");auto sheet=decode_vga(entry(logoPath,"W/0.VGA"));for(int y=0;y<38;++y)for(int x=0;x<304;++x)if(x<38||x>=76)check(sheet.pixels[size_t(y*304+x)]==94,"neighbour pixels changed");rgba.fill(0xff0000ff);logos.set_logo(0,rgba);logos.save();check(entry(logoPath,"M3D.MAN")==firstMaster,"logo-only save changed database");Document logoReload(logoPath);check(logoReload.logo(0)==logoReload.preview_logo(rgba),"logo-only edit was not saved");
auto changed=loaded.player(2);changed.form=40;loaded.set_player(2,changed);auto outside=read_file(path);outside.push_back(0);write(path,outside);rejected=false;try{loaded.save();}catch(const FormatError&){rejected=true;}check(rejected&&read_file(path)==outside,"external edit overwritten");
auto failRoot=root/"backup-failure";std::filesystem::create_directory(failRoot);auto failPath=failRoot/"COMMUNITY.OBD";write(failPath,input);write(failRoot/"backups",bytes("not a directory"));Document failure(failPath);auto value=failure.player(0);value.form=12;failure.set_player(0,value);rejected=false;try{failure.save();}catch(const std::exception&){rejected=true;}check(rejected&&read_file(failPath)==input,"backup failure changed original");
auto corrupt=input;corrupt.resize(12);write(root/"bad.obd",corrupt);rejected=false;try{Document bad(root/"bad.obd");}catch(const std::exception&){rejected=true;}check(rejected,"truncated archive accepted");
std::filesystem::remove_all(root);std::cout<<"Editor roundtrips, unknown bits, roster changes, assets, verified backups and failure safety passed\n";return 0;
}catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/resource_bundle.hpp"
#include "formats/le.hpp"
#include "formats/data_profile.hpp"
#include "formats/executable_layout.hpp"
#include "game/calendar.hpp"
#include "miniz.h"
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace bmh;
void check(bool ok,const char* what){if(!ok)throw std::runtime_error(what);}
void bundle(const std::filesystem::path& path,const std::vector<std::pair<std::string,Bytes>>& files) {
mz_zip_archive zip{};
check(mz_zip_writer_init_heap(&zip,0,0)!=0,"synthetic ZIP initialization");
for(const auto& [name,bytes]:files)check(mz_zip_writer_add_mem(&zip,name.c_str(),bytes.data(),bytes.size(),MZ_BEST_COMPRESSION)!=0,"synthetic ZIP entry");
void* data=nullptr;size_t size=0;
check(mz_zip_writer_finalize_heap_archive(&zip,&data,&size)!=0,"synthetic ZIP finalization");
std::ofstream out(path,std::ios::binary);out.write(static_cast<const char*>(data),std::streamsize(size));
mz_free(data);mz_zip_writer_end(&zip);check(bool(out),"synthetic ZIP write");
}
Bytes bytes(std::string text){return Bytes(text.begin(),text.end());}
int main()try {
const auto root=std::filesystem::temp_directory_path()/("openbmh-bundle-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
std::filesystem::create_directories(root);
Bytes data(0x20000,0);
const auto put=[&](uint32_t address,uint8_t value){data.at(address-layout::GermanDataSegmentBegin)=value;};
for(int league=0;league<9;++league)put(layout::LeagueSizes+uint32_t(league),league<5?18:12);
for(int day=24;day<24+34*8;day+=8)put(layout::CompetitionCalendar+uint32_t(day*2),1);
RuntimePolicy policy{2030,2,90,1,{{layout::FreeKickTakerLabel,"Test label"}}};
save_runtime_image(LeImage::from_bytes(layout::GermanDataSegmentBegin,data),policy,root/"source.dat");
const auto runtime=read_file(root/"source.dat");
bundle(root/kCommunityBundle,{{"RUNTIME.DAT",runtime},{"OBMHPROF.INI",bytes("[OpenBMH]\nprofile=classic-plus-1\n")},{"KB/20.VGA",bytes("synthetic picture")}});
std::filesystem::remove(root/"source.dat");
check(!std::filesystem::exists(root/"BMH.exe"),"synthetic bundle accidentally requires an executable");
check(resource_exists(root/"kb"/"20.vga") && read_file(root/"kb"/"20.vga")==bytes("synthetic picture"),"case-insensitive resource read");
check(load_data_profile(root).extended(),"bundled profile metadata not found");
const auto image=load_le(root/"BMH.exe");
check(image.expanded_profile() && image.runtime_policy(),"data-only image did not bind the extended profile");
check(!image.contains(layout::CalendarDateSetup) && !image.contains(layout::ForeignBadgeGateInstruction),"machine-code segment retained");
check(calendar_epoch_from_executable(image).year==2030,"calendar still depends on original instructions");
check(image.cstring(layout::FreeKickTakerLabel)=="Test label","resolved auxiliary label lost");
check(image.u16(layout::TeamsWithSquads)==164,"standalone runtime roster dimensions differ");
// Loose user-created files remain writable and are not replaced by bundle data.
{std::ofstream out(root/"user.FBM");out<<"user save";}
check(read_file(root/"user.FBM")==bytes("user save"),"bundle swallowed a loose user save");
for(int kind=0;kind<2;++kind) {
const auto bad=root/("bad-"+std::to_string(kind));std::filesystem::create_directory(bad);
bundle(bad/kCommunityBundle,kind==0?std::vector<std::pair<std::string,Bytes>>{{"../escape",{1}}}:
std::vector<std::pair<std::string,Bytes>>{{"DUP",{1}},{"dup",{2}}});
bool rejected=false;try{resource_exists(bad/"anything");}catch(const FormatError&){rejected=true;}
check(rejected,"unsafe or duplicate resource accepted");
}
auto broken=runtime;broken.pop_back();
{std::ofstream out(root/"broken.dat",std::ios::binary);out.write(reinterpret_cast<const char*>(broken.data()),std::streamsize(broken.size()));}
bool rejected=false;try{load_le(root/"broken.dat");}catch(const FormatError&){rejected=true;}
check(rejected,"truncated runtime labels accepted");
std::filesystem::remove_all(root);
std::cout<<"Standalone data policies, bundled resources, paths and loose saves passed\n";return 0;
}catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}
+44
View File
@@ -4,6 +4,8 @@
#include "game/messages.hpp"
#include "ui/manager.hpp"
#include "formats/palette.hpp"
#include <fstream>
#include <algorithm>
#include <array>
@@ -1182,9 +1184,51 @@ void source_stadium_data_controls(const std::filesystem::path& data) {
}
}
namespace {
void construction_backdrop_tests(const std::filesystem::path& data,const std::filesystem::path& output) {
const auto save_image=[&](const Image& image,const std::string& name) {
if(output.empty())return;
std::filesystem::create_directories(output);const auto palette=load_palette(data/"M3PC.COL");
std::ofstream file(output/(name+".ppm"),std::ios::binary);file<<"P6\n320 240\n255\n";
for(auto pixel:image.pixels){const auto color=palette.argb[pixel];file.put(char(color>>16));file.put(char(color>>8));file.put(char(color));}
};
for(bool compact:{false,true})for(bool periphery:{false,true}) {
auto state=periphery?overview_state():detail_state(1,15333,1);
state.compact_dialog_frame=compact;
StadiumScreen screen(data,state);
if(periphery){screen.click(30,220);screen.click(160,220);}
const auto request=screen.click(periphery?266:50,periphery?125:140);
check(request.kind==(periphery?StadiumRequestKind::quote_periphery:StadiumRequestKind::expansion_confirm),"construction backdrop fixture did not enter its real request path");
const Image underlay=screen.render();
state=screen.state();next_identity(state);
auto question=question_for();question.compact_dialog_frame=compact;
if(periphery){state.quoted_object=request.object;state.quoted_price=1700000;question.source_flags=1;state.periphery_quote_dialog=question;}
else {state.block_expansion->offer=pending_offer(state.block_expansion->quote);state.construction_tip_dialog=question;}
screen.acknowledge(state);const auto actual=screen.render();
const auto check_outside=[&](const Image& image) {
for(int y=0;y<240;++y)if(y<80 || y>=190)for(int x=0;x<320;++x)
if(image.pixels[size_t(y*320+x)]!=underlay.pixels[size_t(y*320+x)])throw std::runtime_error(std::string(periphery?"periphery":"stands")+" compact="+std::to_string(compact)+" backdrop differs at "+std::to_string(x)+","+std::to_string(y));
};
check_outside(actual);
screen.pointer_down(100,171);check_outside(screen.render());
GameEndRenderOptions options{state.plain_background,state.gradient_text,true};
GameEndTaxDialog notice(data,question,options,screen.construction_notice_backdrop());
check(notice.backdrop().pixels==screen.construction_notice_backdrop().pixels,"construction notice completion restores a black frame");
check_outside(notice.render(GameEndTaxDialog::Button::yes));
if(compact) {
const auto name=periphery?"periphery":"stands";
GameEndTaxDialog previous(data,question,{state.plain_background,state.gradient_text},underlay);
check(previous.render().pixels[0]==0,"default compact dialog behavior changed outside construction menus");
save_image(previous.render(),std::string(name)+"-before");save_image(actual,std::string(name)+"-after");
}
}
}
}
int main(int argc, char** argv) try {
if (argc < 2 || !*argv[1]) throw std::runtime_error("expected Original BMH data directory");
const std::filesystem::path data = argv[1];
construction_backdrop_tests(data,argc>2?std::filesystem::path(argv[2]):std::filesystem::path{});
source_stadium_data_controls(data);
source_periphery_hit_tests(data);
row_hit_tests(data);
+3
View File
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: GPL-3.0-only
"""Build products and every configured test program, without unused data fixtures."""
import argparse
import os
from pathlib import Path
import re
import subprocess
@@ -13,6 +14,8 @@ HOST = re.compile(r'(?:python(?:[0-9.]+)?|cmake|ctest)(?:\.exe)?$', re.I)
def targets_for_tests(build):
build = build.resolve(strict=True)
targets = {'openbmh_play', 'openbmh_cli'}
if os.name == 'nt':
targets.add('obdeddi')
tests = 0
for file in sorted(build.rglob('CTestTestfile.cmake')):
for line in file.read_text(encoding='utf-8').splitlines():
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Assemble a small local Windows community ZIP from a verified program and private data."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import zipfile
def create(program, data, destination, version):
if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?',version):
raise ValueError('Invalid version')
bundle=data/'COMMUNITY.OBD'
with zipfile.ZipFile(bundle) as z:
for name in z.namelist():
if Path(name).suffix.lower() in ('.exe','.com','.dll','.png','.jpg','.jpeg'):
raise ValueError('Original executables or raster studies found in data bundle')
if z.read('RUNTIME.DAT')[:8]!=b'OBMHDAT1':
raise ValueError('Expected a data-only runtime')
receipt=json.loads(z.read('PACKAGE.json'))
for name,digest in receipt['files'].items():
if hashlib.sha256(z.read(name)).hexdigest()!=digest:
raise ValueError('Resource checksum mismatch: '+name)
files={}
with zipfile.ZipFile(program) as z:
for info in z.infolist():
if info.is_dir():continue
path=Path(info.filename)
if path.is_absolute() or '..' in path.parts or len(path.parts)<2:
raise ValueError('Invalid program archive path')
name=Path(*path.parts[1:]).as_posix()
if name=='openbmh_cli.exe':continue
if path.suffix.lower() in ('.zip','.cpp','.hpp','.c','.h','.png','.jpg','.jpeg'):
raise ValueError('Unexpected source/archive/image in program package')
files[name]=z.read(info)
for required in ('OpenBMH.exe','vcruntime140.dll','msvcp140.dll','LICENSE'):
if required not in files:raise ValueError('Missing runtime component: '+required)
files['COMMUNITY.OBD']=bundle.read_bytes()
report=data/'IMPORT-REPORT.json'
if report.exists():files[report.name]=report.read_bytes()
source_url=f'https://github.com/Weyoune/openbmh/releases/download/v{version}/OpenBMH-{version}-source.zip'
files['COMMUNITY_README.txt']=('OpenBMH '+version+' Community Edition\n\n'
'ZIP vollstaendig in einen eigenen Ordner entpacken und OpenBMH.exe starten.\n'
'Alle benoetigten Spieldaten, Grafiken und Sounds liegen in COMMUNITY.OBD.\n'
'Keine Original-DOS-Installation und kein Startskript erforderlich.\n'
'Eigene Spielstaende und Einstellungen bleiben ausserhalb des Datenarchivs.\n\n'
'263 auslaendische Vereinswappen: 175 echte und 88 fiktive Ersatzwappen.\n'
'Quellen und gekennzeichnete Ergaenzungen: IMPORT-REPORT.json.\n\n'
'Anwendung: GPL-3.0-only. Vollstaendiger korrespondierender Quellcode und\n'
'Abhaengigkeiten kostenlos und separat unter:\n'+source_url+'\n'
'Lizenzen der Abhaengigkeiten siehe THIRD_PARTY_NOTICES.md und docs/licenses.\n'
'Inhaltsrechte der Spieldaten und Wappen bleiben bei ihren jeweiligen Quellen.\n').encode('utf-8')
files['PACKAGE-SHA256SUMS']=''.join(hashlib.sha256(b).hexdigest()+' '+name+'\n' for name,b in sorted(files.items())).encode()
destination.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
for name,content in files.items():z.writestr(name,content)
if destination.stat().st_size>=10_000_000:
destination.unlink()
raise ValueError('Community ZIP exceeds the 10 MB budget')
print(json.dumps({'file':str(destination),'bytes':destination.stat().st_size,'sha256':hashlib.sha256(destination.read_bytes()).hexdigest(),'source_included':False}))
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--program',type=Path,required=True);p.add_argument('--data',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--version',required=True);a=p.parse_args();create(a.program,a.data,a.out,a.version)
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Package the native Windows OBD data editor separately from the game."""
import argparse
from pathlib import Path
import zipfile
def package(build,game,out):
executable=build/'obdeddi.exe'
if not executable.is_file():executable=build/'Release/obdeddi.exe'
if not executable.is_file():raise RuntimeError('Native editor executable missing')
files={'obdeddi.exe':executable.read_bytes()}
with zipfile.ZipFile(game) as z:
for name in z.namelist():
parts=Path(name).parts
if len(parts)<2:continue
relative=Path(*parts[1:]).as_posix()
if relative.lower().endswith('.dll') or relative in ('LICENSE','THIRD_PARTY_NOTICES.md','ACKNOWLEDGEMENTS.md') or relative.startswith('docs/licenses/'):
if not name.endswith('/'):files[relative]=z.read(name)
files['README.txt']=('obdeddi 0.1.0 – nativer OpenBMH-1.1-Dateneditor\n\n'
'Vollstaendig entpacken und obdeddi.exe starten. COMMUNITY.OBD ueber Oeffnen waehlen.\n'
'Spieler und Vereine bearbeiten; Suche, Sortierung und Kaderwechsel stehen zur Verfuegung.\n'
'Speichern ersetzt die OBD erst nach geprueftem Backup im Unterverzeichnis backups.\n'
'Vereinslogos: PNG/JPEG/BMP importieren, zuschneiden, drehen und spiegeln; Vorschau im Originalformat. Andere Assets bleiben unveraendert. Festes Ligaset und feste Datensatzanzahlen bleiben erhalten.\n'
'Classic-Eigenheit: Viele Werte werden beim Karrierestart neu erzeugt. Bestehende Spielstaende bleiben unveraendert.\n'
'Tasten: Strg+O oeffnen, Strg+S speichern. Alternativ: obdeddi.exe "Pfad\\COMMUNITY.OBD".\n\n'
'GPL-3.0-only; vollstaendige passende Quellen und Abhaengigkeiten separat:\n'
'https://github.com/Weyoune/openbmh/releases/tag/obdeddi-v0.1.0\n').encode('utf-8')
out.mkdir(parents=True,exist_ok=True);target=out/'obdeddi-0.1.0-windows-x64.zip'
with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
for name,data in files.items():z.writestr('obdeddi-0.1.0/'+name,data)
print(target)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--build',type=Path,required=True);p.add_argument('--game',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();package(a.build,a.game,a.out)
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Prepare a compact data-only community directory from private supplied content."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import zipfile
def build(source, destination, exporter):
if destination.exists():
raise ValueError('Destination must not exist')
source=source.resolve();destination.mkdir(parents=True)
runtime=destination/'RUNTIME.DAT'
try:
exe=next(p for p in source.iterdir() if p.name.upper()=='BMH.EXE')
subprocess.run([str(exporter.resolve()),str(exe),str(runtime)],check=True)
data=runtime.read_bytes()
if data[:8]!=b'OBMHDAT1':raise ValueError('Exporter did not produce a data-only runtime')
# Only resources actually used by OpenBMH; no DOS programs, manuals, backups or unused original graphics formats.
names=('M3D.MAN','TEXTD.BLK','M3.DAT','M3.MEN','M3PC.COL','OBMHPROF.INI')
entries={'RUNTIME.DAT':data}
for name in names:
file=next(p for p in source.iterdir() if p.name.upper()==name)
entries[name]=file.read_bytes()
for directory in ('KB','W','F','S'):
root=next(p for p in source.iterdir() if p.name.upper()==directory)
for file in sorted(root.iterdir()):
if not file.is_file():continue
if directory in ('KB','W') and file.suffix.upper()!='.VGA':continue
if directory=='F' and file.name.upper() not in ('BMH2.FNT','BMH3.FNT'):continue
if directory=='S' and file.name not in ('2000','2001','2002','2003'):continue
entries[directory+'/'+file.name.upper()]=file.read_bytes()
receipt={'format':'openbmh-community-1','files':{name:hashlib.sha256(value).hexdigest() for name,value in entries.items()},
'executable_code_included':False,'profile':'classic-plus-1'}
entries['PACKAGE.json']=(json.dumps(receipt,indent=2)+'\n').encode()
archive=destination/'COMMUNITY.OBD'
with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
for name,value in entries.items():z.writestr(name,value)
report=source/'IMPORT-REPORT.json'
if report.exists():(destination/report.name).write_bytes(report.read_bytes())
print(json.dumps({'bundle_bytes':archive.stat().st_size,'uncompressed_resource_bytes':sum(map(len,entries.values())),
'resource_count':len(entries),'runtime_bytes':len(data),'bundle_sha256':hashlib.sha256(archive.read_bytes()).hexdigest()}))
finally:runtime.unlink(missing_ok=True)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--exporter',type=Path,required=True);a=p.parse_args();build(a.source,a.out,a.exporter)
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/le.hpp"
#include "formats/executable_layout.hpp"
#include "formats/badge_policy.hpp"
#include "game/calendar.hpp"
#include "game/environment.hpp"
#include <iostream>
int main(int argc,char**argv)try {
if(argc!=3)throw std::runtime_error("usage: export_community_runtime <supplied executable> <output runtime.dat>");
const auto image=bmh::load_le(argv[1]);
const auto epoch=bmh::calendar_epoch_from_executable(image);
bmh::install_environment_rules(image);
bmh::RuntimePolicy policy{uint32_t(epoch.year),uint32_t(epoch.weekday),uint32_t(bmh::original_badge_gate(image)),uint32_t(bmh::environment_rules_supported()),{}};
for(auto address:{bmh::layout::FreeKickTakerLabel,bmh::layout::PenaltyTakerLabel,bmh::layout::CornerTakerLabel,bmh::layout::AutomaticTakersLabel})
policy.labels.emplace(address,image.cstring(address));
bmh::save_runtime_image(image,policy,argv[2]);
std::cout<<"Data-only runtime exported; no DOS header, loader or code objects\n";return 0;
}catch(const std::exception& e){std::cerr<<e.what()<<'\n';return 1;}
+35 -8
View File
@@ -95,6 +95,33 @@ def encode_vga(width, height, pixels):
def find_file(root, name):
return next(p for p in root.iterdir() if p.name.upper() == name.upper())
def original_crest_background(source):
"""Recover the shared bright crest texture from the supplied domestic sheets."""
sheets = {}
samples = []
directory = find_file(source, 'W')
for cell in range(90):
page = cell // 8
if page not in sheets:
sheets[page] = decode_vga(find_file(directory, str(page) + '.VGA').read_bytes())
width, height, pixels = sheets[page]
if (width, height) != (304, 38):
raise ValueError('Unexpected Original crest-sheet dimensions')
samples.append(bytes(pixels[y*width+(cell%8)*38+x] for y in range(38) for x in range(38)))
return crest_background_from_samples(samples)
def crest_background_from_samples(samples):
if not samples or any(len(s) != 38*38 for s in samples):
raise ValueError('Invalid crest background samples')
# The Original bright paper texture uses these four adjacent palette entries.
background = bytearray()
for pos in range(38*38):
counts = collections.Counter(s[pos] for s in samples if 92 <= s[pos] <= 95)
background.append(counts.most_common(1)[0][0] if counts else 94)
return bytes(background)
def repeated_native_images(clubs, assets, read):
"""Detect shared Original fallback images without baking in game pixels/hashes."""
counts = collections.Counter()
@@ -214,6 +241,10 @@ def build(source, donor, output):
palette=find_file(source,'M3PC.COL').read_bytes()
rgb=[tuple(((v&63)*255+31)//63 for v in palette[i:i+3]) for i in range(0,768,3)]
sheets={}; crest_report=[]; cache={}
backdrop = original_crest_background(source)
backdrop_image = Image.frombytes('P',(38,38),backdrop)
backdrop_image.putpalette([value for color in rgb for value in color])
backdrop_image = backdrop_image.convert('RGBA')
w_dir=find_file(source,'W')
def sheet(n):
if n not in sheets:
@@ -250,22 +281,18 @@ def build(source, donor, output):
color = '#%02x%02x%02x' % rgb[64 + index % 16]
svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="38" height="38"><path d="M5 3H33L31 24L19 35L7 24Z" fill="{color}" stroke="#f0f5f3" stroke-width="2"/><path d="M8 9H30" stroke="#f0f5f3"/><text x="19" y="23" text-anchor="middle" font-family="sans-serif" font-size="10" font-weight="bold" fill="white">{html.escape(initials)}</text></svg>'
image=Image.open(io.BytesIO(cairosvg.svg2png(bytestring=svg.encode()))).convert('RGBA')
foreground = [(r,g,b) for r,g,b,a in image.getdata() if a >= 128]
contrast_adjusted = bool(foreground) and sum(max(pixel) for pixel in foreground)/len(foreground) < 60
if contrast_adjusted:
alpha=image.getchannel('A');image=Image.new('RGBA',image.size,(238,244,240,0));image.putalpha(alpha)
contrast_adjusted = False # Black silhouettes remain readable on the Original bright background.
image=ImageOps.contain(image,(36,36),method=Image.Resampling.LANCZOS)
canvas=Image.new('RGBA',(38,38));canvas.alpha_composite(image,((38-image.width)//2,(38-image.height)//2))
canvas=backdrop_image.copy();canvas.alpha_composite(image,((38-image.width)//2,(38-image.height)//2))
pixels=bytearray()
for r,g,b,a in canvas.getdata():
if a<128:pixels.append(0);continue
key=(r,g,b)
if key not in cache:cache[key]=min(range(1,256),key=lambda n:sum((x-y)**2 for x,y in zip(rgb[n],key)))
if key not in cache:cache[key]=min(range(256),key=lambda n:sum((x-y)**2 for x,y in zip(rgb[n],key)))
pixels.append(cache[key])
dst=sheet(cell//8)
for y in range(38):dst[y*304+(cell%8)*38:y*304+(cell%8)*38+38]=pixels[y*38:(y+1)*38]
badges[index]=(badges[index]&~511)|cell
crest_report.append({'club':club['id'],'runtime_team':index,'cell':cell,'asset':club.get('crest'),'source':asset.get('source'),'license':asset.get('license'),'fictional':fictional,'contrast_adjusted':contrast_adjusted,'last_decode_error':error})
crest_report.append({'club':club['id'],'runtime_team':index,'cell':cell,'asset':club.get('crest'),'source':asset.get('source'),'license':asset.get('license'),'fictional':fictional,'contrast_adjusted':contrast_adjusted,'background':'original-crest-texture','last_decode_error':error})
db['badges']=words(badges)
# Every Original player word and all German starting rosters remain unchanged.
original_db = read_master(master)
+9 -1
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: GPL-3.0-only
"""Synthetic encoder/reader tests; no Original game content required."""
import unittest
from prepare_international import decode_vga, encode_vga, legacy_name, read_master, write_master, words, repeated_native_images
from prepare_international import decode_vga, encode_vga, legacy_name, read_master, write_master, words, repeated_native_images, crest_background_from_samples
class ProfileDataTests(unittest.TestCase):
def test_master_identity_and_sizes(self):
@@ -37,6 +37,14 @@ class ProfileDataTests(unittest.TestCase):
found=repeated_native_images(clubs,assets,lambda path: {'shared':b'placeholder','real':b'individual-crest'}[path])
self.assertEqual(found,{hashlib.sha256(b'placeholder').hexdigest()})
def test_original_background_recovers_texture(self):
texture=bytes(92+(i%4) for i in range(38*38))
samples=[bytearray(texture) for _ in range(7)]
for j, sample in enumerate(samples):
for i in range(j*100,j*100+80):sample[i]=0
self.assertEqual(crest_background_from_samples(samples),texture)
self.assertNotIn(0,crest_background_from_samples(samples))
def test_original_encoding(self):
self.assertEqual(legacy_name('Müller'),b'M}LLER')
self.assertEqual(legacy_name('Sørloth'),b'SORLOTH')