Fork the Classic season core into src/modern and add the world layout (M1)

- src/modern/game: the season modules as bmh::modern, working on ModernState
  (a GameState). Data types stay shared with Classic; Modern code calls its
  season functions qualified (modern::...), so a missing Modern function is a
  compile error instead of a silent call into Classic.
- src/modern/app/modern_session: the session on the Modern core. It still uses
  the Classic UI projections until the Modern projections exist.
- SeasonHooks: the shared match core reaches player statistics and the table
  prediction of the season core that owns the game (Classic: unchanged).
- WorldLayout: team ranges, squad slots and pools of the running world. Shared
  code and the Modern fork read them; Classic keeps the original numbers.
- Transfer list views moved to game/transfer_offer_view.hpp (shared).
- tools/modern/check_fork_calls.sh, modern_season_sim and world_layout_tests.

Verified: Classic tests and replay regression unchanged; season_sim and
modern_season_sim produce identical output with Classic data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-23 18:08:54 +02:00
1 parent badd08f05e
commit f2fcb28f65
81 files changed
+29351 -91

No files matched your search

+362
View File
@@ -0,0 +1,362 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/balance_plan.hpp"
#include <algorithm>
#include <cmath>
#include "modern/game/prediction.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include "modern/game/week.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr uint32_t kPlanTicketPrice = ::bmh::layout::PlanTicketPrice; // one byte per manager
// BalancePlanRuntimeField: months left in the business year by calendar month (July: 12, June: 1)
constexpr int8_t kMonthsLeft[13] = {0, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7};
// BalancePlanRuntimeField2: which rows can be changed; BalancePlanRuntimeField3: the class of the maximum
// (BalancePlanRuntimeField4: 30 million, 25, 100000, 2 million)
constexpr uint8_t kEditable[0x16] = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1};
constexpr uint8_t kMaximumClass[0x16] = {0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 1, 2, 1};
constexpr int32_t kMaximum[4] = {30000000, 25, 100000, 2000000};
// BalancePlanRuntimeField5: monthly running costs of the stadium facilities (BMHExeXa)
constexpr uint16_t kFacilityCost[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600,
2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000};
// BalancePlanRuntimeField6: monthly income of the first six facilities (FacilityIncome)
constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000};
// BalancePlanRuntimeField7: catering income per visitor of the facilities 0-13 (BookMoney)
constexpr uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2};
// Rec32: price units of the six funds (BMH.exe+MonthRuntimeField10)
constexpr int32_t kShareUnits[6] = {15, 18, 21, 24, 27, 30};
int32_t rec32(const ModernState& g, int m, size_t o) {
const size_t at = size_t(m) * kRecordSize + o;
const auto& r = g.manager_records;
return int32_t(uint32_t(r.at(at)) | uint32_t(r.at(at + 1)) << 8 | uint32_t(r.at(at + 2)) << 16 | uint32_t(r.at(at + 3)) << 24);
}
void set_rec32(ModernState& g, int m, size_t o, int32_t v) {
for (int i = 0; i < 4; i++) g.manager_records.at(size_t(m) * kRecordSize + o + size_t(i)) = uint8_t(uint32_t(v) >> (8 * i));
}
uint8_t rec8(const ModernState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * kRecordSize + o); }
int32_t mem32(const ModernState& g, uint32_t a) { return g.memory.has(a + 3) ? int32_t(g.memory.u32(a)) : 0; }
int32_t wrap(int64_t v) { return int32_t(uint32_t(uint64_t(v))); }
// Add32: the level of a facility (facility 0: its size step)
uint32_t facility_level(const ModernState& g, int m, int k) {
const uint8_t v = rec8(g, m, size_t(k));
return k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xff : 1;
}
// DailyInterest2(0): the interest of one day without booking it - negative is income
// (balance 1 %, fixed deposit 2 % a year), positive an expense (overdraft 12 %, beyond the
// credit line 18 %). The divisor is -36500.
int32_t daily_interest_preview(const ModernState& g, int m) {
constexpr int32_t kAnnual = -0x8e94;
const int32_t balance = rec32(g, m, 0x314), deposit = rec32(g, m, 0x318), credit = rec32(g, m, 0x31c);
int32_t result = 0;
if (balance < 0) {
const int32_t with_credit = wrap(int64_t(balance) + credit);
if (with_credit < 0) result = wrap(int64_t(with_credit) * 0x12) / kAnnual;
int32_t below = wrap(-int64_t(credit));
if (below < balance) below = balance;
result = wrap(int64_t(result) + wrap(int64_t(below) * 0xc) / kAnnual);
} else {
result = balance / kAnnual;
}
return wrap(int64_t(result) + wrap(int64_t(deposit / 10000) * 20000) / kAnnual);
}
// SharesAndLoans(manager, flags, months): flags 1 the dividends of the manager's funds and
// the loans he gave to other managers (income), 2 the loans he took (expense, negative);
// flag 4 multiplies by the months (loans: at most their remaining months).
int32_t shares_and_loans(const ModernState& g, int m, int flags, int months) {
int32_t sum = 0;
if (flags & 1) {
for (int k = 0; k < 6; k++) {
const uint32_t unit = g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareUnits[k]) / 10000;
sum = wrap(int64_t(sum) + int64_t(unit * g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c)));
}
if (flags & 4) sum = wrap(int64_t(sum) * months);
}
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
for (int c = 0; c <= managers; c++) {
uint32_t row = uint32_t(c) * 0x18 + uint32_t(m) * 0x78;
int32_t amount = mem32(g, ::bmh::layout::Loans + row + 8);
if (amount != 0 && (flags & 2)) {
if (!(flags & 4)) {
sum = wrap(int64_t(sum) - amount);
} else {
int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10));
sum = wrap(int64_t(sum) - int64_t(std::min(left, months)) * amount);
}
}
if (c == 0) continue;
row = uint32_t(m + 1) * 0x18 + uint32_t(c - 1) * 0x78;
amount = mem32(g, ::bmh::layout::Loans + row + 8);
if (amount != 0 && (flags & 1)) {
if (!(flags & 4)) {
sum = wrap(int64_t(sum) + amount);
} else {
int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10));
sum = wrap(int64_t(sum) + int64_t(std::min(left, months)) * amount);
}
}
}
return sum;
}
// MonthlyPay(manager, 0xb): a month of the squad's pay - bonus base (+0x4e), salary
// (+0x50) and the bonus each player can expect (ContractOffer with the fitness correction)
// for the predicted final rank (Void5 mode 4). Changes scratch tables: `g` is a copy.
int32_t monthly_pay(ModernState& g, int m, uint8_t flags = 0xb) {
const int team = g.manager_teams.at(size_t(m));
std::array<uint8_t, 24> buf{};
const int predicted = modern::table_prediction(g, team, 4, buf);
const int rank = predicted == 0 ? 0xb : predicted + 1;
const SquadRange range = squad_range(team);
int32_t sum = 0;
for (int s = 0; s < 0x18; s++) {
const size_t slot = size_t(m) * 0x840 + size_t(s) * 0x58;
if (g.tactics.at(slot + 0x3d) == 0xff) continue;
const int32_t bonus = int32_t((g.tactics.at(slot + 0x4e) | g.tactics.at(slot + 0x4f) << 8) & 0x7fff);
const int32_t salary = int32_t(uint32_t(g.tactics.at(slot + 0x50)) | uint32_t(g.tactics.at(slot + 0x51)) << 8 |
uint32_t(g.tactics.at(slot + 0x52)) << 16 | uint32_t(g.tactics.at(slot + 0x53)) << 24);
// a board row whose squad slot is empty (0xfff) makes the original read a player
// beyond the table; the port counts no expected bonus for it
const size_t player = g.squad_slots.at(range.first + size_t(s)) & 0xfff;
const int32_t expected = (flags & 1) && player < g.players.size() ? int32_t(modern::expected_bonus(g, m, rank, s, int(player), true)) : 0;
sum = wrap(int64_t(sum) + ((flags & 2) ? salary : 0) +
((flags & 1) ? expected : 0) + ((flags & 8) ? bonus : 0));
}
return sum;
}
// BMHExeXa: the facilities' monthly running costs
int32_t facility_costs(const ModernState& g, int m) {
int32_t sum = 0;
for (int i = 0; i < 0xe; i++) sum += kFacilityCost[i];
for (int i = 0xe; i < 0x16; i++) sum += (rec8(g, m, 0x2e + size_t(i)) & 7) * kFacilityCost[i];
return sum;
}
// FacilityIncome: the facilities' monthly income
int32_t facility_income(const ModernState& g, int m) {
int32_t sum = 0;
for (int k = 0; k < 6; k++)
if (rec8(g, m, size_t(k)) != 0) sum += int32_t(facility_level(g, m, k)) * kFacilityIncome[k];
return sum;
}
// BookMoney(manager, gate, 1): kiosks and restaurants of one home game, without the
// random factor
uint32_t catering_per_game(const ModernState& g, int m, int32_t gate) {
uint32_t sum = 0;
for (int k = 0; k < 14; k++)
if (rec8(g, m, size_t(k)) != 0) sum += kPerVisitor[k] * uint32_t(gate) * facility_level(g, m, k) / 100;
return sum;
}
// The redraw of BalanceFromGame2 (with its continuation Redraw and the patch at
// Redraw2): recomputes the items if `refresh` asks for it, then the spectator income
// and the totals.
void redraw(const ModernState& source, BalancePlanDraft& d) {
const int m = d.manager;
const int view = int(d.view);
auto& r = d.rows;
r[3] = view < 2 ? rec32(source, m, 0x868) : 0;
int32_t home = r[kBalanceLeagueHomeGames] + r[kBalanceOtherHomeGames]; // local_48
if (view == 0) home = 0;
if (view < 2) {
const int month = modern::month_code(source.date);
d.months_left = month >= 1 && month <= 12 ? kMonthsLeft[month] : 0;
d.days_left = 0x16d - source.season_day();
const bool first_of_month = source.date == 0 || modern::month_code(source.date - 1) != month;
if (source.season_day() != 0 && month == 7 && first_of_month) d.months_left = d.days_left = 0;
home -= int8_t(rec8(source, m, 0x28c)) + int8_t(rec8(source, m, 0x28d)) + int8_t(rec8(source, m, 0x28e));
if (home < 0) home = 0;
} else {
d.months_left = 12;
d.days_left = 0x16d;
}
const int months = int8_t(d.months_left);
if (d.refresh != 0) {
if (view < 2) {
for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = rec32(source, m, 0x85c + size_t(i) * 4);
r[7] = wrap(int64_t(rec32(source, m, 0x33c)) + rec32(source, m, 0x334) + rec32(source, m, 0x338));
} else {
std::fill(r.begin(), r.begin() + kBalanceItems, 0);
}
if (view != 0 && months != 0)
for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = wrap(int64_t(r[size_t(i)]) + d.adjustments[size_t(i)] * 12 / months);
if (d.refresh != 2) r[kBalanceAverageGate] = r[kBalanceGateSoFar];
if (view != 0) {
ModernState g = source; // scratch copy, see the header
const int32_t interest = wrap(int64_t(int16_t(d.days_left)) * daily_interest_preview(g, m));
if (interest < 1) r[5] = wrap(int64_t(r[5]) - interest);
else r[0x10] = wrap(int64_t(r[0x10]) + interest);
r[5] = wrap(int64_t(r[5]) + shares_and_loans(g, m, 5, months));
r[0x10] = wrap(int64_t(r[0x10]) - shares_and_loans(g, m, 6, months));
// advertising: shirt (+0xadc) and TV (+0xae8) contracts, the 14 boards (+0xa34);
// free boards are expected to bring 80 % of the average board
r[0] = wrap(int64_t(r[0]) + int64_t(rec32(g, m, 0xadc)) * months);
r[2] = wrap(int64_t(r[2]) + int64_t(months) * rec32(g, m, 0xae8));
int boards = 0;
for (int s = 0; s < 0xe; s++) {
const int32_t v = rec32(g, m, 0xa34 + size_t(s) * 0xc);
if (v != 0) boards++;
r[1] = wrap(int64_t(r[1]) + int64_t(v) * months);
}
if (g.memory.u8(::bmh::layout::GameMode) == 1 || (g.memory.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0)) boards = 0xe;
if (boards != 0 && boards < 0xe) {
int32_t missing = (r[1] / boards) * (0xe - boards);
if (months != 0) missing /= months;
r[1] = wrap(int64_t(r[1]) + int64_t(months) * ((int64_t(missing) * 0x50) / 100));
}
r[7] = wrap(int64_t(r[7]) + int64_t(monthly_pay(g, m)) * months);
r[8] = wrap(int64_t(r[8]) + int64_t(facility_costs(g, m)) * months);
r[4] = wrap(int64_t(r[4]) + int64_t(facility_income(g, m)) * months);
const uint32_t catering = catering_per_game(g, m, r[kBalanceAverageGate]);
r[4] = wrap(int64_t(r[4]) + int64_t((catering * uint32_t(home)) / 12) * months);
const uint32_t costs = ::bmh::layout::Spending + uint32_t(m) * 0x24;
for (int k = 0; k < 3; ++k) {
const auto value = modern::environment_monthly_cost(g, m, k);
const auto raw = mem32(g, costs + uint32_t(k) * 4);
const int count = k == kYouthAcademy && raw > kEnvironmentStep[k] * 6 ? 1 : months;
r[9] = wrap(int64_t(r[9]) + int64_t(count) * value);
}
for (int k = 0; k < 3; k++) r[size_t(10 + k)] = wrap(int64_t(r[size_t(10 + k)]) + int64_t(months) * mem32(g, costs + 0xc + uint32_t(k) * 4));
for (int k = 0; k < 2; k++) r[size_t(14 + k)] = wrap(int64_t(r[size_t(14 + k)]) + int64_t(months) * rec32(g, m, 0x854 + size_t(k) * 4));
}
d.refresh = 0;
}
// the view "real" leaves out the season tickets of the remaining league home games
int32_t season_tickets = 0;
if (view == 1) {
int32_t sold = int32_t(uint16_t(rec8(source, m, 0x2ac) | rec8(source, m, 0x2ad) << 8));
if (r[kBalanceAverageGate] < sold) sold = r[kBalanceAverageGate];
int32_t games = r[kBalanceLeagueHomeGames] - int8_t(rec8(source, m, 0x28c));
if (games < 0) games = 0;
season_tickets = wrap(int64_t((sold * 0x46) / 100) * r[kBalanceTicketPrice] * games);
}
r[3] = wrap(int64_t(r[3]) + (int64_t(home) * r[kBalanceTicketPrice] * r[kBalanceAverageGate] - season_tickets));
double total = 0;
for (int i = 0; i < kBalanceItems; i++) {
if (r[size_t(i)] < 0) r[size_t(i)] = 0;
total += double(r[size_t(i)]) * (i < 7 ? 1 : -1);
}
d.depreciation = view < 2 ? rec32(source, m, 0x30c) : 0;
d.total = total - double(d.depreciation);
}
} // namespace
// StadiumRequiredAttendance: Source's monthly preview differs from booked month_change totals.
// Prediction may touch scratch tables; both pay previews run on an owned copy.
int32_t stadium_required_attendance(const ModernState& source, int manager) {
if (manager < 0 || manager > 4) throw FormatError("stadium attendance: invalid manager");
ModernState g = source;
const int team = g.manager_teams.at(size_t(manager));
const int league = team > 0x164 ? 0 : team_league(team);
if (league < 0 || league >= kLeagueCount)
throw FormatError("stadium attendance: manager has no Source league");
const int home_games = league_matchdays(league) / 2;
if (home_games <= 0) throw FormatError("stadium attendance: invalid Source league home count");
const int m = manager;
int32_t costs = wrap(int64_t(facility_costs(g, m)) + rec32(g, m, 0x854) + rec32(g, m, 0x858));
costs = wrap(int64_t(costs) + monthly_pay(g, m, 0xa));
for (int k = 0; k < 6; ++k) {
const int32_t value = modern::environment_monthly_cost(g, m, k);
costs = wrap(int64_t(costs) + value);
}
costs = wrap(int64_t(costs) - shares_and_loans(g, m, 2, 0) + int(rec8(g, m, 0x179)) * 1000);
if (costs < 0) costs = 0;
int32_t income = facility_income(g, m);
for (int i = 0; i < 16; ++i) income = wrap(int64_t(income) + rec32(g, m, 0xa34 + size_t(i) * 12));
constexpr int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // DeskState_DeskDate_RuntimeField
const int month = modern::month_code(g.date);
if (month < 1 || month > 12) throw FormatError("stadium attendance: invalid Source month");
income = wrap(int64_t(income) + shares_and_loans(g, m, 1, 0) -
int64_t(daily_interest_preview(g, m)) * days[month]);
const int32_t bonus = monthly_pay(g, m, 9);
int32_t needed = wrap(int64_t(wrap(int64_t(costs) - income)) * 12 + bonus) / home_games;
const int price = rec8(g, m, 0x26e);
if (price != 0) needed /= price;
return std::max(needed, int32_t(0));
}
BalancePlanDraft open_balance_plan(const ModernState& g, int manager) {
BalancePlanDraft d;
d.manager = manager;
const int m = manager;
d.view = BalanceView(std::clamp(int(int8_t(rec8(g, m, 0x310))), 0, 2));
const int league = team_league(g.manager_teams.at(size_t(m)));
auto& r = d.rows;
r[kBalanceLeagueHomeGames] = league < kLeagueCount ? league_matchdays(league) / 2 : 0;
r[kBalanceOtherHomeGames] = rec32(g, m, 0x2f8);
r[kBalanceAverageGate] = rec32(g, m, 0x2fc);
uint8_t ticket = g.memory.has(kPlanTicketPrice + uint32_t(m)) ? g.memory.u8(kPlanTicketPrice + uint32_t(m)) : 0;
if (ticket == 0) ticket = rec8(g, m, 0x26e);
r[kBalanceTicketPrice] = ticket;
r[kBalanceAccount] = rec32(g, m, 0x314);
// the average gate of the last league home games (+0x340, count +0x283)
int32_t sum = 0;
const int games = rec8(g, m, 0x283);
for (int i = 0; i < games; i++) sum = wrap(int64_t(sum) + rec32(g, m, 0x340 + size_t(i) * 4));
r[kBalanceGateSoFar] = games != 0 ? sum / games : sum;
if (rec32(g, m, 0x300) != 0) r[kBalanceAverageGate] = rec32(g, m, 0x304) / rec32(g, m, 0x300);
for (int i = 0; i < kBalanceItems; i++) d.adjustments[size_t(i)] = rec32(g, m, 0x2b0 + size_t(i) * 4);
d.refresh = 2;
redraw(g, d);
return d;
}
void cycle_balance_view(const ModernState& g, BalancePlanDraft& d) {
d.view = BalanceView((int(d.view) + 1) % 3);
d.refresh = d.rows[kBalanceAverageGate] != 0 ? 2 : 1;
redraw(g, d);
}
void reset_balance_plan(const ModernState& g, BalancePlanDraft& d) {
d.adjustments.fill(0);
d.refresh = 1;
redraw(g, d);
}
int32_t balance_row_maximum(const BalancePlanDraft& d, int row) {
if (row < 0 || row >= 0x16 || !kEditable[row]) return -1;
(void)d; // the input dialog BalanceFromGame only offers other step sizes for the gate
return kMaximum[kMaximumClass[row]];
}
BalanceEditStatus edit_balance_plan(const ModernState& g, BalancePlanDraft& d, int row, int32_t value) {
if (row < 0 || row >= 0x16 || !kEditable[row]) return BalanceEditStatus::not_editable;
if (d.view == BalanceView::so_far) return BalanceEditStatus::view_so_far;
if (value < 0 || value > modern::balance_row_maximum(d, row)) return BalanceEditStatus::out_of_range;
if (row < kBalanceItems)
d.adjustments[size_t(row)] = wrap(int64_t(d.adjustments[size_t(row)]) +
wrap(int64_t(int8_t(d.months_left)) * (int64_t(value) - d.rows[size_t(row)])) / 12);
d.rows[size_t(row)] = value;
if (row > 0x11) d.refresh = 2;
redraw(g, d);
return BalanceEditStatus::changed;
}
bool close_balance_plan(ModernState& g, const BalancePlanDraft& d) {
const int m = d.manager;
const bool warning = double(rec32(g, m, 0x314)) + d.total < -4000000.0; // BalancePlanRuntimeField8
for (int i = 0; i < kBalanceItems; i++) set_rec32(g, m, 0x2b0 + size_t(i) * 4, d.adjustments[size_t(i)]);
set_rec32(g, m, 0x308, int32_t(std::lround(d.total)));
if (g.memory.has(kPlanTicketPrice + uint32_t(m))) g.memory.set8(kPlanTicketPrice + uint32_t(m), uint8_t(d.rows[kBalanceTicketPrice]));
set_rec32(g, m, 0x2f8, d.rows[kBalanceOtherHomeGames]);
set_rec32(g, m, 0x2fc, d.rows[kBalanceAverageGate]);
set_rec32(g, m, 0x310, int32_t(d.view));
return warning;
}
} // namespace bmh::modern
+65
View File
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/balance_plan.hpp"
// All three youth budgets and staff costs share the monthly environment model.
// The balance plan ("Bilanz", desk menu 28, mode III; H2 p. 26-27; BMH.exe V2.24 + supported rule profile
// patch): the screen BalanceFromGame2 projects the club's income and expenses for the business
// year and lets the manager change every item. When he leaves the screen the resulting
// profit/loss becomes the plan figure (manager record +0x308). On the 16th Bundesliga
// matchday the plan is handed to the DFB (+0x308 -> +0x320, matchday.cpp); from then on it
// lifts or lowers the advertising offers (weekly.cpp, plan / 100000 within -10..10) and at
// the end of the season the DFB punishes a result more than 1 million below the plan
// (season.cpp, SeasonEvent).
//
// The screen has three views (left button, captions BalancePlan_DrawButtons_TextPointer):
// so_far "bisher" - the booked figures of the season so far (record +0x85c..), no changes
// real "real" - booked figures plus a projection for the months left
// future "zukunft" - a projection for twelve months
// The manager's changes are kept per item normalised to twelve months (record +0x2b0, the
// screen's local_c8) and are added again on the next visit; "Werte akt." (right button)
// drops them.
//
// The screen's state is a BalancePlanDraft (the locals of BalanceFromGame2); the functions below
// are its event handlers. Projections run on a copy of the ModernState: the wage projection
// (MonthlyPay -> table prediction) writes scratch tables, and a console must be able to
// look at the plan without changing the game.
#include <array>
#include <cstdint>
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
constexpr int kBalanceItems = 18; // 0-6 income, 7-17 expenses (labels BalancePlan_DrawRows_TextPointer5)
// Rows after the items (labels BalancePlan_DrawRows_TextPointer4): league home games, other home games, average
// gate (calculated), ticket price, average gate so far, account balance.
// BalanceFromGame2 up to its first redraw: the draft of `manager` with the stored view, the
// stored changes and the projection of that view.
// StadiumRequiredAttendance: minimum average attendance at the current stadium entry price.
// Pure preview, using a copy for Source prediction scratch writes; no RNG.
int32_t stadium_required_attendance(const ModernState&, int manager);
BalancePlanDraft open_balance_plan(const ModernState& g, int manager);
// The left button: the next view (so_far -> real -> future -> so_far), projected again.
void cycle_balance_view(const ModernState& g, BalancePlanDraft& draft);
// The right button "Werte akt.": drops the manager's changes and projects again.
void reset_balance_plan(const ModernState& g, BalancePlanDraft& draft);
// Range of a row in the number input (BalanceFromGame): 0 .. maximum.
int32_t balance_row_maximum(const BalancePlanDraft& draft, int row);
// A click on a row and a new value: items keep the change in `adjustments` (scaled to twelve
// months); the home games, the gate and the ticket price project the plan again.
BalanceEditStatus edit_balance_plan(const ModernState& g, BalancePlanDraft& draft, int row, int32_t value);
// Leaving the screen: writes the changes (+0x2b0), the plan figure (+0x308), the other home
// games and the gate (+0x2f8/+0x2fc), the view (+0x310) and the ticket price of the plan
// (PlanTicketPrice). Returns true when the DFB demands a better balance (account + plan below
// -4 million, message BalancePlan_BalanceFromGame_TextPointer2) - the plan is stored nevertheless.
bool close_balance_plan(ModernState& g, const BalancePlanDraft& draft);
} // namespace bmh::modern
+258
View File
@@ -0,0 +1,258 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/bank_credit.hpp"
#include <bit>
#include <cmath>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <utility>
#include "modern/game/matchday.hpp"
namespace bmh::modern {
namespace {
constexpr uint32_t kLoans = ::bmh::layout::Loans;
constexpr size_t kRecord = 0xb0c;
int32_t signed_word(uint32_t v) { return std::bit_cast<int32_t>(v); }
uint32_t word(int32_t v) { return std::bit_cast<uint32_t>(v); }
int32_t add(int32_t a, int32_t b) { return signed_word(word(a) + word(b)); }
int32_t sub(int32_t a, int32_t b) { return signed_word(word(a) - word(b)); }
int32_t mul(int32_t a, int32_t b) { return signed_word(word(a) * word(b)); }
int32_t divide(int32_t a, int32_t b) {
if (!b || (a == std::numeric_limits<int32_t>::min() && b == -1))
throw std::invalid_argument("invalid native credit division");
return a / b;
}
uint32_t read_record(const ModernState& g, size_t at) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= uint32_t(g.manager_records.at(at + i)) << (i * 8);
return v;
}
// Amount: signed IMUL/IDIV, x87 intermediate, QWORD store,
// exact-zero floor, then Amount2's explicit rounding toward zero.
int32_t amount(const BankCreditContext& c, uint32_t months, int32_t principal) {
if (months > 48 || c.rate_table[months] <= 100 || c.divisor != 100.0)
throw std::invalid_argument("invalid native credit factors");
const int32_t factor = c.rate_table[months];
const int32_t base = divide(mul(principal, factor), 100);
const int32_t den = divide(10000, factor - 100);
const long double intermediate = (static_cast<long double>(base) / c.divisor)
* den / c.divisor;
double raw = static_cast<double>(intermediate);
if (raw == 0 && principal != 0) raw = 1;
raw = std::trunc(raw);
if (!std::isfinite(raw) || raw < std::numeric_limits<int32_t>::min()
|| raw > std::numeric_limits<int32_t>::max())
throw std::invalid_argument("invalid native credit amount");
return static_cast<int32_t>(raw);
}
void balance(const BankCreditContext& c, BankCreditDraft& d) {
int32_t result = add(c.cash, signed_word(d.values[0]));
result = sub(result, signed_word(c.saved[0]));
result = sub(result, signed_word(d.values[6]));
result = add(result, d.refund);
result = sub(result, d.fees);
d.values[7] = word(sub(result, d.interest_adjustment));
}
}
BankCreditContext bank_credit_context(const ModernState& g, const LeImage& exe, int manager, int counterparty) {
BankCreditContext c;
if (manager < 0 || size_t(manager) >= g.manager_teams.size()
|| g.manager_records.size() < (size_t(manager) + 1) * kRecord) return c;
// case 5: another human manager lends (row lender + 1 of the borrower's matrix)
if (counterparty < 0 || counterparty > 4 || counterparty - 1 == manager ||
(counterparty > 0 && size_t(counterparty - 1) >= g.manager_teams.size())) return c;
c.counterparty = counterparty;
const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(counterparty) * 0x18;
try {
for (size_t i = 0; i < c.saved.size(); ++i) c.saved[i] = g.memory.u32(at + uint32_t(i) * 4);
for (size_t i = 0; i < c.rate_table.size(); ++i) c.rate_table[i] = exe.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i));
const uint64_t bits = uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32;
c.divisor = std::bit_cast<double>(bits);
const size_t rec = size_t(manager) * kRecord;
c.cash = signed_word(read_record(g, rec + 0x314));
c.overdraft = signed_word(read_record(g, rec + 0x31c));
if (counterparty > 0) {
const size_t lender = size_t(counterparty - 1) * kRecord;
c.lender_liquidity = add(signed_word(read_record(g, lender + 0x314)), signed_word(read_record(g, lender + 0x31c)));
}
c.available = c.divisor == 100.0 && c.saved[3] <= 48 && c.saved[4] <= 48;
for (auto factor : c.rate_table) c.available = c.available && factor > 100;
} catch (const std::out_of_range&) { return {}; }
return c;
}
bool change_bank_credit_interest(ModernState& g, int manager, uint8_t new_rate) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || !g.credit_rate_table_available)
return false;
const uint32_t at = kLoans + uint32_t(manager) * 0x78;
for (uint32_t i = 0; i < 24; ++i) if (!g.memory.has(at + i)) return false;
try {
const int32_t principal = signed_word(g.memory.u32(at));
const int32_t term = signed_word(g.memory.u32(at + 12));
const int32_t elapsed = signed_word(g.memory.u32(at + 16));
const int32_t remaining = sub(principal, mul(divide(principal, term), elapsed));
const int32_t adjusted = divide(remaining, 100);
const int32_t next_principal = mul(adjusted, 100 - int32_t(new_rate));
const int32_t next_term = sub(term, elapsed);
BankCreditContext c;
c.rate_table = g.credit_rate_table;
c.divisor = g.credit_divisor;
const uint32_t payment = word(amount(c, uint32_t(next_term), next_principal));
g.memory.set32(at, word(next_principal));
g.memory.set32(at + 12, word(next_term));
g.memory.set32(at + 16, 0);
g.memory.set32(at + 20, 0);
g.memory.set32(at + 8, payment);
g.memory.set32(at + 4, payment * uint32_t(next_term));
return true;
} catch (const std::exception&) { return false; }
}
BankCreditDraft bank_credit_draft(const BankCreditContext& c) {
BankCreditDraft d;
for (size_t i = 0; i < c.saved.size(); ++i) d.values[i] = c.saved[i];
// Source clears the working paid field after its first rendering. The UI
// still uses the saved field for that initial display.
d.values[5] = 0;
d.values[7] = word(c.cash);
return d;
}
BankCreditBounds bank_credit_bounds(const BankCreditContext& c, const BankCreditDraft& d, int field) {
if (!c.available || (field != 0 && field != 1 && field != 3 && field != 6 && !(field == 2 && c.counterparty))
|| (field == 6 && !c.saved[0])) return {};
try {
const auto& v = d.values;
int32_t accrued = 0;
if (v[0]) {
const uint32_t elapsed = v[4] ? v[4] : 1;
accrued = sub(mul(amount(c, elapsed, signed_word(v[0])), signed_word(elapsed)),
signed_word(v[5]));
}
const int32_t liquidity = add(c.cash, c.overdraft);
int32_t lo = 0, hi = 0;
if (field == 0) {
lo = 1000;
hi = sub(12000000, accrued);
// case 5: no more than the lender can pay out (balance + credit line)
if (c.counterparty && c.lender_liquidity < hi) hi = sub(c.lender_liquidity, accrued);
}
if (field == 2) {
// case 5 only: the monthly payment within 20 % of the annuity (Amount
// with the term and the net principal); the input starts at the annuity of
// the whole principal
const int32_t rate = amount(c, v[3], signed_word(v[0] - v[6]));
lo = sub(rate, rate / 5);
hi = add(rate, rate / 5);
if (lo >= hi || lo < 0) return {};
return {word(lo), word(hi), word(amount(c, v[3], signed_word(v[0]))), true};
}
if (field == 1) { lo = c.cash < accrued ? sub(accrued, liquidity) : liquidity; hi = accrued; }
if (field == 3) {
lo = 1;
hi = amount(c, v[3], signed_word(v[0] - v[6])) == 0 ? 0 : 48;
}
if (field == 6) { hi = liquidity < accrued ? liquidity : signed_word(v[0]); }
// Source checks availability before overriding the principal bounds.
if (lo >= hi) return {};
if (field == 0 && lo < signed_word(c.saved[0])) { lo = signed_word(c.saved[0]); hi = 12000000; }
if (lo < 0 || hi < 0 || lo >= hi) return {};
return {word(lo), word(hi), word(lo - (lo == 1)), true};
} catch (const std::invalid_argument&) { return {}; }
}
bool edit_bank_credit(const BankCreditContext& c, BankCreditDraft& draft, int field, uint32_t value) {
const auto bounds = modern::bank_credit_bounds(c, draft, field);
if (!bounds.available || value < bounds.minimum || value > bounds.maximum) return false;
BankCreditDraft d = draft;
try {
if (!d.interest_adjustment) {
d.principal_paid = c.saved[3]
? mul(signed_word(c.saved[4]), divide(signed_word(c.saved[0]), signed_word(c.saved[3])))
: mul(signed_word(c.saved[0]), signed_word(c.saved[4]));
}
d.values[field] = value;
// fees only for the bank (case 4)
d.fees = !c.counterparty && c.saved[0] && (d.values[6] || d.values[3] != c.saved[3]) ? 5000 : 0;
if (!d.interest_adjustment && (field == 0 || field == 3 || field == 6)) {
const int32_t term = c.saved[3] ? signed_word(c.saved[3]) : 1;
const int32_t saved_p = signed_word(c.saved[0]);
const int32_t remaining = sub(saved_p, d.principal_paid);
const int32_t interest = sub(sub(amount(c, 1, saved_p), saved_p),
sub(amount(c, 1, remaining), remaining));
d.interest_adjustment = divide(mul(interest, signed_word(c.saved[3] - c.saved[4])), term);
d.refund = mul(signed_word(c.saved[4]), divide(saved_p, term));
d.values[4] = d.values[5] = 0;
d.principal_paid = 0;
}
if (field != 2 && field != 3 && field != 6) d.values[3] = 48;
const int32_t net = signed_word(d.values[0] - d.values[6]);
// a monthly payment set in case 5 stays; every other edit computes the annuity
if (field != 2) d.values[2] = net ? word(amount(c, d.values[3], net)) : 0;
if (d.fees) d.fees = add(d.fees, sub(amount(c, 1, signed_word(d.values[6])), signed_word(d.values[6])));
d.values[1] = d.values[2] * d.values[3];
d.initial_display = false;
d.edits.push_back({field, value});
balance(c, d);
} catch (const std::invalid_argument&) { return false; }
draft = std::move(d);
return true;
}
BankCreditResult commit_bank_credit(ModernState& g, const LeImage& exe, int manager,
const std::array<uint32_t, 6>& expected, const std::vector<BankCreditEdit>& edits, bool accept_fees,
int counterparty) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return {BankCreditStatus::invalid_manager};
const auto c = modern::bank_credit_context(g, exe, manager, counterparty);
if (!c.available) return {BankCreditStatus::invalid_state};
if (c.saved != expected) return {BankCreditStatus::stale_request};
if (edits.empty()) return {BankCreditStatus::no_change};
if (edits.size() > 4096) return {BankCreditStatus::invalid_request};
auto d = modern::bank_credit_draft(c);
for (const auto& edit : edits)
if (!modern::edit_bank_credit(c, d, edit.field, edit.value)) return {BankCreditStatus::invalid_request};
// only the bank charges (and asks for) fees and the interest adjustment
const int32_t fees = c.counterparty ? 0 : add(d.fees, d.interest_adjustment);
const int lender = c.counterparty - 1;
if (fees && !accept_fees) return {BankCreditStatus::confirmation_required, fees, d.refund};
auto resulting_record = c.saved;
if (!d.values[1]) resulting_record.fill(0);
else {
for (size_t i = 0; i < 5; ++i) resulting_record[i] = d.values[i];
resulting_record[0] -= d.values[6];
if (signed_word(resulting_record[1]) < signed_word(resulting_record[0]))
resulting_record[1] += resulting_record[0];
if (signed_word(resulting_record[0]) < 1) resulting_record[0] = 1;
if (d.refund) resulting_record[4] = resulting_record[5] = 0;
}
if (!fees && !d.refund && c.saved[0] - d.values[0] + d.values[6] == 0
&& resulting_record == c.saved) return {BankCreditStatus::no_change};
ModernState staged = g;
if (fees) modern::book_money(staged, manager, fees, true, false);
if (d.refund) {
d.values[4] = 0;
// the repaid part comes back from the bank or from the lender
if (lender >= 0) modern::book_money(staged, lender, d.refund, true, false);
modern::book_money(staged, manager, sub(0, d.refund), true, false);
}
const int32_t principal_change = signed_word(c.saved[0] - d.values[0] + d.values[6]);
modern::book_money(staged, manager, principal_change, true, false);
if (lender >= 0) modern::book_money(staged, lender, sub(0, principal_change), true, false);
const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(c.counterparty) * 0x18;
if (!d.values[1]) {
for (uint32_t i = 0; i < 6; ++i) staged.memory.set32(at + i * 4, 0);
} else {
d.values[0] -= d.values[6];
if (signed_word(d.values[1]) < signed_word(d.values[0])) d.values[1] += d.values[0];
if (signed_word(d.values[0]) < 1) d.values[0] = 1;
for (uint32_t i = 0; i < 5; ++i) staged.memory.set32(at + i * 4, d.values[i]);
if (d.refund) staged.memory.set32(at + 20, 0);
}
g = std::move(staged);
return {BankCreditStatus::accepted, fees, d.refund};
}
} // namespace bmh::modern
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/bank_credit.hpp"
#include <array>
#include <cstdint>
#include <vector>
#include "formats/le.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// MaxSharesToBuy case 4 (the bank) and case 5 (another manager lends). Row c of
// each manager's native 0x78-byte loan matrix (Loans + borrower * 0x78 + c * 0x18)
// is the credit from the bank (c = 0) or from manager c - 1, and contains principal,
// total, monthly payment, term, elapsed months and payments made. Case 5 differs only
// in: the principal is limited by the lender's balance plus credit line, the monthly
// payment (field 2) can be set within 20 % of the annuity, there are no fees and no
// fee question, and every booking is mirrored on the lender. The original asks the
// lender nothing. Projection and draft editing are read-only.
BankCreditContext bank_credit_context(const ModernState&, const LeImage&, int manager, int counterparty = 0);
// ChangeBankCreditInterest: apply the automatic interest change to the bank loan record.
bool change_bank_credit_interest(ModernState&, int manager, uint8_t new_rate);
BankCreditDraft bank_credit_draft(const BankCreditContext&);
BankCreditBounds bank_credit_bounds(const BankCreditContext&, const BankCreditDraft&, int field);
bool edit_bank_credit(const BankCreditContext&, BankCreditDraft&, int field, uint32_t value);
// Replay the local Source edits against the current native record before
// booking; fees and refund are derived here, never trusted from a UI amount.
BankCreditResult commit_bank_credit(ModernState&, const LeImage&, int manager,
const std::array<uint32_t, 6>& expected, const std::vector<BankCreditEdit>& edits,
bool accept_fees, int counterparty = 0);
} // namespace bmh::modern
+684
View File
@@ -0,0 +1,684 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/career.hpp"
#include <algorithm>
#include "game/messages.hpp"
#include "game/schedule.hpp"
namespace bmh::modern {
namespace {
// LeagueSizes: clubs per league; LeagueStrengthRanges: (minimum, maximum) strength per league.
// (the clubs per league are kLeagueSizes, schedule.hpp)
constexpr int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28},
{85, 95}, {90, 95}, {75, 95}, {80, 95}};
} // namespace
void generate_player(ModernState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand) {
Player& p = g.players.at(size_t(id));
const bool keep_age = (level_flags & 0x1000) != 0, exact = (level_flags & 0x2000) != 0;
const int level = int16_t(level_flags & 0x0fff);
uint32_t w = 0x3000000; // goalkeepers
if ((p.w364 & 3) != 0) {
w = uint32_t(game.range(0, 7)) << 24;
w += uint32_t(game.range(0, 7)) << 21;
}
const int lo = exact ? level : level - level / 10, hi = exact ? level : level + level / 10;
const int condition = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); // ClampInteger
w += uint32_t(condition) << 14;
const int technique = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63);
w += uint32_t(technique) << 7;
p.w35c = w + uint32_t(game.range(0x23, 0x41));
p.w368 = (p.w368 & 0xff03c000u) + uint32_t(rand.range(0, 0x3fff));
p.w364 &= ~(0x1fu << 21);
if (!keep_age) p.w364 |= uint32_t(game.range(2, 5)) << 21;
}
std::vector<uint16_t> startup_squad_list(const Database& db) {
std::vector<uint16_t> slots(total_squad_slots(), 0x0fff);
for (size_t i = 0; i + 1 < db.squad_list.size() && i / 2 < slots.size(); i += 2)
slots[i / 2] = uint16_t(db.squad_list[i] | db.squad_list[i + 1] << 8);
std::copy_backward(slots.begin() + long((transfer_list_slot() + 40)), slots.begin() + long((transfer_list_slot() + 40) + (total_squad_slots() - free_agent_slot())), slots.end());
return slots;
}
void startup_players(ModernState& g, GameRandom& game, WatcomRandom& rand) {
for (size_t i = 0; i < 0x36; i++) {
const int level = rand.range(i < 0x16 ? 0x14 : 0x46, 0x5a);
modern::generate_player(g, int16_t(g.squad_slots.at((pool_end_slot() + 24) + i)), int16_t(level), game, rand);
}
int previous = 0, index = -1; // local_18, local_1c
for (int team = 0; team < league_clubs(); team++) {
const int league = team_league(team);
index = league == previous ? index + 1 : 0;
previous = league;
const uint32_t count = uint32_t(kLeagueSizes[league]);
const uint32_t range = uint32_t(kLeagueStrength[league][1] - kLeagueStrength[league][0]);
const int level = int16_t(int((count - uint32_t(index)) * range * 100) / int(count) / 100) + kLeagueStrength[league][0];
const SquadRange r = squad_range(team);
for (size_t s = r.first; s < r.first + r.count; s++) {
const int id = g.squad_slots.at(s) & 0x0fff;
if (id != 0x0fff) modern::generate_player(g, id, level | 0x1000, game, rand);
}
}
}
} // namespace bmh::modern
#include "formats/le.hpp"
#include "formats/savestate.hpp"
namespace bmh::modern {
ModernState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat) {
const DbCounts counts;
const std::vector<SaveBlock> layout = save_layout(counts, true);
Bytes stream;
for (const SaveBlock& b : layout) {
Bytes data(b.size, 0);
auto put = [&](const Bytes& src, size_t at = 0) {
for (size_t i = 0; i < src.size() && at + i < data.size(); i++) data[at + i] = src[i];
};
if (!b.heap) {
for (size_t i = 0; i < b.size; i++)
if (exe.contains(b.address + uint32_t(i))) data[i] = exe.u8(b.address + uint32_t(i));
}
switch (b.address) {
case ::bmh::layout::PlayerBonuses: if (b.heap) put(db.raw_player_bonus_values); break;
case ::bmh::layout::ClubBadgeSelectors: if (b.heap) put(db.raw_club_badge_selectors); break;
case ::bmh::layout::ClubIdentities: if (b.heap) put(db.raw_club_name_offsets); break;
case ::bmh::layout::PlayerNameOffsets: if (b.heap) put(db.raw_player_name_offsets); break;
case ::bmh::layout::MasterDatabaseMetadata: if (b.heap) put(db.raw_database_metadata); break;
case ::bmh::layout::ClubAuxiliaryWords: if (b.heap) put(db.raw_club_auxiliary_words); break;
case ::bmh::layout::ForeignClubStrength: put(db.raw_foreign_club_strength); break;
case ::bmh::layout::Career_Put_ExecutableField3: put(db.raw_league_auxiliary_bytes); break;
case ::bmh::layout::RefereeProperties: put(db.raw_referee_properties); break;
case ::bmh::layout::ClubKitSelectors: put(db.raw_club_kit_selectors); break;
case ::bmh::layout::ClubShortNameOffsets: put(db.raw_club_short_name_offsets); break;
case ::bmh::layout::ClubSeasonRecords: if (!b.heap) data[0] = 1; break; // the pointer: records allocated
case ::bmh::layout::NextDeskManager:
for (size_t m = 0; m < 4; m++) data[m * 2] = uint8_t(m), data[m * 2 + 1] = 0;
break;
case ::bmh::layout::ManagerAutomation:
for (size_t m = 0; m < 4; m++) data[m * 5] = 1;
break;
case ::bmh::layout::ActiveManager: data[0] = 4; break;
case ::bmh::layout::Desktops:
for (size_t k = 0; k < 5; k++) put(m3_men, k * 0x360);
break;
case ::bmh::layout::Formations:
put(m3_dat);
for (size_t k = 1; k < 4; k++)
for (size_t i = 0; i < 0x160; i++) data[k * 0x160 + i] = data[i];
break;
case ::bmh::layout::SquadSlots:
if (b.heap) {
const std::vector<uint16_t> slots = modern::startup_squad_list(db);
for (size_t i = 0; i < slots.size() && 2 * i + 1 < data.size(); i++)
data[2 * i] = uint8_t(slots[i]), data[2 * i + 1] = uint8_t(slots[i] >> 8);
}
break;
case ::bmh::layout::PlayerConditionTechniqueForm:
case ::bmh::layout::PlayerSkillWords:
case ::bmh::layout::PlayerIdentityWords:
if (b.heap) {
for (size_t i = 0; i < db.players.size() && 4 * i + 3 < data.size(); i++) {
uint32_t w = b.address == ::bmh::layout::PlayerConditionTechniqueForm ? db.players[i].w35c : b.address == ::bmh::layout::PlayerSkillWords ? db.players[i].w368 : db.players[i].w364;
if (b.address == ::bmh::layout::PlayerSkillWords && i + 32 >= db.players.size())
w = (w & 0x07ffffffu) | uint32_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 - uint32_t(db.players.size() - i))) << 27;
for (int k = 0; k < 4; k++) data[4 * i + size_t(k)] = uint8_t(w >> (8 * k));
}
}
break;
default: break;
}
stream.insert(stream.end(), data.begin(), data.end());
}
for (const Bytes& pool : db.pools) {
stream.push_back(uint8_t(pool.size()));
stream.push_back(uint8_t(pool.size() >> 8));
stream.insert(stream.end(), pool.begin(), pool.end());
}
const SaveState save(stream, counts);
ModernState g = GameState::from_save(save, counts);
modern::competition_pointers(g.memory, exe); // CompetitionPointers
return g;
}
} // namespace bmh::modern
#include "modern/game/matchday.hpp"
#include "modern/game/season.hpp"
#include "modern/game/week.hpp"
namespace bmh::modern {
void new_career_markets_and_moods(ModernState& g, GameRandom& game, WatcomRandom& rand) {
StaticMemory& mem = g.memory;
for (uint32_t k = 0; k < 12; k++) {
if (k < 6) mem.set32(::bmh::layout::FundBlock + k * 0x1c, (1u << k) * 100000);
const size_t s = size_t(k) * 0x5c;
const uint32_t value = k * 2000 + 10000;
for (int i = 0; i < 4; i++) g.stocks.at(s + size_t(i)) = uint8_t(value >> (8 * i));
g.stocks.at(s + 0x4e) = uint8_t(k * 20 + 100), g.stocks.at(s + 0x4f) = uint8_t((k * 20 + 100) >> 8);
}
modern::stir_random(game, rand);
const int first = game.range(0, 1);
if (g.texts) {
auto name = [&](int record, uint32_t pointer) {
const std::string& t = (*g.texts)[(pointer - ::bmh::layout::TextPointerTable) / 4];
const size_t at = size_t(record) * 0xb0c + 0xa8;
for (size_t i = 0; i <= t.size(); i++) g.manager_records.at(at + i) = i < t.size() ? uint8_t(t[i]) : 0;
};
name(first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField);
name(1 - first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField2);
name(2, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField3);
name(3, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField4);
}
for (int day = 0; day < 30; day++) modern::stock_market(g, game);
for (uint32_t i = 0; i < 900; i++) mem.set8(::bmh::layout::Titles + i, 0xff);
for (uint32_t i = 0; i < 4; i++) mem.set8(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2 + i, uint8_t(1 << i));
for (uint32_t i = 0; i < 0x2c; i++) mem.set16(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField + i * 0x58, 0xfff);
modern::reset_club_moods(g, game, rand, true);
}
bool new_career_players(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
for (size_t slot = 0; slot < transfer_list_slot(); slot++) {
const int id = g.squad_slots.at(slot) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
p.w364 |= uint32_t(rand.range(4, 0x10)) << 21;
p.w368 = (p.w368 & 0xffffc000u) + uint32_t(rand.range(0, 0x3fff));
}
for (int slot = 3096; slot < 3096 + 0x36; slot++)
if (!modern::release_player(g, slot, game, rand, report)) return false;
return !report.unsupported;
}
bool new_career_before_dialog(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
// CareerFirstSteps2 clears all four pending offers immediately before calling
// InitializeCareer. Raw executable BSS starts at zero, which is a valid offer
// for manager/player zero in ResolvePendingOffer, rather than the empty sentinel.
for (uint32_t offer = 0; offer < 4; ++offer)
g.memory.set32(::bmh::layout::OfferSlots + offer * 4, 0xffffffff);
modern::new_career_markets_and_moods(g, game, rand);
return modern::new_career_players(g, game, rand, report);
}
} // namespace bmh::modern
#include "game/lineup.hpp"
#include "modern/game/national.hpp"
#include "modern/game/weekly.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xb0c;
uint16_t team_of(const ModernState& g, int m) {
const size_t at = size_t(m) * kRecord + 0x290;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
// FindManagerForClub: a club of a human manager (manager slot 4 counts when manager 0 coaches
// the national team).
bool human_club(const ModernState& g, int team) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
for (int m = 0; m < managers; m++)
if (team_of(g, m) == uint16_t(team)) return true;
return team_of(g, 0) == no_team() && team_of(g, 4) == uint16_t(team);
}
// OpenBMH deviates from the original: skips reserved calendar positions when assigning a joining manager to a club.
// The supported rule profile patch reserves club places whose calendar word (CompetitionCalendar, read with the
// club id as index) has the bits 0x4001.
bool reserved_place(const ModernState& g, int team) {
return team >= 0 && (g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(team) * 2) & 0x4001) == 0x4001;
}
// EuropeanClub: only the active prefixes of the three European lists count.
bool european_club(const ModernState& g, int team) {
for (const auto& entry : {std::pair<uint32_t, uint32_t>{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField},
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}})
for (uint32_t i = 0; i < g.memory.u8(entry.second); ++i)
if (g.memory.u16(entry.first + i * 2) == uint16_t(team)) return true;
return false;
}
// RemoveJoinTransfers: remove a joining club's sale entries and parallel bid fields.
void remove_join_transfers(ModernState& g, int team) {
StaticMemory& mem = g.memory;
for (uint32_t row = 0; row < 44; ++row) {
const uint32_t base = ::bmh::layout::EditorList + row * 0x58;
if ((mem.u16(base + 8) & 0x7fff) == uint16_t(team)) {
g.squad_slots.at(transfer_list_slot() + row) = kEmptySlot;
continue;
}
int bid = 0;
while (bid < 4 && mem.u16(base + uint32_t(bid) * 2) != uint16_t(team)) ++bid;
if (bid == 4) continue;
const uint32_t found = uint32_t(bid);
if (bid != 3) {
for (uint32_t k = found; k < 3; ++k) {
mem.set16(base + k * 2, mem.u16(base + (k + 1) * 2));
mem.set32(base + 0xc + k * 4, mem.u32(base + 0xc + (k + 1) * 4));
mem.set32(base + 0x1c + k * 4, mem.u32(base + 0x1c + (k + 1) * 4));
mem.set8(base + 0x34 + k, mem.u8(base + 0x34 + k + 1));
for (uint32_t b = 0; b < 7; ++b)
mem.set8(base + 0x38 + k * 7 + b, mem.u8(base + 0x38 + (k + 1) * 7 + b));
}
++bid; // The Source terminator is found + 1, not always the last bid.
}
mem.set16(base + uint32_t(bid) * 2, 0xffff);
if (row > 39) {
g.squad_slots.at(transfer_list_slot() + row + 40) = kEmptySlot;
mem.set32(::bmh::layout::Career_RemoveJoinTransfers_RuntimeField + row * 4, 0xffffffff);
}
}
}
// ConfirmManager: clean loans only after the final club swap/remapping.
bool remove_join_loans(ModernState& g, int team, MinuteReport& report) {
StaticMemory& mem = g.memory;
for (uint32_t i = 0; i < 200; ++i) {
const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + i * 4, loan = mem.u32(at);
if (loan == 0) continue;
const int owner = int((loan >> 12) & 0x3ff), borrower = int((loan >> 22) & 0x3ff);
if (owner == team) mem.set32(at, 0);
else if (borrower == team) {
mem.set32(at, 0);
if (human_club(g, owner)) {
uint32_t k = 0;
while (k < 12 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2) != (loan & 0xfff)) ++k;
if (k == 12) {
report.fail("joining-manager loan has no human owner entry (PresentLoanReturn(0x3c))");
return false;
}
mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2, kEmptySlot);
}
}
}
return true;
}
void put32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i));
}
// CareerAddManager2(team, mode): condition and technique of every player of a league club around
// a level of its league (mode 0 random W(min, max), 1 min + 3, 2 the middle + 1, 3 max - 3).
void set_club_strength(ModernState& g, int team, int mode, WatcomRandom& rand) {
if (team >= league_clubs()) return;
const int league = team_league(team);
const int lo = kLeagueStrength[league][0], hi = kLeagueStrength[league][1];
int level = mode;
switch (mode) {
case 0: level = rand.range(lo, hi); break;
case 1: level = lo + 3; break;
case 2: level = (hi + lo) / 2 + 1; break;
case 3: level = hi - 3; break;
default: break;
}
level = int16_t(level);
const SquadRange r = squad_range(team);
for (size_t s = r.first; s < r.first + r.count; s++) {
const int id = g.squad_slots.at(s) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
const int condition = std::clamp(rand.range(level - 6, level + 6), 0, 99); // ClampInteger
const int technique = std::clamp(rand.range(level - 6, level + 6), 0, 99);
p.w35c = (p.w35c & 0xffe0007fu) | uint32_t(condition) << 14 | uint32_t(technique) << 7;
}
}
// CareerAddManager3(record, league, mode): the stadium of a human club - eight stand blocks
// (Career_BuildStadium_RuntimeField4[league] thousand places each), the facilities of the league
// (Career_BuildStadium_RuntimeField, levels W(Career_BuildStadium_RuntimeField2, Career_BuildStadium_RuntimeField3) << 2) and eight block values W(100, 140).
// Mode 1 (CareerDuration) builds everything one step better.
void build_stadium(ModernState& g, const LeImage& exe, int m, int league, int mode, WatcomRandom& rand) {
uint8_t* rec = &g.manager_records.at(size_t(m) * kRecord);
for (int k = 0; k < 8; k++) {
rec[0x4c + k] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 + uint32_t(league)) + (mode == 1 ? 1 : 0));
rec[0x5c] = uint8_t(rec[0x5c] + rec[0x4c + k]);
}
for (int i = 0; i < 0x16; i++) {
const uint8_t level = mode == 1 ? 3 : exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(i + league * 0x17));
if (i == 0x10 || i == 0x11 || level == 0) continue;
if (i == 0) {
rec[0] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0));
} else {
rec[i] = uint8_t(rand.range(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField2 + uint32_t(i * 5)), exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField3 + uint32_t(i * 5))) << 2);
}
if (i > 0xd) rec[i + 0x2e] = uint8_t(level + (mode == 1 ? 1 : 0));
}
rec[0x3f] = rec[0x3e] = uint8_t((mode == 1) + 1);
for (int k = 0x16; k < 0x1e; k++) rec[k] = uint8_t(rand.range(100, 0x8c));
}
} // namespace
// StartingSponsors: in mode GameMode == 1 or in the one-year mode before
// the first season day, the three sponsor contracts start at the value for the
// selected league and difficulty. Use ModernState.date: memory CalendarDay can be
// stale in the port after a new-career/season transition.
void starting_sponsors(ModernState& g, int m) {
const StaticMemory& mem = g.memory;
if (!(mem.u8(::bmh::layout::GameMode) == 1 || (mem.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0))) return;
const size_t rec = size_t(m) * kRecord;
int league = g.manager_records.at(rec + 0x210);
if (league > 2) league--;
const int v = (((league * -20 + 80) * 60000 + 1000000) / 12 * (mem.u8(::bmh::layout::Difficulty) * -5 + 0xaa)) / 3000000 * 10000;
for (size_t o : {size_t(0xae8), size_t(0xadc), size_t(0xa34)}) put32(g.manager_records, rec + o, uint32_t(v));
for (size_t o : {size_t(0xaed), size_t(0xae1), size_t(0xa39)}) g.manager_records.at(rec + o) = 1;
}
void career_managers_begin(ModernState& g, bool adding) {
g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
const size_t rec = 4 * kRecord;
put32(g.manager_records, rec + 0x314, 1000000);
put32(g.manager_records, rec + 0x324, 1000000);
for (size_t i = 0; i < 0xd; i++) g.manager_records.at(rec + 0xc5 + i) = 2;
if (adding) {
const size_t count = g.memory.u8(::bmh::layout::ManagerCount);
g.manager_teams.resize(count);
for (size_t m = 0; m < count; ++m) g.manager_teams[m] = team_of(g, int(m));
} else g.manager_teams.assign(g.memory.u8(::bmh::layout::ManagerCount), 0);
// ConfirmManager(0) posts PostSeasonNotice(0xff) immediately after the accepted
// new-career options dialog. The join path starts at a nonzero manager slot and
// must not repeat these three introduction messages.
if (adding || g.manager_teams.empty() || g.manager_teams.size() > 4) return;
post_text(g, -1, 1001); // CareerRuntimeField3
post_text(g, -1, 1002); // CareerRuntimeField4
post_text(g, -1, 1003); // CareerRuntimeField5
}
bool career_add_manager(ModernState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding,
GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
// Reject malformed requests before changing records or consuming either RNG.
if (!g.memory.has(::bmh::layout::ManagerCount) || m < 0 || m >= 4 ||
g.memory.u8(::bmh::layout::ManagerCount) > 4 || m >= g.memory.u8(::bmh::layout::ManagerCount) ||
size_t(m) >= g.manager_teams.size() || g.manager_records.size() < 5 * kRecord ||
choice.team < 0 || choice.team >= first_foreign_cup() || size_t(choice.team) >= g.club_ids.size() ||
choice.league < 0 || choice.league > 4 || choice.strength < 0 || choice.strength > 2 ||
choice.portrait < 0 || choice.portrait > 11 || choice.name.size() > 24 ||
g.tactics.size() < size_t(m + 1) * 0x840 ||
g.manager_ratings.size() < size_t(m + 1) * 0x3c ||
g.manager_results.size() < g.manager_teams.size() * 0x690 ||
g.squad_slots.size() < total_squad_slots() || g.club_ids.size() < size_t(first_foreign_cup()) ||
g.team_morale.size() < size_t(first_foreign_cup()) || g.team_flags.size() < size_t(first_foreign_cup()) ||
g.club_heap_bc.size() < size_t(first_foreign_cup()) * 2 || g.club_heap_78.size() < size_t(first_foreign_cup()) * 2 ||
g.club_heap_b8.size() < size_t(first_foreign_cup()) || g.position_history.size() < size_t(league_clubs()) * 0x1a ||
(!g.club_table.empty() && g.club_table.size() < size_t(first_foreign_cup()) * 0x4a) ||
g.player_bonus.size() < g.players.size() || g.player_cards.size() < g.players.size() ||
!exe.contains(::bmh::layout::Career_CareerAddManager_ExecutableField) || !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField3 + 0x15 * 5) ||
!exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField + 4 * 0x17 + 0x15)) {
report.fail("invalid career manager choice or slot");
return false;
}
for (int other = 0; other < m; ++other)
if (g.manager_teams[size_t(other)] == choice.team) {
report.fail("career manager club is already managed");
return false;
}
for (size_t slot = 0; slot < transfer_list_slot(); ++slot) {
const uint16_t player = g.squad_slots[slot] & 0x0fff;
if (player != kEmptySlot && size_t(player) >= g.players.size()) {
report.fail("invalid career manager squad player");
return false;
}
}
StaticMemory& mem = g.memory;
const size_t rec = size_t(m) * kRecord;
std::vector<uint8_t>& r = g.manager_records;
for (size_t i = 0; i < 0x12; i++) r.at(rec + 0x1f6 + i) = 1;
for (size_t i = 0; i < 10; i++) r.at(rec + 0x8b6 + i) = 0xff;
r.at(rec + 0x1f6) = 0x40;
// the values of the dialog (ManagerScreen2)
for (size_t i = 0; i < 0x19; i++) r.at(rec + 0xa8 + i) = i < choice.name.size() ? uint8_t(choice.name[i]) : 0;
r.at(rec + 0x290) = uint8_t(choice.team), r.at(rec + 0x291) = uint8_t(choice.team >> 8);
r.at(rec + 0x221) = uint8_t(choice.portrait);
r.at(rec + 0x210) = uint8_t(choice.league);
g.manager_teams.at(size_t(m)) = int16_t(choice.team);
int place = 1 + m; // the club's place in the first league
if (!adding && mem.u8(::bmh::layout::CareerDuration) <= 1) mem.set8(::bmh::layout::Career_CareerAddManager_RuntimeField, 0);
else place = m + 9;
while (reserved_place(g, place) || human_club(g, place) || (adding && european_club(g, place))) place++; // CareerAddManager4
int league = r.at(rec + 0x210); // local_18
const int team = int16_t(team_of(g, m));
if (adding) remove_join_transfers(g, team);
if (team_league(team) != league) {
int other = place;
if (league != 0) {
const int first = league_first_team(league), last = first + 12; // CareerRuntimeField6 (league * 18 in DE)
do other = int16_t(game.range(first, last));
while (human_club(g, other)); // ReservedPlace2
// ReservedPlace: the next of 13 places that is neither reserved nor human
int c = other;
for (int k = 0; k < 13; k++) {
if (!reserved_place(g, c) && !human_club(g, c)) {
other = c;
break;
}
if (++c > last) c -= 13;
}
}
if (adding) remove_join_transfers(g, other);
modern::clubs_change_places(g, team, other);
set_club_strength(g, team, 0, rand);
place = 0;
}
if (league == 0 && place != 0) {
if (adding) remove_join_transfers(g, place);
modern::clubs_change_places(g, int16_t(team_of(g, m)), place);
}
set_club_strength(g, int16_t(team_of(g, m)), choice.strength + 1, rand);
const int club = int16_t(team_of(g, m));
if (adding && !remove_join_loans(g, club, report)) return false;
g.team_morale.at(size_t(club)) |= 0x80;
r.at(rec + 0x26f) = 0x32;
if (league > 2) league--;
modern::starting_sponsors(g, m);
r.at(rec + 0x26e) = uint8_t(std::max(20 - 2 * league, 14));
build_stadium(g, exe, m, league, mem.u8(::bmh::layout::CareerDuration), rand);
if (league > 2) league = 2;
for (uint32_t i = 0; i < 3; i++) {
const uint32_t base = ::bmh::layout::Career_CareerAddManager_RuntimeField2 + uint32_t(m) * 0x24;
mem.set8(base + i, uint8_t(0x52 - league * 15));
mem.set8(base + 3 + i, 6);
mem.set8(base + 6 + i, uint8_t(league));
mem.set32(base + 0x18 + i * 4, 5000);
}
const SquadRange squad = squad_range(club);
r.at(rec + 0x288) = 0x16;
for (size_t i = 0; i < 0xd; i++) r.at(rec + 0xc5 + i) = 2;
for (size_t i = 0; i < 6; i++) r.at(rec + 0x8aa + 2 * i) = 0x26, r.at(rec + 0x8ab + 2 * i) = 0x02;
for (size_t i = 0; i < 0x3c; i++) g.manager_ratings.at(size_t(m) * 0x3c + i) = 100;
const int players = adding ? modern::squad_count(g, club, 2) : 20;
for (int i = 0; i < players; i++) {
const size_t slot = squad.first + size_t(i);
Player& p = g.players.at(size_t(g.squad_slots.at(slot) & 0x0fff));
p.w364 &= ~(0x1fu << 21);
p.w364 |= uint32_t(rand.range(4, 9)) << 21;
modern::new_board_entry(g, m, i, int(slot), rand);
g.tactics.at(size_t(m) * 0x840 + size_t(i) * 0x58 + 0xd) = 100;
}
// Deviation from the original: a new career fills exactly 20 board rows (local_28 = 0x14),
// but new_career_players runs before the dialog and may already have moved a free agent
// into the chosen club (transfer_bid, "straight to the club"). That 21st player had no
// board row - no salary, and team_rating divides by his base pay (the original crashes
// once he plays). The remaining occupied rows get their entry the same way; with the
// usual 20 players nothing changes and no random number is drawn.
if (!adding)
for (size_t i = 20; i < squad.count && i < 24; i++) {
const size_t slot = squad.first + i;
const int id = g.squad_slots.at(slot) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
p.w364 &= ~(0x1fu << 21);
p.w364 |= uint32_t(rand.range(4, 9)) << 21;
modern::new_board_entry(g, m, int(i), int(slot), rand);
g.tactics.at(size_t(m) * 0x840 + i * 0x58 + 0xd) = 100;
}
for (size_t i = 0; i < 0x690; i++) g.manager_results.at(size_t(m) * 0x690 + i) = 0xff;
const uint8_t level = mem.u8(::bmh::layout::Difficulty);
const uint32_t money = level == 0 ? 50000000u : 4000000u - level * 200000u;
put32(r, rec + 0x314, money);
put32(r, rec + 0x324, money);
r.at(rec + 0x219) = r.at(rec + 0x218) = 0xf;
put32(r, rec + 0x31c, uint32_t(400000 - league * 100000));
put32(r, rec + 0x310, 1);
auto_lineup(g, club, 100);
return !report.unsupported;
}
void career_managers_end(ModernState& g, bool adding) {
g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 0);
if (!adding)
for (uint32_t i = 0; i < 12; i++) g.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xfff);
}
} // namespace bmh::modern
namespace bmh::modern {
// The English counterpart of CompetitionPointers: the Football Limited GermanRoundTable. The cup table
// (translated to CupTable, launch/fltd.hpp) is the English one; its entries 0-24 have the
// same roles as in German, so their arrays are the German ones (same sizes). Different:
// entry 0 (FA Cup qualifying stage) and the English-only competitions - entry 28 (FA Cup
// proper), 25-27 (League Cup) and 35 - which use memory blocks at their English addresses
// (english_competition_blocks); there are no indoor tournaments and no Masters.
namespace {
// English round-string pointer tables -> the German ones the engine knows (cup.cpp)
uint32_t german_round_table(uint32_t en) {
switch (en) {
case ::bmh::layout::Career_GermanRoundTable_ExecutableField2: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField; // 4 teams
case ::bmh::layout::Career_GermanRoundTable_ExecutableField3: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField2; // 6
case ::bmh::layout::Career_GermanRoundTable_ExecutableField: return ::bmh::layout::CareerSession_RuntimeError_ExecutableField2; // 20
case ::bmh::layout::Career_GermanRoundTable_ExecutableField4: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField3; // 12
default: return en;
}
}
void competition_pointers_english(StaticMemory& mem, const LeImage& exe) {
auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; };
modern::english_competition_blocks(mem);
for (uint32_t k = 1; k < 0xf; k++) {
uint32_t b = k;
if (k > 9) b -= 9;
if (k > 0xc) b -= 3;
mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc);
}
uint32_t k = 7;
for (uint32_t i = 0; i < 8; i += 2, k++) {
if (k == 10) k = 0xc;
mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2);
}
const std::pair<uint32_t, uint32_t> single[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13},
{::bmh::layout::CupTable, kEnglishFaQualifyingField}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, kEnglishFaResults},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}};
for (const auto& [at, to] : single) mem.set_pointer(at, to);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10);
for (uint32_t i = 0; i < 4; i++) {
const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i));
mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30);
mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc);
const std::pair<uint32_t, uint32_t> more[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays},
// the English-only cup entry table (entries 25-28 and 35)
{entry(28), ::bmh::layout::EnglishFaCupProperField}, {entry(28) + 0xc, ::bmh::layout::EnglishFaCupStageResults}, // FA Cup proper
{entry(25), ::bmh::layout::EnglishLeagueCupFirstRoundField}, {entry(25) + 0xc, ::bmh::layout::EnglishLeagueCupFirstRoundResults}, // League Cup
{entry(26), ::bmh::layout::EnglishLeagueCupQuarterFinalField}, {entry(26) + 0xc, ::bmh::layout::EnglishLeagueCupQuarterFinalResults}, {entry(26) + 0x10, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults},
{entry(27), ::bmh::layout::EnglishLeagueCupSemiFinalField}, {entry(27) + 0xc, ::bmh::layout::EnglishLeagueCupSemiFinalResults},
{entry(35) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField}, {entry(35), ::bmh::layout::EnglishAdditionalCupField}, {entry(35) + 0xc, ::bmh::layout::EnglishAdditionalCupResults}};
for (const auto& [at, to] : more) mem.set_pointer(at, to);
// round tables the English table holds itself (static pointers to English strings)
for (uint32_t e = 0; e < 0x24; e++) {
const uint32_t at = entry(e) + 8;
const uint32_t p = mem.u32(at);
if (p >= ::bmh::layout::EnDataStart && p < ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField) mem.set_pointer(at, german_round_table(p));
}
}
} // namespace
void english_competition_blocks(StaticMemory& mem) {
for (const auto& [at, size] : kEnglishCompetitionBlocks)
if (!mem.has(at)) mem.add_block(at, size);
}
void competition_pointers(StaticMemory& mem, const LeImage& exe) {
if (kEnglishCompetitions) {
competition_pointers_english(mem, exe);
return;
}
auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; };
// the cups of the leagues 1..14 (entries 1..14)
for (uint32_t k = 1; k < 0xf; k++) {
uint32_t b = k;
if (k > 9) b -= 9;
if (k > 0xc) b -= 3;
mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc);
}
// entries 7, 8, 9, 12 (Career_CompetitionPointersEnglish_RuntimeField10 pairs)
uint32_t k = 7;
for (uint32_t i = 0; i < 8; i += 2, k++) {
if (k == 10) k = 0xc;
mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2);
}
const std::pair<uint32_t, uint32_t> single[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, {::bmh::layout::CupTable, ::bmh::layout::Field}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, ::bmh::layout::Career_CompetitionPointers_ExecutableField},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}};
for (const auto& [at, to] : single) mem.set_pointer(at, to);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10);
for (uint32_t i = 0; i < 4; i++) {
const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i));
mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30);
mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc);
const std::pair<uint32_t, uint32_t> more[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}};
for (const auto& [at, to] : more) mem.set_pointer(at, to);
// the indoor tournaments and the Masters (entries 25..29)
for (uint32_t i = 0; i < 5; i++) {
const uint32_t e = entry(0x19 + i);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(e + 0xc, ::bmh::layout::MatchdayGroupWorkspace + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField4 + i)) * 2);
mem.set_pointer(e, ::bmh::layout::Teams + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField5 + i)) * 2);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField, ::bmh::layout::Teams);
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField3, ::bmh::layout::MatchdayGroupWorkspace);
}
} // namespace bmh::modern
+149
View File
@@ -0,0 +1,149 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
#include "game/career.hpp"
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// The start of a new career (BMH.exe V2.24 + supported rule profile patch).
//
// The original starts every career at program start: CareerFirstSteps2 loads the data files
// (TEXTD.BLK, M3.MEN, M3.DAT, M3D.MAN), gives every player new values and then calls
// InitializeCareer, which sets up shares, funds, club moods, ages and skills, shows the
// options and manager dialogs (SetupScreen2) inside ConfirmManager and finally prepares the
// first season. Loading a savegame from the options screen replaces all of that.
//
// The game generator starts at 0 (CareerSession_Save_RuntimeField is not initialised), the Watcom generator
// at the clock value of srand() - recordings capture it.
#include <cstdint>
#include <utility>
#include <string>
#include "formats/m3d.hpp"
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// GeneratePlayer with the supported rule profile patch GeneratePlayer2: new values for player `id` around
// `level` (low 12 bits of `level_flags`; 0x1000 = leave the age at 0, 0x2000 = exactly
// the level instead of +-10 %):
// - w35c bits 21-26: G(0, 7) << 3 | G(0, 7) for field players, 0x18 for goalkeepers
// (two game draws, high part first);
// - condition and technique G(level - level / 10, level + level / 10), each cut to
// 10..99; form G(35, 65); bits 27-31 cleared;
// - w368: skills W(0, 0x3fff), bits 18-23 (cards) cleared;
// - w364: age bits cleared, then (without 0x1000) G(2, 5) = 18..21 years.
void generate_player(ModernState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand);
// The part of CareerFirstSteps2 after loading M3D.MAN: the 54 players of the extra slots
// (CareerSession_DataDirectory_RuntimeField4 ..) get W(20 or 70, 90) as level (the first 22 from 20), then the players
// of every league club get the level of its place in the database order of its league,
// from the league's maximum (first club) down towards its minimum (LeagueStrengthRanges pairs,
// club counts LeagueSizes), keeping the age at 0 for InitializeCareer.
void startup_players(ModernState& g, GameRandom& game, WatcomRandom& rand);
// The squad list as CareerFirstSteps2 leaves it: all slots 0xfff, the database list read
// over them and its tail (from slot CareerRuntimeField + 40) moved up to slot CareerRuntimeField2
// (memmove; the four slots before keep their values).
std::vector<uint16_t> startup_squad_list(const Database& db);
} // namespace bmh::modern
namespace bmh::modern {
// The memory of the original after loading the data files in CareerFirstSteps2, as a ModernState
// (built like a savegame: every saved block from the program's data object - zero where
// it is uninitialised - with the data of M3.MEN, M3.DAT and M3D.MAN read over it):
// manager order 0..3, option byte 0 of each manager 1, active manager 4, M3.MEN five
// times (Desktops), the first 0x160 bytes of M3.DAT four times (the other three
// parts of the file are overwritten), the nationality of the last 32 players from
// CareerRuntimeField7. The player values are those of the database; startup_players follows.
ModernState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat);
// CompetitionPointers (part of startup_state): the pointers of the competition table CupTable
// (36 entries of 0x28 bytes: +0 the teams, +8 the rounds, +0xc the results) to the tables of
// the leagues, cups and tournaments.
void competition_pointers(StaticMemory& mem, const LeImage& exe);
// The memory of the English-only competitions (Football Limited, kEnglishCompetitions):
// blocks at their English addresses, which no German address uses. FA Cup results (67
// matches) and fields (68 clubs: the 20 Premier League clubs, the 48 of the qualifying
// stage, the proper rounds), the League Cup (44 clubs, three entries) and entry 35.
constexpr uint32_t kEnglishFaResults = ::bmh::layout::EnglishFaCupResults; // 0x86 bytes, entry 0 +0x0c
constexpr uint32_t kEnglishFaField = ::bmh::layout::EnglishFaCupField; // 68 clubs: 20 + kEnglishFaQualifyingField
constexpr uint32_t kEnglishFaQualifyingField = ::bmh::layout::EnglishFaCupQualifyingField; // the 48 of the qualifying stage (entry 0)
constexpr uint32_t kEnglishLeagueCupField = ::bmh::layout::EnglishLeagueCupField; // 44 clubs: 20 + 24 at layout field (entry 25)
constexpr std::pair<uint32_t, uint32_t> kEnglishCompetitionBlocks[] = {
{::bmh::layout::EnglishFaCupResults, 0x1ba}, // FA Cup: results EnglishFaCupResults, stage results EnglishFaCupStageResults, field EnglishFaCupField, proper EnglishFaCupProperField
{::bmh::layout::EnglishLeagueCupField, 0x136}, // League Cup: fields EnglishLeagueCupField/EnglishLeagueCupFirstRoundField/EnglishLeagueCupQuarterFinalField/EnglishLeagueCupSemiFinalField, results EnglishLeagueCupFirstRoundResults/EnglishLeagueCupQuarterFinalResults/EnglishLeagueCupSemiFinalResults/EnglishLeagueCupQuarterFinalOtherLegResults
{::bmh::layout::EnglishAdditionalCupResults, 0x48}, // entry 35: results EnglishAdditionalCupResults, field EnglishAdditionalCupField
};
void english_competition_blocks(StaticMemory& mem);
} // namespace bmh::modern
namespace bmh::modern {
// InitializeCareer up to the options dialog (SetupScreen2, called first in ConfirmManager(0)):
// - funds (price (1 << k) * 100 000) and shares (value k * 2000 + 10 000, price
// k * 20 + 100);
// - stir_random; G(0, 1) chooses which of the two computer manager names (Career_NewCareerMarketsAndMoods_ExecutableField /
// aeafc) the records 0 and 1 get, records 2 and 3 get Career_NewCareerMarketsAndMoods_ExecutableField3 / Career_NewCareerMarketsAndMoods_ExecutableField4 (needs
// g.texts; skipped without);
// - 30 days of share prices (stock_market);
// - Titles (900 bytes) 0xff, Career_NewCareerMarketsAndMoods_RuntimeField2 = 1, 2, 4, 8, the transfer list's 44
// entries empty (player 0xfff);
// - club moods (reset_club_moods, career mode);
// - every club player (squad slots 0 .. CareerRuntimeField) gets an age W(4, 16) and new
// skills W(0, 0x3fff);
// - the 54 extra players leave for the free agents (release_player, MonthChange).
// Returns false if a step is not supported (report).
bool new_career_before_dialog(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// Its two parts: up to the club moods, and the ages, skills and extra players.
void new_career_markets_and_moods(ModernState& g, GameRandom& game, WatcomRandom& rand);
bool new_career_players(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh::modern
namespace bmh::modern {
// A manager as confirmed in his dialog (ManagerScreen2; the UI's ManagerChoice): the dialog
// writes name (record +0xa8), club (+0x290), start league 0..4 (+0x210) and portrait
// (+0x221) into the record and returns the strength 0 (lower third) .. 2 (upper third).
// ConfirmManager before the first dialog: manager slot 4 (the national team's) gets the
// training plan 2 and 1 000 000 money.
void career_managers_begin(ModernState& g, bool adding = false);
// StartingSponsors initializes the three sponsor contracts for mode I, or for a
// one-year career before season day 0. The date check uses ModernState.date,
// because the serialized CalendarDay mirror can be stale during startup/reset.
void starting_sponsors(ModernState& g, int manager);
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// The body of ConfirmManager's loop for manager `m` (`adding` = a manager joins a running
// game, param_1 != 0): the record is prepared and the dialog's values entered, then
// - the club moves to its place: in a league other than the chosen start league it
// changes places with a club of that league (G(first, first + 12), supported rule profile ReservedPlace2
// / ReservedPlace skip clubs of humans and reserved places), which gets new values
// (CareerAddManager2(club, 0)); in the first league with a club place m + 1 (m + 9 when
// adding; supported rule profile CareerAddManager4 skips reserved and human places);
// - the club's players get condition and technique around the chosen strength
// (CareerAddManager2, W(level - 6, level + 6));
// - record values: morale flag, board patience, stadium (CareerAddManager3, StartingSponsors),
// training plan, ratings, money (4 000 000 - level * 200 000; 50 000 000 at level 0),
// credit line, the first 20 players (or the whole squad when adding) on the tactics
// board with a new age W(4, 9), and an automatic line-up.
// The optional file of CareerAddManager (bonus codes) is not read. Needs the program image
// for its tables (Career_BuildStadium_RuntimeField4, Career_BuildStadium_RuntimeField, Career_BuildStadium_RuntimeField2).
bool career_add_manager(ModernState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ConfirmManager after the loop: clear CareerSession_FormatError_RuntimeField6; only a new career empties the twelve
// human loan entries Career_CareerManagersEnd_RuntimeField. Joining preserves unrelated entries.
void career_managers_end(ModernState& g, bool adding);
} // namespace bmh::modern
+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/club_info.hpp"
#include <stdexcept>
namespace bmh::modern {
ClubInfoEntry prepare_club_info_entry(ModernState& g, int team) {
if (team < 0 || (team >= league_clubs() && team != no_team()))
throw std::invalid_argument("club info: team has no squad");
const SquadRange range = squad_range(team);
if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first)
throw std::invalid_argument("club info: truncated squad range");
size_t occupied = 0;
for (size_t row = 0; row < range.count; ++row) {
const int id = g.squad_slots[range.first + row] & 0x0fff;
if (id == 0x0fff) continue;
if (size_t(id) >= g.players.size())
throw std::invalid_argument("club info: invalid player ID");
++occupied;
}
// Allocate the owned pre-cleanup drawing rows before the first engine write.
ClubInfoEntry entry;
entry.displayed_slots.assign(g.squad_slots.begin() + range.first,
g.squad_slots.begin() + range.first + range.count);
// SquadCount(team,2) counts occupied IDs over the complete range. PrepareLineupEntry
// scans that count-sized prefix, even if the supplied map is sparse.
int last = int(occupied) - 1;
while (last >= 0 && (g.squad_slots[range.first + size_t(last)] & 0xc000) == 0) --last;
for (int row = 0; row <= last && row < 17; ++row) {
auto& slot = g.squad_slots[range.first + size_t(row)];
slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000));
}
entry.displayed_slots.assign(g.squad_slots.begin() + range.first,
g.squad_slots.begin() + range.first + range.count);
// PrepareClubInfoEntry clears bits13..15 for injured players over the entire range.
// Empty slots are a dummy ID in Original; preserve the sentinel explicitly.
for (size_t row = 0; row < range.count; ++row) {
auto& slot = g.squad_slots[range.first + row];
const int id = slot & 0x0fff;
if (id != 0x0fff && ((g.players[size_t(id)].w364 >> 16) & 0x1f) != 0)
slot &= 0x1fff;
}
return entry;
}
uint8_t set_club_info_category(ModernState& g, int team, int requested) {
constexpr size_t scan_count = 0x147;
if (team < 0 || size_t(team) >= g.team_morale.size() ||
g.team_morale.size() < scan_count || requested < 0 || requested > 2)
throw std::invalid_argument("club info: invalid category request or club table");
const size_t manager_count = g.memory.has(::bmh::layout::ManagerCount)
? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size();
if (manager_count > 4 || manager_count > g.manager_teams.size())
throw std::invalid_argument("club info: truncated manager teams");
const bool national = !g.manager_teams.empty() && g.manager_teams.front() == no_team();
constexpr size_t national_club = 4 * 0xb0c + 0x290;
if (national && g.manager_records.size() < national_club + 2)
throw std::invalid_argument("club info: truncated national manager record");
// FindManagerForClub matches the first ManagerCount teams, irrespective of manager name,
// then the fifth record when the first manager is the national coach.
const auto human = [&](int club) {
for (size_t m = 0; m < manager_count; ++m)
if (g.manager_teams[m] == club) return true;
return national && (g.manager_records[national_club] |
uint16_t(g.manager_records[national_club + 1]) << 8) == club;
};
uint8_t category = uint8_t(requested);
uint8_t seen = 0;
if (category == 2) {
for (size_t club = 0; club < scan_count; ++club) {
if ((g.team_morale[club] >> 6) != 2) continue;
++seen;
if (seen != 4 || category != 2) continue;
if (!human(team)) category = 0;
else {
// Source local10 stays0: every search restarts at the first club.
for (size_t other = 0; other < scan_count; ++other) {
if ((g.team_morale[other] >> 6) == 2 && !human(int(other))) {
g.team_morale[other] = uint8_t((g.team_morale[other] & 0x3f) | 0x40);
--seen;
break;
}
}
}
}
}
g.team_morale[size_t(team)] = uint8_t((g.team_morale[size_t(team)] & 0x3f) | (category << 6));
return category;
}
}
+14
View File
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/club_info.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// ClubInfoFromGame -> LineupScreen(..., param11=1): PrepareLineupEntry before
// drawing, PrepareClubInfoEntry after drawing. No player selection or RNG.
// Applies to computer and human domestic squads and the national squad.
// Invalid team/range/player IDs throw before any mutation.
ClubInfoEntry prepare_club_info_entry(ModernState& g, int team);
// ClubInfoFromGame numeric icon -> SetClubInfoCategory. Returns the applied raw
// category (0..2); may demote another computer club's category2 to1.
uint8_t set_club_info_category(ModernState& g, int team, int requested);
}
+221
View File
@@ -0,0 +1,221 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/club_player_detail.hpp"
#include <algorithm>
#include <stdexcept>
#include "modern/game/matchday.hpp"
#include "modern/game/month.hpp"
#include "modern/game/national.hpp"
#include "game/lineup.hpp"
#include "modern/game/weekly.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xb0c, kBoard = 0x840, kBoardRow = 0x58;
uint16_t record_word(const ModernState& g, size_t manager, size_t offset) {
const size_t at = manager * kRecord + offset;
if (at + 2 > g.manager_records.size()) throw std::invalid_argument("player detail: truncated manager record");
return uint16_t(g.manager_records[at] | uint16_t(g.manager_records[at + 1]) << 8);
}
int source_manager(const ModernState& g, int club) {
const size_t count = g.memory.has(::bmh::layout::ManagerCount) ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size();
if (count > 4 || count > g.manager_teams.size()) throw std::invalid_argument("player detail: invalid manager count");
for (size_t m = 0; m < count; ++m) if (g.manager_teams[m] == club) return int(m);
if (count && g.manager_teams[0] == no_team() && record_word(g, 4, 0x290) == club) return 4;
return -1;
}
int club_of_slot(int slot) {
if (slot < 0) return -1;
if (slot < 90 * 24) return slot / 24;
if (slot < 90 * 24 + 48 * 16) return (slot - 90 * 8) / 16;
if (slot >= pool_end_slot() && slot < pool_end_slot() + 24) return no_team();
return -1;
}
std::array<uint8_t, kBoardRow> board_copy(const ModernState& g, int manager, int row) {
const size_t at = size_t(manager) * kBoard + size_t(row) * kBoardRow;
if (at + kBoardRow > g.tactics.size()) throw std::invalid_argument("player detail: truncated manager board");
std::array<uint8_t, kBoardRow> out{};
std::copy_n(g.tactics.begin() + static_cast<std::ptrdiff_t>(at), out.size(), out.begin());
return out;
}
} // namespace
ClubPlayerDetailContext club_player_detail_context(const ModernState& g, const ClubPlayerDetailSelection& s) {
if ((s.origin != ClubPlayerDetailOrigin::squad && s.origin != ClubPlayerDetailOrigin::market_pool) ||
s.player_id < 0 || size_t(s.player_id) >= g.players.size() ||
size_t(s.player_id) >= g.player_cards.size() || size_t(s.player_id) >= g.player_bonus.size())
throw std::invalid_argument("player detail: invalid player identity");
ClubPlayerDetailContext out;
out.selection = s;
out.active_manager = g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0;
if (out.active_manager < 0 || size_t(out.active_manager) >= g.manager_teams.size())
throw std::invalid_argument("player detail: invalid active manager");
if (s.origin == ClubPlayerDetailOrigin::market_pool) {
if (s.runtime_team != -1 || s.physical_row != -1 || s.human_loan_index != -1 ||
s.market_pool_slot < int(transfer_list_slot()) ||
s.market_pool_slot >= int(transfer_list_slot()) + kClubPlayerDetailMarketPoolCount ||
s.rendered_row < 0 || s.rendered_row >= kClubPlayerDetailMarketPoolCount ||
size_t(s.market_pool_slot) >= g.squad_slots.size())
throw std::invalid_argument("player detail: invalid transfer-market slot");
out.source_slot = s.market_pool_slot;
out.displayed_slot = g.squad_slots[size_t(out.source_slot)];
if (out.displayed_slot == kEmptySlot || (out.displayed_slot & 0x0fff) != s.player_id)
throw std::invalid_argument("player detail: stale transfer-market identity");
out.market_pool = true;
out.source_manager = -1;
out.primary_club = -1;
} else {
if (s.rendered_row < 0 || s.rendered_row >= 24 || s.runtime_team < 0 ||
(s.runtime_team >= league_clubs() && s.runtime_team != no_team()))
throw std::invalid_argument("player detail: invalid runtime club");
const auto range = squad_range(s.runtime_team);
if (range.first + range.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated squad");
out.source_manager = source_manager(g, s.runtime_team);
out.primary_club = s.runtime_team;
}
if (s.origin == ClubPlayerDetailOrigin::market_pool) {
// The validated pool identity is already loaded. National resolution
// below may select a real squad copy; offers never imply a board.
} else if (s.human_loan_index >= 0) {
const auto range = squad_range(s.runtime_team);
if (s.human_loan_index >= 12 || s.physical_row != -1 || s.runtime_team == no_team() || out.source_manager < 0)
throw std::invalid_argument("player detail: invalid human loan row");
const uint32_t loan = uint32_t(s.human_loan_index);
const uint32_t player_at = ::bmh::layout::Career_CareerManagersEnd_RuntimeField + loan * 2, owner_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField2 + loan, board_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField + loan * kBoardRow;
if (!g.memory.has(player_at + 1) || !g.memory.has(owner_at) || !g.memory.has(board_at + kBoardRow - 1) ||
g.memory.u16(player_at) != s.player_id || g.memory.u8(owner_at) != out.source_manager)
throw std::invalid_argument("player detail: stale human loan identity");
out.human_loan = true;
out.source_slot = int(range.first) + s.rendered_row;
out.displayed_slot = uint16_t(s.player_id);
out.board.emplace();
for (size_t i = 0; i < kBoardRow; ++i) (*out.board)[i] = g.memory.u8(board_at + uint32_t(i));
} else {
const auto range = squad_range(s.runtime_team);
if (s.human_loan_index != -1 || s.physical_row < 0 || size_t(s.physical_row) >= range.count)
throw std::invalid_argument("player detail: invalid physical row");
out.source_slot = int(range.first) + s.physical_row;
out.displayed_slot = g.squad_slots[size_t(out.source_slot)];
if ((out.displayed_slot & 0x0fff) != s.player_id) throw std::invalid_argument("player detail: stale physical identity");
}
if (!out.human_loan) {
if (g.manager_teams[size_t(out.active_manager)] == no_team()) {
const auto national = squad_range(no_team());
if (national.first + national.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated national squad");
bool selected = false;
for (size_t row = 0; row < national.count; ++row)
if ((g.squad_slots[national.first + row] & 0x0fff) == s.player_id) selected = true;
out.national_mode = selected ? 2 : 1;
// ClubPlayerDetailFromGame remaps BOTH modes to the first matching slot below
// LargeSquadClubCount, including pool slots, before resolving club/owner/board.
size_t slot = 0;
while (slot < national.first && (g.squad_slots[slot] & 0x0fff) != s.player_id) ++slot;
if (slot == national.first) throw std::invalid_argument("player detail: national player has no source slot before national squad");
out.source_slot = int(slot);
out.primary_club = club_of_slot(out.source_slot);
out.secondary_club = selected ? no_team() : -1;
out.displayed_slot = g.squad_slots[slot];
out.source_manager = out.primary_club < 0 ? -1 : source_manager(g, out.primary_club);
}
if (out.national_mode != 0 && out.primary_club == int(record_word(g, 4, 0x290)) && g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3)) {
const uint8_t owner = g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3); // literal SquadRange override
out.source_manager = owner == 0xff ? -1 : owner;
}
if (out.source_manager >= 0) {
const auto owner_range = squad_range(out.primary_club);
const int row = out.source_slot - int(owner_range.first);
if (row < 0 || size_t(row) >= owner_range.count) throw std::invalid_argument("player detail: board row outside owner squad");
out.board = board_copy(g, out.source_manager, row);
}
}
for (int loan = 0; loan < 200; ++loan) {
const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan) * 4;
if (!g.memory.has(at + 3)) continue;
const uint32_t value = g.memory.u32(at);
if (value == 0 || (value & 0x0fff) != uint32_t(s.player_id)) continue;
out.loan_record = loan;
out.loan_duration = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) ? g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) : 0;
if (out.human_loan || out.national_mode == 0) {
out.primary_club = int((value >> 12) & 0x3ff);
out.secondary_club = int((value >> 22) & 0x3ff);
}
break;
}
if (out.human_loan && out.loan_record < 0) throw std::invalid_argument("player detail: missing packed human loan record");
out.attributes = g.players[size_t(s.player_id)];
out.cards = g.player_cards[size_t(s.player_id)];
out.bonus = g.player_bonus[size_t(s.player_id)];
out.original_name = g.player_name(s.player_id);
const uint8_t national_override = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) ? uint8_t(g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) & 10) : 0;
const bool national_label = !out.human_loan && out.national_mode != 0 && national_override == 0 &&
out.attributes.nationality() + ((out.bonus & 0x80) >> 2) == 0;
for (int offer = 0; !national_label && offer < 4; ++offer) {
const uint32_t at = ::bmh::layout::OfferSlots + uint32_t(offer) * 4;
if (!g.memory.has(at + 3)) continue;
const uint32_t value = g.memory.u32(at);
if ((out.source_manager < 0 || int(value & 31) == out.source_manager) &&
int((value >> 10) & 0x0fff) == s.player_id) { out.active_offer = offer; break; }
}
// ClubPlayerDetail_InvalidArgument_RuntimeField2/nationality select the label and the ResolvePendingOffer fallback, not the
// ClubPlayerDetailRedraw dispatch: any existing action remains national in modes1/2.
out.national_action_available = !out.human_loan && out.national_mode != 0 &&
(national_label || out.active_offer >= 0);
return out;
}
ClubPlayerDetailRedraw club_player_detail_redraw(const ModernState& g, const ClubPlayerDetailSelection& selection,
const LeImage& original, GameRandom& game, WatcomRandom& rand,
bool portrait_available) {
ClubPlayerDetailRedraw out;
out.context = modern::club_player_detail_context(g, selection);
std::array<uint8_t, 5> feature_count{};
for (size_t i = 0; i < feature_count.size(); ++i) {
feature_count[i] = original.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + uint32_t(i));
if (feature_count[i] == 0) throw std::invalid_argument("player detail: empty Original portrait feature range");
}
const uint32_t named_players = original.u32(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField);
out.portrait_available = portrait_available;
if (portrait_available) {
uint32_t seed = 0x14344;
if (uint32_t(selection.player_id) < named_players)
for (size_t i = 0; i < out.context.original_name.size(); ++i)
seed += uint32_t(int32_t(int8_t(out.context.original_name[i]))) * uint32_t(i) * 10;
game.set_seed(int32_t(seed));
game.range(0, 100);
out.portrait_base = uint8_t(game.range(0, 3));
for (size_t i = 0; i < out.portrait_features.size(); ++i)
out.portrait_features[i] = uint8_t(game.range(0, feature_count[i] - 1));
const uint64_t before = game.calls();
modern::stir_random(game, rand);
out.portrait_burn_count = uint16_t(game.calls() - before);
}
if (!out.context.human_loan) {
uint32_t value = 0, salary = 0;
modern::market_value(g, out.context.source_slot, 0, 100, value, salary, 0, 0, rand);
out.market_value = ((value + (value >> 2)) / 10000) * 10000;
}
return out;
}
bool club_player_detail_national_action(ModernState& g, const ClubPlayerDetailSelection& selection,
WatcomRandom& rand, MinuteReport& report) {
const auto context = modern::club_player_detail_context(g, selection);
if (!context.national_action_available)
throw std::invalid_argument("player detail: national action is not offered by Source");
const auto national = squad_range(no_team());
bool applied = true;
if (context.national_mode == 1)
applied = modern::add_to_squad(g, context.active_manager, context.source_slot, int(national.first), rand) >= 0;
else if (!g.memory.has(::bmh::layout::MatchEventsDisabled) || g.memory.u8(::bmh::layout::MatchEventsDisabled) == 0)
applied = modern::remove_from_seller(g, no_team(), selection.player_id, report);
auto_lineup(g, no_team(), 0xe4); // ClubPlayerDetailFromGame follows either action with this call.
return applied;
}
} // namespace bmh::modern
+49
View File
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/club_player_detail.hpp"
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include "formats/le.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// The list owns all row identities. A loan row has physical_row==-1 and its
// explicit Source Career_CareerManagersEnd_RuntimeField index. rendered_row is the visible list index, which
// may differ from a filtered/sorted market-pool entry.
// OpenTransferEditor passes actual slots CareerRuntimeField + entry (0..39) for ordinary
// transfer-market pool cards. It never turns the entry into a squad row.
constexpr int kClubPlayerDetailMarketPoolCount = 40;
// Resolves runtime club, explicit row and Source loan/national ownership without
// changing ModernState or either random generator. Invalid/stale identities throw.
ClubPlayerDetailContext club_player_detail_context(const ModernState&,
const ClubPlayerDetailSelection&);
// One actual ClubPlayerDetailFromGame card rebuild: Copy2/21213 portrait draws, followed
// by422ac/42307/PlayerCardMarketValue market valuation. Pure renderer calls consume this owned
// result repeatedly and never draw RNG. The caller passes Source heap gate.
ClubPlayerDetailRedraw club_player_detail_redraw(const ModernState&,
const ClubPlayerDetailSelection&,
const LeImage& original,
GameRandom&, WatcomRandom&,
bool portrait_available = true);
// ClubInfoFromGame temporarily uses (bbcde!=2), then restores its caller's value.
constexpr uint8_t club_player_detail_input_mode(uint8_t prior) { return prior != 2; }
// The actual Source nomination/remove button. Returns false if the national
// squad is full; the Source lineup refresh still follows the attempted add.
bool club_player_detail_national_action(ModernState&, const ClubPlayerDetailSelection&,
WatcomRandom&, MinuteReport&);
} // namespace bmh::modern
+783
View File
@@ -0,0 +1,783 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/cup.hpp"
#include <algorithm>
#include <array>
#include <string>
#include <utility>
#include <vector>
#include "modern/game/driver.hpp"
#include "game/lineup.hpp"
#include "modern/game/matchday.hpp"
#include "modern/game/matchday_setup.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh::modern {
// After the fifth indoor tournament (the end of AdvanceCup for competition 0xb): the
// field of the Masters.
// MastersQualification2: the holders of the three titles of last season (Cup_AdvanceCup_RuntimeField6[0..2],
// u16 club ids) qualify directly, each once (list Cup_MastersQualification_RuntimeField, count CupRuntimeField);
// they head the team list (Teams).
// IndoorStandingsFromGame(0): the clubs 0-39 are sorted by their Masters points (Cup_AdvanceCup_ExecutableField,
// Games descending); IndoorTournamentDraw only resets the tournament (no draw while
// CupRuntimeField != 0); the best clubs not qualified yet fill the list up to eight, which
// is shuffled (PrepareEvent, one game draw per club). The strength class Cup_AdvanceCup_RuntimeField3
// stays that of the last tournament.
// The test "qualified yet" (MastersQualification) scans Cup_MastersQualification_RuntimeField[0 .. CupRuntimeField), but
// CupRuntimeField also counts the clubs filled in from the points list, which never enter
// Cup_MastersQualification_RuntimeField: the scan runs over the stale entries 2 and 3 (0 unless an earlier Masters
// had three direct qualifiers) and from entry 4 into the invitation counters that follow
// (MatchdaySetup_IndoorTournamentDraw_RuntimeField, u16 per club). A club whose id equals one of those values (team 0 with a
// 0 there, small ids with an invitation count) is skipped although it has the points.
// The list is not in the savegame; the replay keeps it in memory, starting at 0.
void masters_qualification(ModernState& g, GameRandom& game) {
StaticMemory& mem = g.memory;
constexpr uint32_t kTeams = ::bmh::layout::Teams, kDirect = ::bmh::layout::Cup_MastersQualification_RuntimeField;
if (!mem.has(kDirect)) mem.add_block(kDirect, 8);
// MastersQualification: whether club t is in Cup_MastersQualification_RuntimeField[0 .. count)
auto listed = [&](uint16_t t, size_t count) {
for (size_t k = 0; k < count; k++)
if (mem.u16(kDirect + uint32_t(k) * 2) == t) return true;
return false;
};
size_t count = 0; // CupRuntimeField
for (uint32_t k = 0; k < 3; k++) {
const uint16_t t = mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6 + k * 2);
if (k == 0 || !listed(t, count)) mem.set16(kDirect + uint32_t(count++) * 2, t);
}
for (size_t k = 0; k < count; k++) mem.set16(kTeams + uint32_t(k) * 2, mem.u16(kDirect + uint32_t(k) * 2));
int16_t order[0x28];
uint32_t points[0x28];
for (int i = 0; i < 0x28; i++) order[i] = int16_t(i), points[i] = mem.u16(::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(i) * 2);
quicksort_by_key(order, points, 0x28);
modern::indoor_tournament_reset(g);
for (int i = 0; count < 8; i++) {
const uint16_t t = uint16_t(order[i]);
if (!listed(t, count)) mem.set16(kTeams + uint32_t(count++) * 2, t);
}
for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams)
const uint32_t j = uint32_t(game.range(0, 7));
const uint16_t a = mem.u16(kTeams + i * 2);
mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2));
mem.set16(kTeams + j * 2, a);
}
for (uint32_t k = 0; k < 8; k++) {
const int manager = g.manager_of(mem.u16(kTeams + k * 2));
if (manager < 0) continue;
post_composed(g, manager, kMastersQualificationText); // MastersQualificationText
modern::book_money(g, manager, -150000, true, true);
}
const std::string name = message_text(g, ::bmh::layout::Cup_MastersQualification_TextPointer);
if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0);
for (size_t i = 0; i <= name.size() && i < 0x24; i++) g.tournament_name[i] = i < name.size() ? uint8_t(name[i]) : 0;
}
namespace {
void put32(Bytes& b, size_t o, uint32_t v) {
for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i));
}
// Replays of postponed league matches: cup entry type 9 plays the matches whose replay day
// (table Postponed, 40 entries of 6 bytes: day, round, league, match) is today.
constexpr uint32_t kPostponed = ::bmh::layout::Postponed;
constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; // team list of the type 9 entry (home, away)
constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; // its result array (u16 per match)
// AddBlock: the fixtures of today's replays; the entry's team count (+0x1a) and played
// counter (+0x1d) restart.
void prepare_replays(ModernState& g, uint32_t e, int day) {
StaticMemory& mem = g.memory;
mem.add_block(kReplayFixtures, 0x50);
mem.add_block(kReplayResults, 0x12);
mem.set8(e + 0x1d, 0);
mem.set8(e + 0x1a, 0);
for (uint32_t i = 0; i < 0x12; i++) mem.set8(kReplayResults + i, 0xcc);
int k = 0;
for (int n = 0; n < 0x28; n++) {
const uint32_t at = kPostponed + uint32_t(n) * 6;
if (mem.u16(at) != day) continue;
const int league = mem.u8(at + 3);
const std::vector<Fixture> fx = generate_fixtures(league_table_teams(league), mem.u8(at + 2) + 1, league_matchdays(league) / 2,
league_first_team(league));
const Fixture& f = fx.at(mem.u8(at + 4));
mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.home));
mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.away));
mem.set8(e + 0x1a, uint8_t(mem.u8(e + 0x1a) + 2));
}
}
// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors).
void remove_competition(StaticMemory& mem, int id) {
for (int i = 0; i < 8; i++) {
if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + uint32_t(i))) != id) continue;
for (int j = i; j < 7; j++) mem.set8(::bmh::layout::ActiveSelectors + uint32_t(j), mem.u8(::bmh::layout::Cup_RemoveCompetition_RuntimeField + uint32_t(j)));
mem.set8(::bmh::layout::Cup_RemoveCompetition_RuntimeField2, 0x14);
return;
}
}
// UndoReschedule(day, 0, 0): today's replay results go back into the league result table and
// their entries are freed; then EndCompetition(9) takes the competition off the list of
// running competitions (ActiveSelectors).
void store_replays(ModernState& g, int day) {
StaticMemory& mem = g.memory;
int k = 0;
for (int n = 0; n < 0x28; n++) {
const uint32_t at = kPostponed + uint32_t(n) * 6;
if (mem.u16(at) != day) continue;
const uint16_t r = mem.u16(kReplayResults + uint32_t(k++) * 2);
const uint8_t result = uint8_t(((r >> 5) << 4) | (r & 0xf));
g.results.at(size_t(mem.u8(at + 4)) + size_t(mem.u8(at + 2)) * 10 + size_t(mem.u8(at + 3)) * 0x17C) = result;
mem.set16(at, 0);
}
remove_competition(mem, 9);
}
// Size of the round string table a cup group plays with (pointer at entry +8).
int group_table_teams(const StaticMemory& mem, uint32_t e) {
switch (mem.pointer(e + 8)) {
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: return 4;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: return 6;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: return 12;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: return 16;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: return 18;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: return 20;
}
return 0;
}
// AddResult(entry, 0): the table of a cup group from its result array (u16 per match,
// 0xCCCC = not played), indexed by draw position. Bit 7 of the flags: three points for a
// win. The ranks are sorted like the league tables (AddResult2) after the last two rounds
// and after later rounds with results.
LeagueTable group_table(const StaticMemory& mem, uint32_t e) {
LeagueTable t;
const uint8_t flags = mem.u8(e + 0x14);
const int teams = mem.u8(e + 0x1a), rounds = mem.u8(e + 0x1b), played = mem.u8(e + 0x1d);
t.size = teams;
const int three_points = flags >> 7;
int last = played - 1, before_last = 0x80;
if (last > 1) before_last = played - 2;
if (last < 0) last = 0;
sort_table(t, 0);
const uint32_t results = mem.pointer(e + 0x0c);
for (int r = 0; r < rounds; r++) {
const std::vector<Fixture> fx = generate_fixtures(group_table_teams(mem, e), r + 1, rounds / ((flags & 1) + 1), 0);
bool counted = false;
for (int s = 0; s < teams; s += 2) {
const uint16_t u = mem.u16(results + uint32_t(s / 2 + r * teams / 2) * 2);
if (u == 0xcccc) continue;
const uint8_t goals[2] = {uint8_t((u >> 5) & 0x1f), uint8_t(u & 0x1f)};
const int club[2] = {fx.at(size_t(s / 2)).home, fx.at(size_t(s / 2)).away};
add_result(t, club, goals, 3, three_points);
counted = true;
}
if (before_last == r || last == r || (last < r && counted)) sort_table(t, 0);
}
return t;
}
// The end of a group stage (AdvanceCup): the qualifiers place by place (all group
// winners, then the runners-up, ...) until the stage's quota (+0x1f) is reached; a place
// taken only partly keeps its best clubs by the table key. Group winner and runner-up are
// noted in +0x22 / +0x24 of every group. Returns the qualifiers and in `loser_pair` the
// first two clubs of the first group ordered by the last table's second place (for a final
// of two).
std::vector<uint16_t> group_qualifiers(StaticMemory& mem, uint32_t e, std::array<uint16_t, 2>& loser_pair) {
const int groups = mem.u8(e + 0x1e) & 0xF;
int quota = int8_t(mem.u8(e + 0x1f));
std::vector<uint16_t> teams;
std::vector<uint32_t> keys;
LeagueTable t;
for (int place = 0; quota > 0; place++) {
for (int grp = 0; grp < groups; grp++) {
uint32_t ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
t = group_table(mem, ge);
int idx = 0;
while (idx < mem.u8(ge + 0x1a) && t.rank(idx) != place) idx++;
const uint16_t team = mem.u16(mem.pointer(ge) + uint32_t(idx) * 2);
if (place == 0) mem.set16(ge + 0x22, team);
if (place == 1) mem.set16(ge + 0x24, team);
keys.push_back(sort_key(t, idx, 0));
teams.push_back(team);
quota--;
}
}
const uint32_t list = mem.pointer(e);
loser_pair[0] = t.rank(0) == 1 ? mem.u16(list) : mem.u16(list + 2);
const int wanted = int8_t(mem.u8(e + 0x1f));
const int cut = wanted - wanted % groups;
for (; quota < 0; quota++) {
uint32_t worst = keys.back();
size_t at = 0;
for (int k = cut; k < wanted; k++)
if (keys[size_t(k)] < worst) at = size_t(k), worst = keys[size_t(k)];
if (worst < keys.back()) {
std::swap(teams.back(), teams[at]);
std::swap(keys.back(), keys[at]);
}
teams.pop_back();
keys.pop_back();
}
return teams;
}
} // namespace
LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address) {
return group_table(mem, entry_address);
}
int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address) {
return group_table_teams(mem, entry_address);
}
void end_competition(StaticMemory& mem, int id) { remove_competition(mem, id); }
void prepare_friendlies(ModernState& g) {
StaticMemory& mem = g.memory;
if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams) || !mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24)) return;
const int today = g.season_day(); // DaysIntoSeason
int count = 0; // local_c: two teams per friendly
for (int i = 0; i < 0x1e; i++) {
if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i) * 2)) != int16_t(today)) continue;
for (int c = 0; c < 2; c++)
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24 + uint32_t(c + count) * 2, mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i * 2 + c) * 2));
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29 + uint32_t(count >> 1) * 2, 0xcccc);
mem.set16(::bmh::layout::FriendlyDays + uint32_t(i) * 2, 0);
count += 2;
if (i < 0x1d) {
// the planned ones after it move up (the last place keeps its copy)
for (int k = i; k < 0x1d; k++) {
mem.set32(::bmh::layout::FriendlyTeams + uint32_t(k) * 4, mem.u32(::bmh::layout::Cup_PrepareFriendlies_RuntimeField + uint32_t(k) * 4));
mem.set16(::bmh::layout::FriendlyDays + uint32_t(k) * 2, mem.u16(::bmh::layout::Cup_PrepareFriendlies_RuntimeField2 + uint32_t(k) * 2));
}
i--;
// the planner's entry 30 counts them (two per friendly); only decreased here,
// not for the last place (as in the original)
const uint32_t planned = modern::cup_entry_address(30) + 0x1a;
mem.set8(planned, uint8_t(mem.u8(planned) - 2));
}
}
mem.set8(modern::cup_entry_address(24) + 0x1a, uint8_t(count)); // today's friendlies (CupRuntimeField2)
}
int find_cup(const StaticMemory& mem, int id) {
for (int i = 0; i < kCupEntries; i++)
if (int16_t(mem.u16(modern::cup_entry_address(i) + 0x18)) == id) return i;
return -1;
}
int cup_round(const StaticMemory& mem, int entry) {
const uint32_t e = modern::cup_entry_address(entry);
const uint8_t flags = mem.u8(e + 0x14), played = mem.u8(e + 0x1d);
if (!(flags & 4)) return played;
return played / ((flags & 1) + 1);
}
int cup_round_offset(const StaticMemory& mem, int entry, int round) {
if (round == 0) return 0;
const int teams = mem.u8(modern::cup_entry_address(entry) + 0x1a);
return teams * 2 - teams / (1 << (round - 1));
}
void rebuild_replay_lists(ModernState& g, uint32_t competitions) {
for (int bit = 5; bit < 0x13; bit++) {
if (!((competitions >> bit) & 1)) continue;
const int entry = modern::find_cup(g.memory, bit - 5);
if (entry >= 0 && int16_t(g.memory.u16(modern::cup_entry_address(entry) + 0x18)) == 9)
prepare_replays(g, modern::cup_entry_address(entry), g.season_day());
}
}
void setup_cup_groups(ModernState& g, int id, std::vector<MatchGroup>& groups, MinuteReport& report) {
const StaticMemory& mem = g.memory;
int entry = modern::find_cup(mem, id);
if (entry < 0) {
report.fail("cup " + std::to_string(id) + " not in the cup table");
return;
}
const int type = int16_t(mem.u16(modern::cup_entry_address(entry) + 0x18));
if (type == 9) prepare_replays(g, modern::cup_entry_address(entry), g.season_day());
if (type == 10) modern::prepare_friendlies(g);
if (type > 9 && mem.u8(modern::cup_entry_address(entry) + 0x1a) != 0) {
// AddCompetition: onto the list of running competitions (ActiveSelectors, 0x14 = free)
for (uint32_t i = 0; i < 8; i++) {
if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == type) break;
if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) {
g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(type));
break;
}
}
}
// (the friendlies 10, the promotion play-off 0xd and the indoor tournament 0xb only join
// the running list above)
if (type > 0xb && type != 0xd && mem.u8(modern::cup_entry_address(entry) + 0x1a) != 0) {
report.fail("cup " + std::to_string(id) + ": preparation of this competition (AddBlock/2631b/26175)");
return;
}
// skip the stages that are completed (bounded: a broken chain would loop for ever)
for (int steps = 0; modern::cup_round(mem, entry) >= mem.u8(modern::cup_entry_address(entry) + 0x1b); ++steps) {
const int next = int8_t(mem.u8(modern::cup_entry_address(entry) + 0x16));
if (steps > 0x24 || next < 0 || next >= 0x24) {
report.fail("cup " + std::to_string(id) + ": stage chain without an open stage (entry " + std::to_string(entry) +
", round " + std::to_string(modern::cup_round(mem, entry)) + " of " +
std::to_string(mem.u8(modern::cup_entry_address(entry) + 0x1b)) + ", next " + std::to_string(next) + ")");
return;
}
entry = next;
}
const int parallel = mem.u8(modern::cup_entry_address(entry) + 0x1e) & 0xF;
if (mem.u32(modern::cup_entry_address(entry)) == 0) return;
for (int k = 0; k < parallel; k++) {
const uint32_t e = modern::cup_entry_address(entry);
const uint8_t flags = mem.u8(e + 0x14);
const int teams = mem.u8(e + 0x1a);
if (teams == 0) continue; // (the original then looks at the same entry again)
MatchGroup grp;
grp.desc = modern::group_descriptor(g, groups.size());
grp.desc.at(0) = uint8_t(type + 1);
grp.desc.at(1) = flags;
// competition 11 is the German indoor tournament; in the English game the same entry
// is the League Cup ("Koka Kola Cup"), an ordinary cup on grass (EN Put32)
if (type == 0xb && !kEnglishCompetitions) g.indoor = true;
put32(grp.desc, 0xcc, e);
// the first leg of a two-legged knockout tie is never decided on the day
if ((flags & 5) == 5 && mem.u8(e + 0x1d) % 2 == 0) grp.desc.at(1) &= 0xF7;
int matches = 0, first = 0; // local_1c; the result index is `first` / 2
const uint32_t list = mem.pointer(e);
if (!(flags & 4)) {
// a group: GenerateFixtures on the cup's round strings (+8), round = played + 1, the
// draw positions index the group's team list; two-legged groups play the rounds
// of the string table twice, home and away swapped
matches = teams / 2;
const int played = mem.u8(e + 0x1d);
first = uint8_t(matches * played * 2);
const int rounds = mem.u8(e + 0x1b) / ((flags & 1) + 1);
int table_teams = 0;
switch (mem.pointer(e + 8)) {
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break;
}
if (table_teams == 0) {
report.fail("cup group with unknown round strings");
return;
}
for (const Fixture& f : generate_fixtures(table_teams, played + 1, rounds, 0)) {
if (int(grp.fixtures.size()) >= matches * 2) break;
grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.home) * 2)));
grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.away) * 2)));
}
// the fixtures are kept in the descriptor itself (+0x88; +0x7c points there)
for (size_t i = 0; i < grp.fixtures.size(); i++) {
grp.desc.at(0x88 + i * 2) = uint8_t(grp.fixtures[i]);
grp.desc.at(0x89 + i * 2) = uint8_t(uint16_t(grp.fixtures[i]) >> 8);
}
} else {
const int round = modern::cup_round(mem, entry);
matches = teams / (1 << (round + 1));
first = modern::cup_round_offset(mem, entry, round);
for (int i = 0; i < matches * 2; i++) grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(first + i) * 2)));
}
grp.desc.at(2) = uint8_t(matches);
if (type == 0 && matches == 1) grp.desc.at(1) &= 0xFD; // the national cup final
// MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a)
for (int i = 0; i < matches * 2; i++)
for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++)
if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * 0xB0C + 0x28a) = uint8_t(i % 2);
for (int leg = 0; leg < 2; leg++) {
if (leg == 1 && !(flags & 1)) break;
const uint32_t results = mem.pointer(e + 0x0c + uint32_t(leg) * 4);
if (results == 0) continue;
grp.cup_result_address[leg] = results + uint32_t(first / 2) * 2;
std::vector<uint16_t>& r = leg == 0 ? grp.cup_results : grp.cup_other_leg;
for (int i = 0; i < matches; i++) r.push_back(mem.u16(grp.cup_result_address[leg] + uint32_t(i) * 2));
}
groups.push_back(grp);
entry++;
}
}
} // namespace bmh::modern
namespace bmh::modern {
void store_cup_results(ModernState& g, const MatchGroup& grp) {
if (grp.desc.at(0) == 0 || grp.cup_result_address[0] == 0) return;
for (size_t i = 0; i < grp.cup_results.size(); i++)
g.memory.set16(grp.cup_result_address[0] + uint32_t(i) * 2, grp.cup_results[i]);
}
namespace {
// NationalTournamentEnd, at the end of the international tournament (competition type 4): the
// honours list of the tournaments (Placements, 4 bytes per tournament, newest first)
// moves one place on and gets the first four (final winner and loser Cup_NationalTournamentEnd_RuntimeField/2dce,
// third place match Cup_NationalTournamentEnd_RuntimeField3/2df6) as national team index | 0x80. A Bundestrainer's
// association (manager slot 0 holds team 0x165) pays 400000 for taking part and the
// premium of the place (CupRuntimeField3).
void national_tournament_end(ModernState& g) {
StaticMemory& mem = g.memory;
const int teams[4] = {int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField2)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField3)),
int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField4))};
static constexpr int32_t kPremium[4] = {1000000, 600000, 300000, 200000}; // CupRuntimeField3
if (mem.has(::bmh::layout::Placements))
for (int i = 0x4c - 1; i >= 0; i--) mem.set8(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField5 + uint32_t(i), mem.u8(::bmh::layout::Placements + uint32_t(i)));
const bool coach = !g.manager_teams.empty() && g.manager_teams[0] == no_team();
if (coach) modern::book_money(g, 0, -400000, true, true);
for (int i = 0; i < 4; i++) {
if (teams[i] == no_team() && coach) modern::book_money(g, 0, -kPremium[i], true, true);
// (0x8a + 0x1e + 0xbd = 0x165: CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3)
if (mem.has(::bmh::layout::Placements)) mem.set8(::bmh::layout::Placements + uint32_t(i), uint8_t((teams[i] - no_team()) | 0x80));
}
}
// cup_tie on the result arrays of a stage (CupTie(results0, results1, index, flags))
int stage_tie(const StaticMemory& mem, uint32_t e, int index) {
MatchGroup grp;
grp.desc.assign(0xd0, 0);
grp.desc.at(1) = mem.u8(e + 0x14);
const uint32_t r0 = mem.pointer(e + 0x0c), r1 = mem.pointer(e + 0x10);
grp.cup_results.assign(size_t(index) + 1, 0);
grp.cup_results[size_t(index)] = mem.u16(r0 + uint32_t(index) * 2);
if (r1 != 0) {
grp.cup_other_leg.assign(size_t(index) + 1, 0);
grp.cup_other_leg[size_t(index)] = mem.u16(r1 + uint32_t(index) * 2);
}
return modern::cup_tie(grp, index);
}
void swap16(StaticMemory& mem, uint32_t a, uint32_t b) {
const uint16_t x = mem.u16(a);
mem.set16(a, mem.u16(b));
mem.set16(b, x);
}
// Getenv(teams, offset): Source home advantage followed by an unstable-free
// descending sort on each tie's combined league weight. Kept in this Core module so
// finish_cup can expose the Original draw before the inner sort and retain its outer sort.
void order_national_cup_ties(ModernState& g, int teams, int offset) {
StaticMemory& mem = g.memory;
const uint32_t list = mem.pointer(modern::cup_entry_address(0)) + uint32_t(offset) * 2;
static constexpr uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0};
const int lower = league_first_team(2);
std::vector<uint8_t> weights;
weights.reserve(size_t(teams / 2));
auto team = [&](int i) { return int16_t(mem.u16(list + uint32_t(i) * 2)); };
auto swap_pair = [&](int a, int b) {
swap16(mem, list + uint32_t(a) * 2, list + uint32_t(b) * 2);
swap16(mem, list + uint32_t(a + 1) * 2, list + uint32_t(b + 1) * 2);
};
for (int i = 0; i < teams; i += 2) {
if (lower <= team(i + 1) && team(i) < lower)
swap16(mem, list + uint32_t(i) * 2, list + uint32_t(i + 1) * 2);
auto league = [](int t) { return t > 0x164 ? 0 : team_league(t); };
const int la = league(team(i)), lb = league(team(i + 1));
weights.push_back(uint8_t(kWeight[la < 10 ? la : 9] + kWeight[lb < 10 ? lb : 9]));
}
for (int i = 0; i < teams / 2 - 1; ++i)
for (int j = i + 1; j < teams / 2; ++j)
if (weights[size_t(i)] < weights[size_t(j)]) {
std::swap(weights[size_t(i)], weights[size_t(j)]);
swap_pair(i * 2, j * 2);
}
}
bool source_cup_draw_enabled(const StaticMemory& mem, int competition) {
// CupDrawFromGame: outside leagues 4..7 the leagues must be enabled, then the
// competition's display option must be clear. The follow-up package targets comp0.
if (competition < 4 || competition > 7) {
if (!mem.has(::bmh::layout::CompetitionSelection) || (mem.u8(::bmh::layout::CompetitionSelection) & 1) == 0) return false;
}
const uint32_t option = ::bmh::layout::LeaguePresentationOptions + uint32_t(competition + 5) * 9;
return mem.has(option) && mem.u8(option) == 0;
}
void observe_cup_draw(const ModernState& g, int entry, SeasonCupDrawPhase phase,
const SeasonCupDrawHook& hook) {
if (!hook) return;
const StaticMemory& mem = g.memory;
const uint32_t address = modern::cup_entry_address(entry);
SeasonCupDrawEvent event;
event.phase = phase;
event.entry_address = address;
event.competition = mem.u8(address + 0x18);
event.round = modern::cup_round(mem, entry);
event.offset = modern::cup_round_offset(mem, entry, event.round);
event.count = size_t(mem.u8(address + 0x1a)) >> event.round;
const uint32_t first = mem.pointer(address) + uint32_t(event.offset) * 2;
event.participants.reserve(event.count);
for (size_t i = 0; i < event.count; ++i)
event.participants.push_back(mem.u16(first + uint32_t(i) * 2));
hook(g, event);
}
} // namespace
void advance_cup(ModernState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game,
const SeasonCupDrawHook& cup_draw, const CompetitionWinnerHook& winner_display) {
StaticMemory& mem = g.memory;
int entry = modern::find_cup(mem, id);
if (entry < 0) return;
const int type = int16_t(mem.u16(modern::cup_entry_address(entry) + 0x18));
if (type == 9) return store_replays(g, g.season_day());
// EndCompetition(type), re-added at the next preparation; the English Put32 keeps its
// League Cup (type 0xb) running like the other cups
if (type == 0xb && !kEnglishCompetitions) remove_competition(mem, type);
if (type == 10) {
// the friendlies: off the running list, the day's calendar entry masked with 0xffe
// (0x4001 becomes 0) and no teams left in today's entry (CupRuntimeField2)
remove_competition(mem, type);
const uint32_t day = ::bmh::layout::CompetitionCalendar + uint32_t(g.season_day()) * 2;
if (mem.has(day)) mem.set16(day, uint16_t(mem.u16(day) & 0xffe));
mem.set8(modern::cup_entry_address(24) + 0x1a, 0);
return;
}
if (type > 8 && type != 0xd && type != 0xb) {
report.fail("cup " + std::to_string(id) + ": processing of this competition (AdvanceCup)");
return;
}
while (modern::cup_round(mem, entry) >= mem.u8(modern::cup_entry_address(entry) + 0x1b))
entry = int8_t(mem.u8(modern::cup_entry_address(entry) + 0x16));
uint32_t e = modern::cup_entry_address(entry);
std::vector<uint16_t> winners, losers;
std::array<uint16_t, 2> loser_pair{};
if (!(mem.u8(e + 0x14) & 4)) {
// a group stage: every group (the consecutive entries up to the one without a
// parallel link, +0x17) counts the round
for (uint32_t ge = e;; ge += kCupEntrySize) {
mem.set8(ge + 0x1d, uint8_t(mem.u8(ge + 0x1d) + 1));
if (mem.u8(ge + 0x17) == 0) break;
}
if (mem.u8(e + 0x1d) < mem.u8(e + 0x1b)) return;
winners = group_qualifiers(mem, e, loser_pair);
} else {
const int round = modern::cup_round(mem, entry);
const int slots = mem.u8(e + 0x1a) / (1 << round); // local_3c: teams in this round
const int first = modern::cup_round_offset(mem, entry, round);
mem.set8(e + 0x1d, uint8_t(mem.u8(e + 0x1d) + 1)); // (unless CupRuntimeField4)
const uint32_t list = mem.pointer(e);
if ((mem.u8(e + 0x14) & 1) && mem.u8(e + 0x1d) % 2 != 0) {
// after the first leg: the pairs turn round, the results go to the second array
for (int i = 0; i < slots; i += 2) {
swap16(mem, list + uint32_t(first + i) * 2, list + uint32_t(first + i + 1) * 2);
const uint32_t k = uint32_t((first + i) / 2) * 2;
swap16(mem, mem.pointer(e + 0x0c) + k, mem.pointer(e + 0x10) + k);
}
return;
}
for (int i = 0; i < slots; i += 2) {
int t = stage_tie(mem, e, (first + i) / 2);
if (t > 1) t = 1;
winners.push_back(mem.u16(list + uint32_t(first + i + t) * 2));
losers.push_back(mem.u16(list + uint32_t(first + i + 1 - t) * 2));
}
}
// CupRuntimeField5[type] < 5 (national cup and the three European cups): a human manager's
// club that goes through counts one more round in his season record (ManagerOf,
// record +0xda + season * 3 + 1 national / 2 European)
if (type >= 0 && type <= 3)
for (uint16_t t : winners) {
const int manager = g.manager_of(t);
if (manager < 0) continue;
const size_t at = size_t(manager) * 0xB0C + 0xda + size_t(std::min(g.season, 0x31)) * 3 + (type > 0 ? 2 : 1);
g.manager_records.at(at) = uint8_t(g.manager_records.at(at) + 1);
}
if (modern::cup_round(mem, entry) == mem.u8(e + 0x1b)) {
// the stage is over
if (mem.u8(e + 0x16) == 0) {
// The last stage of the competition. A single final notes its winner (+0x22) and
// loser (+0x24); competition 0xc leaves the running list.
if (winners.size() == 1) {
mem.set16(e + 0x22, winners[0]);
if (!losers.empty()) mem.set16(e + 0x24, losers[0]);
}
if (type == 0xc) remove_competition(mem, 0xc);
// CupRuntimeField5: the title of the competition (0xFF: none)
static constexpr uint8_t kTitle[14] = {1, 2, 3, 4, 5, 0xff, 6, 0xff, 8, 0xff, 0xff, 0xff, 0xff, 0xff};
const uint8_t title = type >= 0 && type < 14 ? kTitle[type] : 0xff;
if (title != 0xff && !winners.empty()) {
if (type == 4) national_tournament_end(g); // NationalTournamentEnd
// CompetitionWinnerScreen(0, title, winner): the winner screen (unless switched off,
// Cup_AdvanceCup_RuntimeField; no draws) clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2. A human manager's club counts
// the title in his record: +0x8a6 national cup, +0x8a8 European cups.
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display)
winner_display(g, {title, winners[0]});
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
const int manager = g.manager_of(winners[0]);
if (manager >= 0 && type >= 0 && type < 4) {
const size_t at = size_t(manager) * 0xB0C + (type == 0 ? 0x8a6 : 0x8a8);
const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
g.manager_records.at(at) = uint8_t(n + 1), g.manager_records.at(at + 1) = uint8_t((n + 1) >> 8);
}
// ListTitleHoldersAf(winner, title): the list of title holders (Titles)
mem.set16(::bmh::layout::Titles + uint32_t(title) * 100 + uint32_t(std::min<int>(g.season, 0x31)) * 2, winners[0]);
}
if (type == 0 && !winners.empty()) {
// the national cup: winner (Cup_AdvanceCup_RuntimeField5) and the previous holder
// (Career_CompetitionPointersEnglish_ExecutableField28 = Cup_AdvanceCup_RuntimeField6); Cup_AdvanceCup_RuntimeField2 = 0 if the holder won again, else 2
mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, winners[0]);
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6));
if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc);
if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField2)) mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField2, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6) == winners[0] ? 0 : 2);
}
// a linked stage (+0x17) takes the runner-up (the indoor tournament's final group
// notes it in the group for third place)
if (mem.u8(e + 0x17) != 0 && winners.size() > 1)
mem.set16(modern::cup_entry_address(mem.u8(e + 0x17)) + 0x22, winners[1]);
// (the indoor tournament only: the English League Cup has no Masters; its winner
// would go to EN CupRuntimeField6 for Europe - not ported, see docs/fltd.md)
if (type != 0xb || kEnglishCompetitions) return;
// the indoor tournament: the four places (CupRuntimeField7 picks them from the list
// champion..fourth) earn points for the Masters (CupRuntimeField8 x strength class
// Cup_AdvanceCup_RuntimeField3, clubs of the first two leagues only), then the next tournament is
// drawn; after five tournaments the Masters follow
int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4);
if (held > 4) {
// the end of the Masters: CompetitionWinnerScreen(0, 7, winner) shows the winner (unless
// switched off, Cup_AdvanceCup_RuntimeField; no draws) and clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2;
// ListTitleHoldersAf(winner, 7) enters it in the list of title holders (Titles,
// 50 seasons per competition); Cup_AdvanceCup_RuntimeField7 = winner; a human manager's club
// gets a message and 250 000; EndCompetition removes the competition
const uint16_t winner = mem.u16(e + 0x22);
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display)
winner_display(g, {7, winner});
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
mem.set16(::bmh::layout::Titles + 7 * 100 + uint32_t(std::min<int>(g.season, 0x31)) * 2, winner);
if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField7)) mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField7, winner);
const int manager = g.manager_of(winner);
if (manager >= 0) {
post_composed(g, manager, kMastersWinnerText); // MastersWinnerText
modern::book_money(g, manager, -250000, true, true);
}
remove_competition(mem, type);
return;
}
static constexpr uint8_t kPlaceOrder[4] = {0, 2, 1, 3}; // CupRuntimeField7
static constexpr uint8_t kPlacePoints[5] = {0, 6, 4, 2, 1}; // CupRuntimeField8
for (int i = 0; i < 4 && size_t(kPlaceOrder[i]) < winners.size(); i++) { // Uint32T
const int team = winners[kPlaceOrder[i]];
if (team < kLeagueSizes[0] + kLeagueSizes[1]) {
const uint32_t at = ::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(team) * 2;
mem.set16(at, uint16_t(mem.u16(at) + kPlacePoints[i + 1] * mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField3)));
}
}
mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, uint8_t(++held));
if (!game) {
report.fail("indoor tournament: the next draw needs the game generator");
return;
}
if (held >= 5) {
modern::masters_qualification(g, *game);
return;
}
modern::indoor_tournament_draw(g, *game, rand); // (CupRuntimeField = 0)
return;
}
uint32_t last = e;
const int seeded = mem.u8(e + 0x20);
if (seeded != 0) {
// clubs seeded directly into the next stage stand before the team lists
const int groups = mem.u8(e + 0x1e) & 0xF;
int left = seeded;
for (int k = 0; left != 0; k++)
for (int grp = 0; grp < groups; grp++) {
uint32_t ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
last = ge;
if (left != 0) {
winners.push_back(mem.u16(mem.pointer(ge) - 2 - uint32_t(k) * 2));
left--;
}
}
}
entry = int8_t(mem.u8(last + 0x16));
e = modern::cup_entry_address(entry);
}
const int count = int(winners.size()); // local_14
if (mem.u8(e + 0x14) & 0x20) {
// the draw
for (int i = 0; i < count; i++) {
const int a = rand.range(0, count - 1);
const int b = rand.range(0, count - 1);
std::swap(winners[size_t(b)], winners[size_t(a)]);
}
}
if (!(mem.u8(e + 0x14) & 4)) {
// a group stage: the teams go round the groups, taken from the end
// groups of two (third place and final): the losers of the ties are added (local_88)
if (mem.u8(e + 0x1a) == 2)
for (int i = 0; i < 2 && size_t(i) < losers.size(); i++) winners.push_back(losers[size_t(i)]);
const int groups = mem.u8(e + 0x1e) & 0xF;
int left = int(winners.size());
uint32_t ge = e;
for (int slot = 0; slot < mem.u8(e + 0x1a); slot++)
for (int grp = 0; grp < groups; grp++) {
ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
mem.set16(mem.pointer(ge) + uint32_t(slot) * 2, winners.at(size_t(--left)));
}
// AdvanceCup leaves any entrants beyond the regular group slots in the reserved
// list immediately before the final linked group's team list (entry +0x20 is the
// source guard). The Source consumes the remaining local list backwards.
if (mem.u8(ge + 0x20) != 0) {
for (int slot = 0; left > 0; ++slot)
for (int grp = 0; grp < groups; ++grp)
if (left > 0)
mem.set16(mem.pointer(ge) - 2 - uint32_t(slot) * 2, winners.at(size_t(--left)));
}
if (mem.u8(e + 0x1a) == 2) {
// the first club of this group and the second of the linked group change places
const uint32_t a = mem.pointer(e), b = mem.pointer(modern::cup_entry_address(mem.u8(e + 0x17))) + 2;
const uint16_t x = mem.u16(a);
mem.set16(a, mem.u16(b));
mem.set16(b, x);
}
} else {
const int next_round = modern::cup_round(mem, entry);
const int offset = modern::cup_round_offset(mem, entry, next_round);
const uint32_t to = mem.pointer(e);
int first_pair = 0;
if (next_round == mem.u8(e + 0x1b) && mem.u8(e + 0x20) != 0) {
first_pair = mem.u8(e + 0x20);
for (int i = 0; i < first_pair; ++i)
mem.set16(to - 2 - uint32_t(i) * 2, winners.at(size_t(i)));
}
for (int i = first_pair; i < count / 2; i++) {
mem.set16(to + uint32_t(offset + i * 2) * 2, winners[size_t(i)]);
mem.set16(to + uint32_t(offset + i * 2 + 1) * 2, winners[size_t(count - 1 - i)]);
}
if (e == modern::cup_entry_address(0)) {
const bool eligible = type == 0 && count > 2 && (mem.u8(e + 0x14) & 0x20) != 0 &&
source_cup_draw_enabled(mem, type);
if (eligible) {
// CupDrawFromGame displays the just-written shuffled order first.
observe_cup_draw(g, entry, SeasonCupDrawPhase::draw, cup_draw);
// It then performs Getenv and CupGroupOverviewEffects before returning.
order_national_cup_ties(g, count, offset);
modern::cup_overview_effects(g); // simulation effects occur even without an observer
observe_cup_draw(g, entry, SeasonCupDrawPhase::overview, cup_draw);
}
// AdvanceCup performs this outer sort after CupDrawFromGame returns (including
// its hidden-display early return). It is idempotent after the inner sort.
order_national_cup_ties(g, count, offset);
}
}
// Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3: clubs left in the European cups
const uint32_t left_at[4] = {0, ::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3};
if (type >= 1 && type <= 3 && mem.has(left_at[type])) mem.set8(left_at[type], uint8_t(count));
}
} // namespace bmh::modern
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
#include "game/cup.hpp"
// Cup competitions (BMH.exe V2.24 + supported rule profile patch).
//
// All cups are described by the table at CupTable: 36 entries of 0x28 bytes, one per stage
// (knockout rounds of a cup, a group of a group stage, a final, ...). Entries of the same
// cup share the id at +0x18 and are linked:
// +0x00 pointer to the team list (u16 team ids; for knockout stages the pairs of each
// round follow each other, round r starting at cup_round_offset(r))
// +0x08 pointer to the round strings of group stages (fixture tables, see schedule.hpp)
// +0x0c pointer to the results of the first/only leg, +0x10 of the second leg (u16 per
// match: bits 0-4 away goals, 5-9 home goals, 10-15 phase; 0xCCCC not played)
// +0x14 flags: bit 0 two legs, bit 2 knockout, bit 3 the tie is decided on the day
// (extra time), bit 1 away-side penalty for league-style chances, ...
// +0x16 index of the next stage, +0x17 index of the parallel group of this stage
// +0x18 cup id (0 national cup, 1-3 European cups, 4.. further competitions)
// +0x1a number of teams, +0x1b number of rounds (legs), +0x1d legs played so far
// +0x1e low nibble: number of parallel groups, high nibble: index of this group
// Match group descriptors of cups have type = cup id + 1 and point to their table entry
// (descriptor +0xcc) instead of holding a league number.
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/table.hpp"
#include "modern/game/season.hpp"
#include "game/sportschau_presentation.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
constexpr uint32_t kCupTable = ::bmh::layout::CupTable;
constexpr int kCupEntries = 36;
constexpr uint32_t kCupEntrySize = 0x28;
inline uint32_t cup_entry_address(int index) { return kCupTable + uint32_t(index) * kCupEntrySize; }
inline int cup_entry_index(uint32_t address) { return int((address - kCupTable) / kCupEntrySize); }
// FindCup(id, 0): the first table entry of a cup, -1 if there is none.
int find_cup(const StaticMemory& mem, int id);
// CupRound: the current round of a stage (legs played, halved for two-legged ties).
int cup_round(const StaticMemory& mem, int entry);
// CupRoundOffset: index of the first team of knockout round `round` in the team list.
int cup_round_offset(const StaticMemory& mem, int entry, int round);
// AddResult's group-table calculation. Exposes the existing Core projection
// as a read-only value for Source overview observers and renderers.
LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address);
// Team count selected by the Source group round-schedule pointer at entry +8.
int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address);
// SetupCupGroups: the match groups of cup `id` for today, appended to `groups`.
void setup_cup_groups(ModernState& g, int id, std::vector<MatchGroup>& groups, MinuteReport& report);
// The lists of today's postponed-match replays (blocks ReplayFixtures/ReplayResults, not in the savegame) as
// the preparation of the matchday built them (prepare_replays, no draws): needed when a game
// saved at the pre-match desk of a replay day is continued.
void rebuild_replay_lists(ModernState& g, uint32_t competitions);
// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors).
void end_competition(StaticMemory& mem, int id);
// PrepareFriendlies: the friendlies (competition 10, cup table entry 24) of today: the planned ones
// (entry 30: team pairs FriendlyTeams, season days FriendlyDays, 30 places) of this season day
// go into the day's fixture list (Career_CompetitionPointersEnglish_ExecutableField24) with an open result (0xcccc) and leave the plan.
void prepare_friendlies(ModernState& g);
} // namespace bmh::modern
namespace bmh::modern {
// Writes the results of a cup group (current leg) back into the result array in memory.
void store_cup_results(ModernState& g, const MatchGroup& grp);
// AdvanceCup for knockout stages: after a matchday of cup `id` the legs played go up;
// after the first leg of a two-legged tie the pairs turn round (home and away swapped,
// the results moved to the other leg's array). After a complete round the winners
// (cup_tie) meet in the next round - drawn if the stage has flag 0x20 (WatcomRandom) -
// or, when the stage is over, fill the next linked stage, including qualifiers and direct
// seeds for group and knockout formats; group match simulation and competition-specific
// finals remain outside this routine.
// The indoor tournament draws its next tournament at the end (game generator, `game`).
void advance_cup(ModernState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr,
const SeasonCupDrawHook& cup_draw = {}, const CompetitionWinnerHook& winner = {});
// The end of the fifth indoor tournament: the field of the Masters (MastersQualification2,
// IndoorStandingsFromGame(0)), see cup.cpp.
void masters_qualification(ModernState& g, GameRandom& game);
} // namespace bmh::modern
+130
View File
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/desk.hpp"
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include "modern/game/matchday.hpp"
#include "game/messages.hpp"
#include "modern/game/prediction.hpp"
#include "game/schedule.hpp"
#include "modern/game/week.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xB0C;
// DeskRuntimeField: which of the 0x36 desk buttons exist, for the pseudo club 0x165 and per
// game mode (GameMode; the table for mode m starts at DeskRuntimeField + m * 0x36).
constexpr uint8_t kButtons[0xa2] = {
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1,
0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0};
int16_t rd16(const std::vector<uint8_t>& v, size_t o) { return int16_t(v.at(o) | v.at(o + 1) << 8); }
} // namespace
void update_prestige(ModernState& g, int manager) {
static const uint8_t kWeight[4] = {25, 50, 15, 10}; // DeskRuntimeField2
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(manager) * kRecord;
r.at(rec + 0x211) = 0;
for (int k = 0; k < 4; k++) {
int value = 0; // local_c
switch (k) {
case 0: value = (rd16(r, rec + 0x8b2) * 100) / 0x44c; break;
case 1: value = (rd16(r, rec + 0x8aa) * 100) / 0x44c; break;
case 2: {
const int32_t balance = int32_t(r.at(rec + 0x314) | r.at(rec + 0x315) << 8 | r.at(rec + 0x316) << 16 |
uint32_t(r.at(rec + 0x317)) << 24);
value = std::clamp(balance / 50000 + 0x32, 0, 100);
break;
}
case 3: value = r.at(rec + 0x26f); break;
}
r.at(rec + 0x211) = uint8_t(r.at(rec + 0x211) + int8_t((kWeight[k] * value) / 100));
}
}
void save_game_draws(WatcomRandom& rand) {
const int high = rand.range(0, 0x8fff), low = rand.range(0, 0x8fff);
(void)high, (void)low; // the savegame id high * layout field + low + 1 (DeskRuntimeField3, list ab790)
rand.range(0, 0xff); // DeskRuntimeField4 = r + 'n', the check byte at the end of the file
rand.range(0, 0xff); // the key byte of the header
}
void enter_desk(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand,
const DeskAutosaveHook& autosave) {
const int team = g.manager_teams.at(size_t(manager));
// HasNoEquivalentCondition: button states (block Desktops, 0x10 bytes per button, 0x360 per manager)
const int mode = g.memory.has(::bmh::layout::GameMode) ? g.memory.u8(::bmh::layout::GameMode) : 0;
const int mode2 = g.memory.has(::bmh::layout::CareerDuration) ? g.memory.u8(::bmh::layout::CareerDuration) : 0;
if (g.memory.has(::bmh::layout::Desktops))
for (int b = 1; b < 0x36; b++) {
const uint32_t at = ::bmh::layout::Desktops + uint32_t(b) * 0x10 + uint32_t(manager) * 0x360 + 1;
uint8_t v = uint8_t(g.memory.u8(at) & 0xf);
// EN AlwaysHidesRecordIndoorTableIncluding always hides record 10 (IndoorTable), including
// Modus III. DE HasNoEquivalentCondition has no equivalent condition.
if ((kEnglishCompetitions && b == 10) ||
(team == no_team() && kButtons[b] == 0) || (mode < 3 && kButtons[mode * 0x36 + b] == 0) ||
(b == 0x16 && mode2 == 1 && g.date < 0x16e))
v |= 0x10;
g.memory.set8(at, v);
}
modern::stir_random(game, rand); // StirRandom
if (team != no_team()) {
std::array<uint8_t, 24> buf;
modern::table_prediction(g, team, 1, buf);
}
// The autosave: at the first manager's desk a new month code (CareerSession_PairingsRuntimeDraw_ExecutableField5) counts one
// more month (DeskRuntimeField5); every Desk_EnterDesk_RuntimeField months (a setting, byte 0x61 of block
// LeaguePresentationOptions, 0 = off) the game saves itself as AUTOSAVE (MakeSavegame)
if (manager == 0) {
const int month = modern::month_code(g.date);
if (g.autosave_month != month) g.autosave_month = month, g.autosave_months++;
}
const int period = g.memory.has(::bmh::layout::LeaguePresentationOptions) ? g.memory.u8(::bmh::layout::Desk_EnterDesk_RuntimeField) : 0;
if (period != 0 && g.autosave_months != 0 && g.autosave_months % period == 0) {
if (autosave) autosave(g, rand);
else modern::save_game_draws(rand); // unpresented/headless legacy model
g.autosave_months = 0;
}
// (the warnings of Fill are display only)
modern::update_prestige(g, manager);
// At the "Saisonende" desk (CareerSession_RuntimeError_RuntimeField4): the main sponsor's minimal goal (record
// +0x176, a table place). Missed: "Ihnen entgehen Sponsorgelder, da Sie das Minimalziel
// (<goal>. Platz) nicht erreicht haben." Reached: (4 - league) * 50000 per place better
// than the goal plus one (the third divisions count as the second), booked as income.
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(manager) * 0xB0C;
const int goal = r.at(rec + 0x176);
if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0 && goal != 0) {
const int place = int16_t(modern::table_position(g, team)) + 1; // TablePosition
std::string text;
if (goal < place) {
text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer5) + format_number(g, goal, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer6);
} else {
int league = int8_t(r.at(rec + 0x210)); // CareerSession_BeginFriendlyOpponentTable_RuntimeField2
if (league > 2) league--;
const int32_t amount = (4 - league) * 50000 * (goal - place + 1);
modern::book_money(g, manager, -amount, true, true); // BookMoney2 with FinanceStatisticsEnabled
text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer2) + format_number(g, amount, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) +
format_number(g, place, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer3) + format_number(g, goal, 1) +
message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer4);
}
post_composed(g, manager, text);
r.at(rec + 0x176) = 0;
}
}
} // namespace bmh::modern
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/desk.hpp"
// Entering a human manager's desk (DeskDate, the part before the desk screen).
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
#include <functional>
namespace bmh::modern {
// DeskDate up to the screen: the desk buttons (HasNoEquivalentCondition), the random stir when a
// screen is entered (StirRandom), the table prediction with its season goal messages
// (Void5 mode 1), the autosave every Desk_EnterDesk_RuntimeField months and the manager's
// prestige (UpdatePrestige).
// Source save operation at the desk boundary. A successful writer owns exactly
// the normal four Save draws; failure before opening the file owns none.
void enter_desk(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand,
const DeskAutosaveHook& autosave = {});
// The draws of saving a game (MakeSavegame): the savegame id (two WatcomRandom(0, 0x8fff))
// and two bytes WatcomRandom(0, 0xff). Everything else the save writes is not saved itself.
void save_game_draws(WatcomRandom& rand);
// UpdatePrestige: prestige of a human manager (record +0x211), a weighted sum of his two
// manager ratings (+0x8b2 25 %, +0x8aa 50 %), his money (15 %) and record +0x26f (10 %).
void update_prestige(ModernState& g, int manager);
} // namespace bmh::modern
File diff suppressed because it is too large. Load diff
+354
View File
@@ -0,0 +1,354 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/desk_actions.hpp"
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// Actions a human manager can take at his desk that change the game state and draw random
// numbers (BMH.exe V2.24 + supported rule profile patch). The screens themselves belong to the UI; these
// functions are what happens when the manager confirms.
#include <array>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
#include "game/human_buyer_sale.hpp"
#include "modern/game/club_player_detail.hpp"
namespace bmh::modern {
// The eight training camp resorts of BookTrainingCamp (names DeskActionsRuntimeField7).
constexpr int kTrainingCampResorts = 8;
// Resort names, qualities and prices are edition content, not shared rules.
// Install the loaded executable's tables after creating or loading a ModernState.
void configure_training_camp_data(ModernState&, const LeImage&);
// DeskDate / menu 6 friendship booking. `manager_home` selects which team is first in
// the saved pair; the manager of the home team pays the source cost. The national-team
// source-qualified overload below handles pseudo-team ratings and their W/G RNG separately.
// Source-qualified menu-6 national friendly owner. The UI/session supplies the
// revision and request identity; the engine binds them to the selected runtime nation.
// Pure source-derived quote for the pre-calendar price/venue prompt. It performs no writes
// or RNG draws. Bind this quote to the UI request ID/revision until the user chooses a day.
FriendlyBookingQuote quote_friendly_match(const ModernState& g, int manager, int opponent,
bool manager_home);
// Original menu-6 national quote. A successful accepted quote advances W exactly for
// QuoteNationalFriendlyMatch's ratings. Preview runs the same calculation on a copy and never advances W.
NationalFriendlyQuote quote_national_friendly_match(const ModernState& g,
const NationalFriendlyOwner&, int opponent, bool manager_home, WatcomRandom& rand);
NationalFriendlyQuote preview_national_friendly_match(const ModernState& g,
const NationalFriendlyOwner&, int opponent, bool manager_home, const WatcomRandom& rand);
FriendlyDateStatus national_friendly_match_date_status(const ModernState&,
const NationalFriendlyQuote&, const NationalFriendlyOwner&, const WatcomRandom&,
uint16_t season_day);
NationalFriendlyBookingResult book_national_friendly_match(ModernState&,
const NationalFriendlyBookingRequest&, const WatcomRandom&, GameRandom&);
// Conservative saved-state projection for days 0..365. `available_with_calendar_event` is
// the source color class for a selectable day whose calendar word has 0x1c0 set. The
// original calendar also carries a transient, sequentially projected bit 15 that is not in
// ModernState; dates with ambiguous neighboring calendar flags may therefore be over-rejected.
FriendlyDateStatus friendly_match_date_status(const ModernState& g,
const FriendlyBookingQuote& quote,
uint16_t season_day);
// Book the accepted quote on the chosen day atomically. The quote is recomputed and must
// still match; approval is explicit. A successful home booking permanently debits the fee
// and records expense-other (+0x8a0). No RNG is used for club-vs-club bookings.
FriendlyBookingResult book_friendly_match(ModernState& g, const FriendlyBookingRequest& request);
// UI-free human transfer actions (menu 17). List-entry indices address the 44-entry
// transfer table; money and contracts are stored in the normal engine state.
// Authenticated lender snapshot -> real borrower squad identity. This is preview
// only; the snapshot never becomes a listing/sale row.
std::optional<TransferMarketSnapshotPreview> transfer_market_snapshot_preview(
const ModernState&,int manager,int runtime_club,int snapshot_index);
// TransferMarketScreen quote identity: ordinary Native slot, or an explicitly authenticated
// lender snapshot mapped by the read-only resolver above.
// No Native writes or G draws. W is0 or1 (42307 fallback). The owner stages W
// and rolls it back on unsupported/exception; repeated-hover caching belongs
// to that owner, not to this primitive or a render method.
TransferMarketPreviewResult quote_transfer_market_preview_source(
const ModernState& g,const TransferMarketPreviewRequest& request,WatcomRandom& rand);
// Exact ordinary OpenTransferEditor/KB31 state owner. UI events contain calculator
// results in Native units; all quotes and Native row writes belong here.
TransferOfferEditorState open_transfer_offer_editor_source(ModernState&,
const TransferOfferEditorRequest&,GameRandom&,WatcomRandom&);
TransferOfferEditorState edit_transfer_offer_editor_source(ModernState&,
const TransferOfferEditorState&,const TransferOfferEditorEvent&,GameRandom&,WatcomRandom&);
// OpenTransferEditor TeamInfo return: 1c5b7 -> 1c186 -> 1c18b. Rescan and
// redraw the current row, preserving initial percent/G. A first empty selection
// initializes only fee/salary/term once; all seven Native bonus bytes survive.
TransferOfferEditorState resume_transfer_offer_team_info_source(ModernState&,
const TransferOfferEditorState&,WatcomRandom&);
// OpenTransferEditor:6936..6953 resolves the direct footer's actual player slot.
// Unmanaged sellers use the Native pool slot; managed sellers use the first
// masked-ID match in their real 24/16-slot squad. The opened owner retains
// Source local40; stale retained rows reject instead of silently reselecting.
ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const ModernState&,
const TransferOfferEditorState&);
// After player information returns: zero return flags preserve the entire editor and quote;
// otherwise rescan/requote by rebuilding the quote without repeating the initial G draw.
TransferOfferEditorState resume_transfer_offer_player_info_source(ModernState&,
const TransferOfferEditorState&,uint8_t player_info_primary_refresh,uint8_t player_info_secondary_refresh,WatcomRandom&);
TransferOfferEditorState cancel_transfer_offer_editor_source(const ModernState&,
const TransferOfferEditorState&);
TransferOfferEditorSubmitResult submit_transfer_offer_editor_source(ModernState&,
const TransferOfferEditorState&,WatcomRandom&,const HumanBuyerSaleHooks&,MinuteReport&);
// Submit a manager bid on an existing list entry. A full-value fee and salary meeting
// the demand complete an immediate agreement; lower viable offers persist for weekly review.
TransferActionResult submit_transfer_bid(ModernState& g, const TransferBidRequest& request, WatcomRandom& rand);
// Explicit opt-in Source SubmitTransferBidSourceHumanBuyer ordinary bid-submit path. Unlike the legacy
// overload, the caller owns staged Native/W state, supplies the exact source
// pool slot, actual career mode is present in Native, and the session provides
// its allocator/entry ownership plus Original notice presenter. Source-approved
// AI/free-agent purchases use the exact shared settlement; other sellers retain
// a pending bid. Unsupported contexts require caller rollback.
TransferActionResult submit_transfer_bid_source_human_buyer(ModernState& g,
const TransferBidRequest& request, WatcomRandom& rand,
const HumanBuyerSaleHooks& hooks, MinuteReport& report);
// Put one of the manager's squad rows on the list. The request consumes the original
// listing-price RNG and returns the new stable entry index through the result.
TransferActionResult list_manager_player(ModernState& g, int manager, int squad_row,
WatcomRandom& rand, MinuteReport& report);
// SetTrainingCampFocus: persist the four focus sliders (+0xc1..+0xc4) without drawing or
// applying training. Rejects an invalid manager or any value outside the original 0..15 range.
bool set_training_camp_focus(ModernState& g, int manager, const std::array<uint8_t, 4>& focus);
// BookTrainingCamp controller gates, before payment and training effects.
TrainingCampBookingBlock training_camp_booking_block(const ModernState& g, int manager);
// Text: price of a stay at `resort` for the manager's team - the resort's base
// price (DeskActions_ConfigureTrainingCampData_RuntimeField2 of the loaded game) plus 5 000 per player of the squad
// (QuoteNationalFriendlyMatch with 0xff, the player count). Draws nothing.
int32_t training_camp_price(const ModernState& g, int manager, int resort);
// BookTrainingCamp on "Buchen": the price is booked (BookMoney2, not forced). If the money is
// there, record +0x890 (training camp expenses) grows by it, record +0x21f counts the stays
// (bit 7 = "already in a camp this week", cleared by the day step) and the camp takes
// effect (training_camp_effect). Returns false if the booking failed. The four focus
// sliders (record +0xc1..+0xc4, 0..15) are set on the screen before.
// The screen allows a booking only if bit 7 of +0x21f is clear and fewer than 3 stays
// were made (+0x21f & 0x7f < 3) - checked by the caller.
bool book_training_camp(ModernState& g, int manager, int resort, WatcomRandom& rand);
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// TrainingCampEffect (with the supported rule profile patch TrainingCampEffect2 / TrainingCampEffect3 / TrainingCampEffect4): the
// effect of a training camp. The team morale rises by 12 * quality * 20 % (clamped to
// 0..47), then every player of the squad may improve in condition, technique, form,
// familiarity (tactics board +0xf) and freshness (board +0x0e bits 0-5). See the .cpp.
// Ends with the message DeskActionsRuntimeField8 (SystemIdentity, no draws).
void training_camp_effect(ModernState& g, int manager, int resort, WatcomRandom& rand);
} // namespace bmh::modern
namespace bmh::modern {
// The stock exchange screen MaxSharesToBuy (bank button). The twelve shares are entries of
// 0x5c bytes in GameState::stocks (StockExchange): +0x00 long-term value (u32, price * 100),
// +0x04 + manager * 4 the amount the manager paid for his shares (u32), +0x16 trend byte,
// +0x4e current price (u16), +0x50 + manager * 2 shares held (u16), +0x59 age of the trend.
constexpr int kStocks = 12;
// Largest number of shares of `stock` the manager may buy: (money + credit line) / price,
// with at most 9999 shares of one company.
int max_shares_to_buy(const ModernState& g, int manager, int stock);
// Buying `count` shares: the price times count plus 1.5 % fee is booked (BookMoney2, not
// forced) - but only while the paid amount of all shares held stays below 5 % of the
// money (record +0x314 / 20), else the message Bank_OriginalToUtf8_TextPointer8 ("too much") and nothing
// happens (returns false). Record +0x324 (stock balance) falls by the amount.
bool buy_shares(ModernState& g, int manager, int stock, int count);
// Selling `count` shares at the current price: the paid amount shrinks by its average per
// share, the money (forced booking) and record +0x324 rise.
void sell_shares(ModernState& g, int manager, int stock, int count);
// The "Tip" button (costs 5 000, booked forced with statistics): 0 (sell) .. 4 (buy),
// from the trend byte and the price against the long-term value, then with chance 1/3
// moved by -2, 0 or +2 (WatcomRandom(0, 2) twice). The text is Bank_FormatError_RuntimeField19[tip].
int stock_tip(ModernState& g, int manager, int stock, WatcomRandom& rand);
} // namespace bmh::modern
namespace bmh::modern {
// The stadium screen ConstructionPricePercent (stadium button) - the parts that draw numbers or book.
// The manager record holds 14 periphery objects (+0x00..+0x0d condition, +0x1e..+0x2b
// construction weeks), eight Facility/Maintain investments (+0x0e.. condition,
// +0x2c.. construction weeks, +0x3c.. current/pending level), and eight stand blocks
// (+0x34.. construction weeks, +0x44.. seat/roof flags, +0x4c.. current capacity in
// thousands, +0x54.. future capacity). These are distinct Source branches.
// On opening: the game generator restarts from the saved seed CareerSession_Invalid_RuntimeField2 and draws the
// building company's discount, DeskActionsRuntimeField9 = 100 - G(r / 100, r / 100 + 5) with r =
// record +0x8b4 (int16). Returns the price percentage (100 - discount).
int construction_price_percent(const ModernState& g, int manager, GameRandom& game);
// The offer for periphery object `object` (0..13) when it is clicked: the game generator
// restarts from CareerSession_Invalid_RuntimeField2, draws G(0, 100) once per object before it and then the
// price percentage G(85, 115); price = base (StadiumPriceTable) * percentage / 1 000 000 *
// 10 000.
int32_t periphery_offer(const ModernState& g, int object, GameRandom& game);
// PayConstruction: pays a construction. With `sponsor` and a sponsor share (record +0x171)
// the price is reduced once - by ((share >> 5) + 3) * 10 % below a limit of ((share >> 2)
// & 7) * 325 000 + 26 000, else by WatcomRandom(2, 4) * 5 % ("Der Sponsor fühlt sich
// ausgenutzt") - and the share is cleared. Booked with statistics, not forced.
// PayConstruction presents the sponsor notice before clearing+171. A genuine
// BookMoney2 refusal presents funds after that clearing. Presenter exceptions
// propagate; the caller owns the whole transaction checkpoint/rollback.
bool pay_construction(ModernState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand,
const ConstructionNoticeHook& notice = {});
// "Ja" on the offer: pay_construction(price, sponsor) and the construction time of the
// object (CareerSession_DispatchStadium_RuntimeField2[object * 5]) is entered at record +0x1e + object.
bool build_periphery(ModernState& g, int manager, int object, uint32_t price, WatcomRandom& rand,
const ConstructionNoticeHook& notice = {});
// PrepareStandBlockOffer, before its Yes/No prompt: consumes exactly W(6,14) and returns the
// percentage and quoted price. The quote is a value; displaying it consumes no more RNG.
// The path has not been compared with a matching original recording.
StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand);
// Resolve the PrepareStandBlockOffer answer once. No leaves the base price/time and draws nothing;
// Yes applies the quoted price and consumes exactly W(days>>3, days>>1) to shorten time.
// Repeated resolution is ignored, so a duplicated input cannot consume another draw.
bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand);
// ConstructionPricePercent choices 0..7: TEXTD734..741. Choices 8..15 are separate stand
// expansion editors and must never use the Facility/Maintain record arithmetic.
// Pure projection. Busy or terminal investments have no options. Invalid owner,
// constants or a nonzero idle high nibble raise FormatError. Heating/VIP offer
// one tier unless (raw status &7)==2, including raw0. Ordinary tiers start at
// the full raw status byte and stop before5; bit3 yields no ordinary options.
// target_level is the accepted level after weekly completion's &7 narrowing.
std::vector<StadiumInvestmentOption> stadium_investment_options_source(
const ModernState&, int manager, StadiumInvestment, int construction_percent,
const StadiumInvestmentConstants&);
// Revalidate the owned option against the current record and trusted Original
// constants before payment. Both resolved tip answers build: Declined means no
// tip, not cancel. Source sponsor draws/consumption can precede payment refusal;
// only successful payment writes +2c/+3c. No actual block capacity/flags
// (+34/+44/+54), GameRandom or weekly compensation is touched.
bool build_stadium_investment_source(ModernState&, int manager, StadiumInvestment,
int construction_percent, const StadiumInvestmentConstants&,
const StadiumInvestmentOption&, const StandBlockOffer& resolved_tip, WatcomRandom&,
const ConstructionNoticeHook& notice = {});
// LeagueTableRangeDialog: persist the active 11-match pools coupon. The stake sits at
// Coupon + manager*0x14 and picks at +8..+0x12. Money is only charged by
// settle_pools_coupon at matchday end; this confirmation itself draws no RNG.
// BuildPoolsCoupon makes the screen unavailable unless all eleven fixtures exist.
// BalanceFromGame bounds stake to 10,000..400,000 (zero clears it).
bool submit_pools_coupon(ModernState& g, int manager, uint32_t stake,
const std::array<uint8_t, 11>& tips);
} // namespace bmh::modern
namespace bmh::modern {
// Source-backed advertising contracts (DeskActionsOperation/CheckAdvertisingRenewal). Offers are
// generated elsewhere and live in the manager's saved +0x8cc pool. Projection
// is read-only: it never generates offers or consumes RNG.
// A group of identical offers may require several boards. Empty boards and rows
// marked replaceable by source flag +6 bit 7 count toward capacity.
AdvertisingOfferList advertising_offers(const ModernState& g, int manager, int display_slot);
// Accept an existing offer atomically. Board rows are source-sorted before the
// bundle is installed; the group byte at +4 receives AdGroupId and that counter
// advances once. Shirt/TV offers replace their corresponding slot. This commit
// books no immediate cash and draws no RNG. Option-extension offers are excluded.
AdvertisingOfferResult accept_advertising_offer(ModernState& g,
const AdvertisingOfferRequest& request);
// CheckAdvertisingRenewal: a click on a contract whose months ran out (sponsor set, months 0 - the
// month change posted "kann verlängert werden", Month_MonthChange_TextPointer). The sponsor's demand (word
// +8, the club attraction it wants) is scaled by W(95, 105) % (WatcomRandom); if it stays
// below the club's attraction (ClubAttraction) the manager is asked "Möchten Sie den Vertrag
// mit <sponsor> verlängern ?" (DeskActions_CheckAdvertisingRenewal_TextPointer/DeskActions_CheckAdvertisingRenewal_TextPointer2), otherwise the sponsor declines ("Die Firma
// <sponsor> wird den Vertrag nicht verlängern.", DeskActions_CheckAdvertisingRenewal_TextPointer3..DeskActions_CheckAdvertisingRenewal_TextPointer5, a mailbox message) and the
// place becomes free. Step one draws the random number and settles the refusal; step two
// applies the manager's answer: yes = the old duration again (byte +6 & 0x7f), no = free.
// Either way byte +6 is cleared and the other boards of the same bundle (group byte +4)
// get a copy of the result.
AdvertisingRenewal check_advertising_renewal(ModernState& g, int manager, int display_slot, WatcomRandom& rand);
bool answer_advertising_renewal(ModernState& g, int manager, int contract_slot, bool renew);
// CheckAdvertisingRenewal advertising spend fields (manager record +0x850/+0x854/+0x858,
// delivery countdown +0x287). Projection is read-only; only goods purchasing draws.
AdvertisingSpendingView advertising_spending(const ModernState& g, int manager, int target_slot);
AdvertisingSpendingResult set_advertising_spending(ModernState& g,
const AdvertisingSpendingRequest& request,
WatcomRandom& rand);
} // namespace bmh::modern
namespace bmh::modern {
// The funds of the same screen (block FundBlock in GameState::memory, six entries of 0x1c
// bytes): +0x00 price of a unit ((1 << k) * 100 000), +0x04 + manager * 4 the amount the
// manager paid (u32), +0x14 + manager * 2 units held (u16, at most 10 per fund).
constexpr int kFunds = 6;
// Units of fund `fund` the manager can buy: (money + credit line) / (price * 1.05), at most
// 10 minus the units held.
int max_fund_units(const ModernState& g, int manager, int fund);
// Buying `count` units: price * count plus 5 % fee is booked (not forced) - record +0x324
// falls by it, record +0x30c rises by the fee and by price * count / 9. Every fund but
// the first costs a surcharge as well: count * G(price / 40, price / 10), paid (forced) and
// added to +0x30c, with the message CareerSession_Int32T_TextPointer2. Returns the surcharge.
int32_t buy_fund_units(ModernState& g, int manager, int fund, int count, GameRandom& game);
// Selling `count` units at the price: the paid amount shrinks by its average per unit, the
// money (forced) and +0x324 rise, +0x30c falls by price * count / 9.
void sell_fund_units(ModernState& g, int manager, int fund, int count);
// The fixed-term deposit (record +0x318): a positive amount moves money from the account
// to the deposit, a negative one back (both booked forced; +0x324 changes by the same).
// The deposit earns interest in daily_interest.
void move_to_deposit(ModernState& g, int manager, int32_t amount);
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// NormalizePitchSetPieceSource (supported rule profile patch), when the line-up screen opens (PitchScreen, desk menu 3 and
// before matches): a manager record without the set-piece marker 0x3253 at +0xb0a gets it,
// with the takers cleared (+0xafc..+0xaff = 0, +0xb08 = designated-taker signature).
void open_lineup_screen(ModernState& g, int manager);
} // namespace bmh::modern
+280
View File
@@ -0,0 +1,280 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/game/driver.hpp"
#include "modern/game/modern_state.hpp"
#include <algorithm>
#include <array>
#include <vector>
#include "modern/game/matchday.hpp"
#include "modern/game/matchday_setup.hpp"
#include "modern/game/season.hpp"
namespace bmh::modern {
int cup_tie(const MatchGroup& grp, int m) {
const uint16_t r = grp.cup_results.at(size_t(m));
int home = r >> 5 & 0x1F, away = r & 0x1F;
int other_home = 0, other_away = 0;
if (!grp.cup_other_leg.empty()) {
other_home = grp.cup_other_leg.at(size_t(m)) >> 5 & 0x1F;
other_away = grp.cup_other_leg.at(size_t(m)) & 0x1F;
}
// this match's home team was the away team of the other leg
if ((grp.flags() & 0x10) && other_home + away == home + other_away && (r >> 11) == 0) {
away *= 2; // away goals of this match ...
other_away *= 2; // ... and of the other leg count double
}
const int home_total = home + other_away, away_total = other_home + away;
return (unsigned(home_total) < unsigned(away_total) ? 1 : 0) + (home_total == away_total ? 2 : 0);
}
bool cup_screen_shown(const std::vector<uint8_t>& buttons, int cup_id, int minute) {
if (buttons.empty()) return true;
const int kind = (minute > 45) + 1;
const int row = cup_id + 5;
if (row == 0x12) return buttons.at(size_t(0x12 + kind)) == 0 || buttons.at(size_t(0x1b + kind)) == 0;
return buttons.at(size_t(kind + row * 9)) == 0;
}
void play_phase(MatchEngine& engine, std::vector<MatchGroup>& groups, int first, int last, int stoppage, int phase,
MinuteReport& report, const std::function<void(int)>& after_minute) {
for (MatchGroup& grp : groups) grp.ended = 0, grp.phase = phase;
for (int minute = first; minute <= last + stoppage && !report.unsupported; minute++) {
bool running = false;
for (const MatchGroup& grp : groups)
for (int m = 0; m < grp.matches(); m++)
if (!((grp.void_mask() | grp.ended) >> m & 1)) running = true;
if (!running) break; // the original leaves the phase after a minute without matches
report = engine.minute(minute, last, stoppage);
if (after_minute) after_minute(minute);
}
}
namespace {
void set_void(MatchGroup& grp, int m) {
const uint32_t v = grp.void_mask() | 1u << m;
for (int i = 0; i < 4; i++) grp.desc.at(0xb8 + size_t(i)) = uint8_t(v >> (8 * i));
}
} // namespace
namespace {
bool group_played(const MatchGroup& grp) {
for (int m = 0; m < grp.matches(); m++)
if (grp.ended >> m & 1) return true;
return false;
}
bool result_visible(ModernState& g, const MatchGroup& grp, int last,
const std::vector<uint8_t>& buttons, PhaseResultKind& kind,
int& competition_id) {
const uint32_t id = le32(grp.desc, 0xcc);
if (id < 0x15) {
kind = PhaseResultKind::League;
competition_id = int(id);
return modern::league_screen_shown(buttons, 2, last, int(id));
}
kind = PhaseResultKind::Cup;
competition_id = int16_t(g.memory.u16(id + 0x18));
return modern::cup_screen_shown(buttons, competition_id, last);
}
PhaseResultRequest make_result_request(const MatchGroup& grp, uint64_t phase_id,
uint32_t group_index, uint64_t revision,
PhaseResultKind kind, int competition_id, int last) {
PhaseResultRequest req;
req.phase_id = phase_id;
req.group_index = group_index;
req.revision = revision;
req.kind = kind;
req.competition_id = competition_id;
req.phase_end_minute = last;
req.matches.reserve(size_t(grp.matches()));
for (int m = 0; m < grp.matches(); ++m) {
PhaseResultMatch score;
score.home_team = grp.fixtures.at(size_t(m * 2));
score.away_team = grp.fixtures.at(size_t(m * 2 + 1));
score.score_known = modern::match_score(grp, m, score.home_score, score.away_score);
req.matches.push_back(score);
}
return req;
}
void finish_group_phase(ModernState& g, MatchGroup& grp, int last, GameRandom& game) {
const bool full_time = last == 90 || last == 120 || last == 40;
if (!full_time) return;
const bool final_phase = last == 40 || last == 120;
for (int m = 0; m < grp.matches(); m++) {
if ((grp.flags() & 8) && modern::cup_tie(grp, m) == 2) {
uint16_t& r = grp.cup_results.at(size_t(m));
if (r != 0xCCCC) r = uint16_t((final_phase ? 2 : 1) * 0x400 + (r & 0x3FF));
if (final_phase) modern::finish_match(g, grp, m, last, game);
continue;
}
if (grp.void_mask() >> m & 1) continue;
modern::finish_match(g, grp, m, last, game);
set_void(grp, m);
}
}
PhaseEndOutput rejected(const char* why) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Rejected;
out.reason = why;
return out;
}
PhaseEndOutput advance_phase_end(PhaseEndCursor& c) {
while (c.next_group < c.groups->size()) {
MatchGroup& grp = c.groups->at(c.next_group);
if (c.phase_played) {
PhaseResultKind kind;
int competition_id = 0;
if (result_visible(static_cast<ModernState&>(static_cast<ModernState&>(*c.state)), grp, c.last, c.buttons, kind, competition_id)) {
c.pending = make_result_request(grp, c.phase_id, c.next_group, c.revision,
kind, competition_id, c.last);
// CupGroupOverviewEffects initializes the cup viewer before presenting it.
// Keep this once at entry, so closing cannot erase viewer edits.
if (kind == PhaseResultKind::Cup) modern::cup_overview_effects(static_cast<ModernState&>(*c.state));
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
}
finish_group_phase(static_cast<ModernState&>(static_cast<ModernState&>(*c.state)), grp, c.last, *c.game);
++c.next_group;
}
c.complete = true;
c.pending.reset();
PhaseEndOutput out;
out.status = PhaseEndStatus::Complete;
return out;
}
} // namespace
PhaseEndOutput begin_phase_end(PhaseEndCursor& c, uint64_t phase_id, ModernState& g,
std::vector<MatchGroup>& groups, int last,
const std::vector<uint8_t>& buttons, GameRandom& game,
WatcomRandom& rand, MinuteReport& report) {
if (c.initialized) {
const bool same = c.phase_id == phase_id && c.state == &g && c.groups == &groups && c.last == last &&
c.buttons_source == &buttons && c.game == &game && c.rand == &rand && c.report == &report;
if (!c.complete) {
if (!same) return rejected("phase already active with different identity or borrowed objects");
if (c.pending) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
return rejected("active phase has no pending result");
}
if (same) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Complete;
return out;
}
}
c.initialized = true;
c.complete = false;
// Original local_48 belongs to EndPhase, not to a group. Preserve this
// gate throughout the barrier even as each acknowledged group settles.
c.phase_played = std::any_of(groups.begin(), groups.end(), group_played);
c.phase_id = phase_id;
c.revision = 1;
c.next_group = 0;
c.last = last;
c.buttons = buttons;
c.buttons_source = &buttons;
c.state = &g;
c.groups = &groups;
c.game = &game;
c.rand = &rand;
c.report = &report;
c.pending.reset();
c.last_ack.reset();
c.after_last_ack.reset();
return advance_phase_end(c);
}
PhaseEndOutput continue_phase_end(PhaseEndCursor& c, const std::optional<PhaseResultReply>& reply) {
if (!c.initialized) return rejected("phase not started");
if (!reply) {
if (c.complete) return rejected("phase already complete");
if (!c.pending) return rejected("no result is pending");
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
if (c.last_ack && reply->phase_id == c.last_ack->phase_id &&
reply->group_index == c.last_ack->group_index && reply->revision == c.last_ack->revision) {
return *c.after_last_ack;
}
if (c.complete) return rejected("phase already complete");
if (!c.pending || reply->phase_id != c.pending->phase_id ||
reply->group_index != c.pending->group_index || reply->revision != c.pending->revision)
return rejected("stale or mismatched result acknowledgement");
MatchGroup& grp = c.groups->at(c.pending->group_index);
if (c.pending->kind == PhaseResultKind::League) {
modern::stir_random(*c.game, *c.rand);
}
finish_group_phase(static_cast<ModernState&>(static_cast<ModernState&>(*c.state)), grp, c.last, *c.game);
c.next_group = c.pending->group_index + 1;
c.last_ack = *reply;
++c.revision;
c.pending.reset();
PhaseEndOutput out = advance_phase_end(c);
c.after_last_ack = out;
return out;
}
void end_phase(ModernState& g, std::vector<MatchGroup>& groups, int last, const std::vector<uint8_t>& buttons,
GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const PhaseResultRequest&, const std::vector<MatchGroup>&,
const ModernState&)>& presenter) {
PhaseEndCursor cursor;
PhaseEndOutput out = modern::begin_phase_end(cursor, 1, g, groups, last, buttons, game, rand, report);
while (out.status == PhaseEndStatus::Waiting && out.request) {
const PhaseResultRequest& req = *out.request;
if (presenter) presenter(req, groups, g);
out = modern::continue_phase_end(cursor, PhaseResultReply{req.phase_id, req.group_index, req.revision});
}
}
void play_matchday(MatchEngine& engine, ModernState& g, std::vector<MatchGroup>& groups,
const std::vector<uint8_t>& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(int)>& after_minute, int stop_at) {
// EndPhase calls of the matchday: outdoors two halves (4 minutes of stoppage in the
// second) and extra time; the indoor tournament (CareerSessionRuntimeField) plays 2 x 20 minutes
const int outdoor[4][4] = {{1, 45, 0, 0}, {46, 90, 4, 0}, {91, 105, 0, 1}, {106, 120, 1, 1}};
const int indoor[2][4] = {{1, 20, 0, 0}, {21, 40, 0, 0}};
engine.indoor = g.indoor;
std::vector<std::array<int, 4>> phases;
if (g.indoor)
for (const auto& p : indoor) phases.push_back({p[0], p[1], p[2], p[3]});
else
for (const auto& p : outdoor) phases.push_back({p[0], p[1], p[2], p[3]});
for (const auto& p : phases) {
modern::play_phase(engine, groups, p[0], p[1], p[2], p[3], report, after_minute);
if (report.unsupported) return;
if (p[1] == stop_at) return;
modern::end_phase(g, groups, p[1], buttons, game, rand, report, engine.phase_results);
if (report.unsupported) return;
// FinishEvent / BuildSideRecords: EvaluatePoolsCoupon(0) after the second half (outdoors)
if (!g.indoor && p[1] == 90) modern::evaluate_pools_coupon(g, groups);
}
// CupTie2: penalty shoot-outs
for (MatchGroup& grp : groups)
for (int m = 0; m < grp.matches() && !report.unsupported; m++)
if ((grp.flags() & 8) && !grp.cup_results.empty() && (grp.cup_results[size_t(m)] >> 11) != 0)
engine.penalty_shootout(grp, m, report);
}
} // namespace bmh::modern
+79
View File
@@ -0,0 +1,79 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/driver.hpp"
// The matchday driver after the kick-off (FinishEvent + BuildSideRecords, BMH.exe V2.24).
//
// The driver plays the phases one after another with EndPhase(first, last,
// stoppage, phase):
// 1..45 (no stoppage), 46..90 (+ up to 4), then 91..105 and 106..120 (+ up to 1,
// phase 1 = extra time; indoor tournaments play 1..20 and 21..40 instead).
// A phase ends when every match has ended; a phase in which no match is running draws
// nothing. At the end of a phase (end_phase):
// - if any match played in the phase, the result screen of every group is called
// unless switched off at the desk, including groups already settled in regular
// time; leaving a league screen stirs the random numbers (stir_random),
// - at full time (90, 120, and 40 indoors) every match gets FinishMatch and is marked
// done, except cup ties decided on the day (descriptor flag 8) that are still level
// on aggregate (cup_tie): they go into extra time, after 120 minutes into the
// penalty shoot-out (CupTie2).
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// CupTie: state of a cup tie after match m of a group: 0 the home side is through,
// 1 the away side, 2 still level. Two-legged ties add the other leg (its home team is
// this match's away team); with descriptor flag 0x10 away goals count double while the
// match is in regular time.
int cup_tie(const MatchGroup& grp, int m);
// Whether the result screen of a cup (CupGroupOverviewEffects with a phase end minute) is shown.
bool cup_screen_shown(const std::vector<uint8_t>& buttons, int cup_id, int minute);
// One phase: minutes first..last+stoppage until every match has ended. `after_minute`
// is called after each simulated minute (for checks). Stops early if the engine reports
// an unsupported path.
void play_phase(MatchEngine& engine, std::vector<MatchGroup>& groups, int first, int last, int stoppage, int phase,
MinuteReport& report, const std::function<void(int minute)>& after_minute = {});
// The end of EndPhase for a phase that ended at minute `last`.
void end_phase(ModernState& g, std::vector<MatchGroup>& groups, int last, const std::vector<uint8_t>& buttons,
GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const PhaseResultRequest&, const std::vector<MatchGroup>&,
const ModernState&)>& presenter = {});
// Nonblocking end-of-phase result barrier. The cursor borrows the original mutable
// objects for its whole lifetime; do not copy/move it or independently mutate those
// objects while pending. Native viewer actions use the owning synchronous App dispatcher;
// it must preserve group identity and never resume simulation. Cup entry effects precede
// presentation; league exit RNG and match settlement belong to the single ACK.
// Only presentation metadata and a bounded last-ACK record are owned.
// First call starts/resumes the phase; repeating begin with the same phase while waiting
// polls the identical request. A completed cursor may be reused for a later phase.
PhaseEndOutput begin_phase_end(PhaseEndCursor& cursor, uint64_t phase_id, ModernState& g,
std::vector<MatchGroup>& groups, int last,
const std::vector<uint8_t>& buttons, GameRandom& game,
WatcomRandom& rand, MinuteReport& report);
// An empty reply polls without effects. Only an exact current (phase, group, revision)
// reply resumes the group. Duplicate last ACK returns its cached continuation; older or
// mismatched replies are rejected without state/RNG/cursor advancement.
PhaseEndOutput continue_phase_end(PhaseEndCursor& cursor,
const std::optional<PhaseResultReply>& reply = std::nullopt);
// All phases of a matchday (not indoor): regular time, extra time where needed.
// `stop_at` (45, 90, 105 or 120) stops at the whistle of that phase, before its result
// screens and match bookkeeping (end_phase); 0 plays everything.
void play_matchday(MatchEngine& engine, ModernState& g, std::vector<MatchGroup>& groups,
const std::vector<uint8_t>& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(int minute)>& after_minute = {}, int stop_at = 0);
} // namespace bmh::modern
+114
View File
@@ -0,0 +1,114 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include <algorithm>
#include <cstdlib>
namespace bmh::modern {
namespace {
uint32_t youth_at(int manager) { return layout::EnvironmentYouthTeams + uint32_t(manager) * 0x24; }
uint32_t spending_at(int manager, int item) {
return layout::Spending + uint32_t(manager) * 0x24 + uint32_t(item) * 4;
}
void validate_manager(const ModernState& g, int manager) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size() ||
!g.memory.has(youth_at(manager) + 8) || !g.memory.has(spending_at(manager, 5) + 3))
throw FormatError("environment: invalid manager or truncated budgets");
}
int direction(int value) { return (value > 0) - (value < 0); }
int signed_clamp(int value, int low, int high) {
return std::clamp(int(int8_t(uint8_t(value))), low, high);
}
bool legacy_academy(const ModernState& g, int manager) {
const auto value = g.memory.u32(spending_at(manager, kYouthAcademy));
return value == 1500000 || value == 1000000 || value == 580000 || value == 280000;
}
uint32_t academy_paid(const ModernState& g, int manager) {
const auto at = size_t(manager) * 0xb0c + 0x880;
return uint32_t(g.manager_records.at(at)) | uint32_t(g.manager_records.at(at + 1)) << 8 |
uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24;
}
}
int32_t environment_monthly_cost(const ModernState& g, int manager, int item) {
const auto value = g.memory.u32(spending_at(manager, item));
if (item == kYouthAcademy && legacy_academy(g, manager) && academy_paid(g, manager) >= value) return 0;
return int32_t(value);
}
bool environment_academy_active(const ModernState& g, int manager) {
const auto value = g.memory.u32(spending_at(manager, kYouthAcademy));
return value != 0 && (!legacy_academy(g, manager) || academy_paid(g, manager) >= value);
}
EnvironmentState environment_state(const ModernState& g, int manager) {
validate_manager(g, manager);
EnvironmentState result;
for (int i = 0; i < kEnvironmentItems; ++i) {
result.monthly[size_t(i)] = int32_t(g.memory.u32(spending_at(manager, i)));
result.level[size_t(i)] = std::clamp(result.monthly[size_t(i)] / kEnvironmentStep[size_t(i)], 0, 6);
}
for (uint32_t i = 0; i < 3; ++i) {
result.youth_strength[i] = g.memory.u8(youth_at(manager) + i);
result.youth_position[i] = g.memory.u8(youth_at(manager) + 3 + i);
result.youth_league[i] = g.memory.u8(youth_at(manager) + 6 + i);
if (result.youth_position[i] > 11 || result.youth_league[i] > 2)
throw FormatError("environment: invalid youth table");
}
return result;
}
EnvironmentResult set_environment(ModernState& g, int manager, int item, int level, std::string* message) {
if (message) message->clear();
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || item < 0 || item >= kEnvironmentItems ||
level < 0 || level > 6 || !g.memory.has(spending_at(manager, item) + 3))
return EnvironmentResult::invalid;
const auto at = spending_at(manager, item);
const auto value = uint32_t(level * kEnvironmentStep[size_t(item)]);
if (g.memory.u32(at) == value) return EnvironmentResult::unchanged;
g.memory.set32(at, value);
return EnvironmentResult::changed;
}
void advance_youth_teams(ModernState& g, int manager, WatcomRandom& rand) {
const auto observed = modern::environment_state(g, manager);
std::array<uint8_t, 44> movement{};
uint8_t step = 4;
for (auto& value : movement) {
value = step;
if (step != 0 && rand.range(0, 8) == 0) --step;
}
const auto round = g.league_rounds.at(0);
if (round >= movement.size()) throw FormatError("environment: youth round outside season");
constexpr int division_strength[] = {85, 70, 57};
for (size_t i = 0; i < 3; ++i) {
int strength = observed.youth_strength[i];
int position = observed.youth_position[i];
const int opponent = uint8_t(division_strength[observed.youth_league[i]] - position);
const int ratio = strength == 0 ? 100 :
int((((int64_t(observed.monthly[i]) * 100 / ((1 << i) * 10000)) >> 1) + 40) * 100 / strength);
int change = direction(ratio - 100);
if (rand.range(0, 4) == 0) change = rand.range(0, 2) - 1;
if (std::abs(ratio - 100) <= rand.range(0, 30)) change = 0;
if (rand.range(0, 2) == 0) strength = uint8_t(strength + change);
strength = signed_clamp(strength, 10, 85);
g.memory.set8(youth_at(manager) + uint32_t(i), uint8_t(strength));
const int difference = strength - opponent;
change = direction(difference);
if (rand.range(0, 4) == 0) change = rand.range(0, 2) - 1;
if (rand.range(0, 3) != 0 && std::abs(difference) * 2 < rand.range(1, 18)) change = 0;
position = signed_clamp(uint8_t(position - change * rand.range(1, movement[round])), 0, 11);
g.memory.set8(youth_at(manager) + 3 + uint32_t(i), uint8_t(position));
}
}
void finish_youth_season(ModernState& g, int manager) {
const auto observed = modern::environment_state(g, manager);
for (int i = 2; i >= 0; --i) {
auto division = observed.youth_league[size_t(i)];
const int position = observed.youth_position[size_t(i)];
int next_position = 5;
if (position < 2 && division != 0) { --division; next_position = position + 10; }
if (position > 10 && division < 2) { ++division; next_position = position - 10; }
if (i != 0) g.memory.set8(youth_at(manager) + uint32_t(i),
uint8_t((int(observed.youth_strength[size_t(i - 1)]) + observed.youth_strength[size_t(i)] * 2) / 3));
g.memory.set8(youth_at(manager) + 3 + uint32_t(i), uint8_t(next_position));
g.memory.set8(youth_at(manager) + 6 + uint32_t(i), division);
}
}
} // namespace bmh::modern
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/environment.hpp"
#include <array>
#include <cstdint>
#include <string>
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
constexpr int kEnvironmentItems = 6;
// OpenBMH deviates from the original: uses six monthly environment budgets across data editions while retaining the shared staff prices and academy player-generation strength bands.
inline constexpr std::array<int32_t, kEnvironmentItems> kEnvironmentStep = {2000, 4000, 5000, 5000, 5000, 5000};
EnvironmentState environment_state(const ModernState& g, int manager);
// Preserve already saved lump-sum academy contracts until the user edits them.
int32_t environment_monthly_cost(const ModernState& g, int manager, int item);
bool environment_academy_active(const ModernState& g, int manager);
// Set a monthly budget to level 0..6, without an immediate debit or random draw.
EnvironmentResult set_environment(ModernState& g, int manager, int item, int level, std::string* message = nullptr);
// Youth results advance with first-division matchdays. Promotion/relegation and
// the handover to the next age group happen before annual accounts.
void advance_youth_teams(ModernState& g, int manager, WatcomRandom& rand);
void finish_youth_season(ModernState& g, int manager);
} // namespace bmh::modern
+240
View File
@@ -0,0 +1,240 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/highscore.hpp"
#include "formats/native_state.hpp"
#include "formats/native_file.hpp"
#include <algorithm>
#include <bit>
#include <fstream>
#include <stdexcept>
#include <utility>
#include "modern/game/weekly.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xb0c;
// OpenBMH deviates from the original: reads the supported edition-specific high-score format from the loaded image.
// supported rule profile executable HighscoreRuntimeField..a5144, verified against the installed LE image.
constexpr std::array<uint8_t, 8> kHistoryWeights{3, 5, 4, 30, 20, 10, 5, 40};
constexpr std::array<uint8_t, 4> kNationalWeights{30, 20, 10, 5};
constexpr std::array<uint8_t, 3> kTitleWeights{40, 30, 50};
int32_t signed32(uint32_t v) { return std::bit_cast<int32_t>(v); }
uint16_t rec16(const ModernState& g, int m, size_t offset) {
const size_t at = size_t(m) * kRecord + offset;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
uint32_t rec32(const ModernState& g, int m, size_t offset) {
return uint32_t(rec16(g, m, offset)) | uint32_t(rec16(g, m, offset + 2)) << 16;
}
uint8_t rec8(const ModernState& g, int m, size_t offset) {
return g.manager_records.at(size_t(m) * kRecord + offset);
}
std::string record_name(const ModernState& g, int m) {
std::string name;
for (size_t i = 0; i < 30; ++i) {
const auto c = rec8(g, m, 0xa8 + i);
if (!c) return name;
name.push_back(char(c));
}
throw std::invalid_argument("highscore: unterminated manager name");
}
// HighscoreScore(0x1f,0,0xff), deliberately using the Source global asset-manager.
int32_t net_assets(const ModernState& g, int m) {
uint32_t sum = rec32(g, m, 0x314) + rec32(g, m, 0x318);
for (uint32_t k = 0; k < 6; ++k)
sum += uint32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c)) *
g.memory.u32(::bmh::layout::FundBlock + k * 0x1c);
for (size_t k = 0; k < 12; ++k) {
const size_t at = k * 0x5c;
const uint32_t held = uint16_t(g.stocks.at(at + 0x50 + size_t(m) * 2) |
g.stocks.at(at + 0x51 + size_t(m) * 2) << 8);
const uint32_t price = uint16_t(g.stocks.at(at + 0x4e) | g.stocks.at(at + 0x4f) << 8);
sum += held * price;
}
for (uint32_t k = 0; k < 5; ++k)
sum -= g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + k * 0x18);
return signed32(sum);
}
uint32_t read32(const uint8_t* p) {
return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;
}
void put32(uint8_t* p, uint32_t v) {
for (int k = 0; k < 4; ++k) p[k] = uint8_t(v >> (8 * k));
}
std::string read_name(const uint8_t* p) {
size_t n = 0;
while (n < 30 && p[n]) ++n;
if (n == 30) throw std::invalid_argument("highscore: unterminated file name");
return {reinterpret_cast<const char*>(p), n};
}
void put_name(uint8_t* p, const std::string& s) {
if (s.size() >= 30 || s.find('\0') != std::string::npos)
throw std::invalid_argument("highscore: name does not fit Source row");
// strcpy preserves bytes beyond the terminator of an existing row.
std::copy(s.begin(), s.end(), p);
p[s.size()] = 0;
}
} // namespace
HighscoreScore highscore_score(const ModernState& g, int manager, HighscoreContext context) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size())
throw std::invalid_argument("highscore: manager is outside active slots");
HighscoreScore result;
const int team = g.manager_teams.at(size_t(manager));
if (team == no_team()) {
// CareerSession_DispatchLineup_RuntimeField+CareerSession_InstallLeagueSizes_RuntimeField6+ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 == no_team() in the supported Original database;
// national honours store (team-no_team())|0x80, so Germany's index is0.
for (uint32_t year = 0; year < 20; ++year)
for (uint32_t place = 0; place < 4; ++place) {
const uint8_t v = g.memory.u8(::bmh::layout::Placements + year * 4 + place);
if ((v & 0x80) && (v & 0x7f) == 0)
result.history += int32_t(kNationalWeights[place]) * 10;
}
} else {
if (g.season < 0) throw std::invalid_argument("highscore: negative season index");
const int asset_manager = context == HighscoreContext::SeasonBoundary
? int(g.manager_teams.size()) : int(g.memory.u8(::bmh::layout::ActiveManager));
result.assets = std::min(net_assets(g, asset_manager) / 50000, 100);
result.patience = rec8(g, manager, 0x26f);
ModernState facility_state = g; // facility_rating's public API takes mutable state.
int second = 0;
result.facilities = modern::facility_rating(facility_state, manager, &second) * 4;
result.team = int(uint16_t(team_average(g, team, 0x2ff).value)) / 10;
const uint32_t count = std::min(uint32_t(g.season) + 1, 50u);
uint32_t history = 0;
for (uint32_t year = 0; year < count; ++year) {
const size_t at = 0xda + year * 3;
const uint8_t v = rec8(g, manager, at + 2);
history += uint32_t(rec8(g, manager, at)) + uint32_t(rec8(g, manager, at + 1)) * 2 +
uint32_t(kHistoryWeights[v >> 5]) * (v & 0x1f);
}
result.history = int32_t((history & 0xffff) / count);
}
uint32_t total = uint32_t(result.assets) + uint32_t(result.patience) +
uint32_t(result.facilities) + uint32_t(result.team) + uint32_t(result.history);
for (size_t k = 0; k < 3; ++k)
result.titles += int32_t(kTitleWeights[k]) * rec16(g, manager, 0x8a4 + k * 2);
total += uint32_t(result.titles);
result.total = std::max(signed32(total), 0);
return result;
}
HighscoreRow highscore_candidate(const ModernState& g, int manager, HighscoreContext context) {
if (g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == 0) return {};
HighscoreRow row;
row.score = modern::highscore_score(g, manager, context).total;
row.club_name = g.club_name(g.manager_teams.at(size_t(manager)));
row.manager_name = record_name(g, manager);
for (size_t k = 0; k < 3; ++k) row.titles[k] = rec16(g, manager, 0x8a4 + k * 2);
return row;
}
void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate) {
size_t target = rows.size();
for (size_t k = 0; k < rows.size(); ++k)
if (rows[k].manager_name == candidate.manager_name && rows[k].club_name == candidate.club_name) {
target = k;
break;
}
if (target == rows.size() && rows.back().score < candidate.score) target = rows.size() - 1;
if (target == rows.size()) return;
rows[target] = candidate;
// Swap uses these pairwise swaps; preserve equal-score ordering exactly.
for (size_t a = 0; a < 4; ++a)
for (size_t b = a + 1; b < 5; ++b)
if (rows[a].score < rows[b].score) std::swap(rows[a], rows[b]);
}
HighscoreProjection make_highscore_projection(const ModernState& g, HighscoreTable rows, HighscoreContext context) {
HighscoreProjection out;
out.signature = g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7);
out.ranked = out.signature != 0;
out.rows = std::move(rows);
if (!out.ranked) return out;
// GameEndAlternateScoreScreen gates the entire manager loop using slot0, not each candidate's team.
if (!g.manager_teams.empty() &&
(g.manager_teams[0] != no_team() || (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) == 0))
for (size_t m = 0; m < g.manager_teams.size(); ++m)
modern::insert_highscore(out.rows, modern::highscore_candidate(g, int(m), context));
return out;
}
HighscoreBytes encode_highscore_table(const HighscoreTable& rows) {
HighscoreBytes bytes{};
for (size_t k = 0; k < rows.size(); ++k) {
uint8_t* p = bytes.data() + k * 72;
std::copy(rows[k].original_bytes.begin(), rows[k].original_bytes.end(), p);
put32(p, uint32_t(rows[k].score));
put_name(p + 4, rows[k].club_name);
put_name(p + 0x22, rows[k].manager_name);
for (size_t t = 0; t < 3; ++t) {
p[0x40 + t * 2] = uint8_t(rows[k].titles[t]);
p[0x41 + t * 2] = uint8_t(rows[k].titles[t] >> 8);
}
}
return bytes;
}
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) {
HighscoreTable rows{};
for (size_t k = 0; k < rows.size(); ++k) {
const uint8_t* p = bytes.data() + k * 72;
std::copy(p, p + 72, rows[k].original_bytes.begin());
rows[k].score = signed32(read32(p));
rows[k].club_name = read_name(p + 4);
rows[k].manager_name = read_name(p + 0x22);
for (size_t t = 0; t < 3; ++t) rows[k].titles[t] = uint16_t(p[0x40 + t * 2] | p[0x41 + t * 2] << 8);
}
return rows;
}
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix, bool native) {
if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file");
if (native)
return base / ("highscore-" + std::to_string(signature) + ".obscore");
return base / (prefix + std::to_string(signature));
}
HighscoreTable load_highscore_table(const std::filesystem::path& file) {
if (file.extension() == ".obscore") {
const auto data = read_file(file);
const auto j = cli::parse_json(std::string(data.begin(), data.end()));
if (!j.object() || !j.object()->contains("schema") || !j.object()->at("schema").string() ||
*j.object()->at("schema").string() != "classic-highscore@1.0" || !j.object()->contains("payload"))
throw FormatError("Invalid native highscore");
const auto raw = decode_native_bytes(j.object()->at("payload"), 360);
HighscoreBytes bytes;
std::copy(raw.begin(), raw.end(), bytes.begin());
return modern::decode_highscore_table(bytes);
}
std::ifstream in(file, std::ios::binary);
if (!in) {
HighscoreTable empty{};
modern::save_highscore_table(file, empty); // Read creates a zero table on a missing file.
return empty;
}
HighscoreBytes bytes{};
in.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
return modern::decode_highscore_table(bytes);
}
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) {
const auto bytes = modern::encode_highscore_table(rows);
if (file.extension() == ".obscore") {
try {
content::write_atomic(file,
cli::dump_json(cli::Json::Object{
{"schema", "classic-highscore@1.0"},
{"payload", encode_native_bytes(Bytes(bytes.begin(), bytes.end()))}}),
true);
return true;
} catch (const std::exception &) {
return false;
}
}
std::ofstream out(file, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
return bool(out);
}
} // namespace bmh::modern
+37
View File
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/highscore.hpp"
#include <array>
#include <cstdint>
#include <filesystem>
#include <string>
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// HighscoreOperation / GameEndAlternateScoreScreen. Names retain Original ISO646-DE bytes.
// Assets in HighscoreScore use global ActiveManager even when scoring another manager. At the
// season boundary DailyInterest's preceding manager loop leaves ActiveManager=manager_count.
// Pass that context explicitly without modifying the caller's continuation state.
HighscoreScore highscore_score(const ModernState& g, int manager,
HighscoreContext context = HighscoreContext::ActiveManager);
HighscoreRow highscore_candidate(const ModernState& g, int manager,
HighscoreContext context = HighscoreContext::ActiveManager);
void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate);
HighscoreProjection make_highscore_projection(const ModernState& g, HighscoreTable rows = {},
HighscoreContext context = HighscoreContext::ActiveManager);
HighscoreBytes encode_highscore_table(const HighscoreTable& rows);
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes);
// The caller supplies the configured installation base and Original TEXTD889 prefix.
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix = "high/h.", bool native = false);
HighscoreTable load_highscore_table(const std::filesystem::path& file);
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows);
} // namespace bmh::modern
+548
View File
@@ -0,0 +1,548 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/league_pairings.hpp"
#include <algorithm>
#include <bit>
#include <cstdint>
#include <stdexcept>
#include "modern/game/matchday.hpp"
#include "modern/game/matchday_setup.hpp"
#include "game/match_engine.hpp"
#include "game/schedule.hpp"
#include "modern/game/source_tip.hpp"
#include "game/table.hpp"
namespace bmh::modern {
namespace {
void require(bool value,const char* reason) {
if(!value) throw std::invalid_argument(reason);
}
void clear_computer_tip(LeaguePairingsOwner& owner) {
owner.computer_tip_active=false;owner.computer_tip_league=owner.computer_tip_round=-1;
owner.computer_tip_original.fill(0);owner.computer_tip_results.clear();
}
void prepare_computer_tip(ModernState& g,LeaguePairingsOwner& owner,
const LeaguePairingsConstants& c,GameRandom& game) {
const uint32_t preferences_at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(owner.manager);
require(!owner.filter_active&&!owner.postponed_active&&
(g.memory.u8(preferences_at)&0x0f)<=3,
"pairings: Computer Tip supports only ordinary/search modes 0..3");
require(owner.round>=0&&size_t(owner.league)<g.league_rounds.size()&&
int(g.league_rounds[size_t(owner.league)])<=owner.round,
"pairings: Computer Tip requires a current/future Source round");
require(g.memory.has(::bmh::layout::CurrentMatchday)&&g.results.size()>=kResultsSize,
"pairings: Computer Tip Native seed/results unavailable");
const auto page=modern::league_pairings_view_source(g,owner,c);
const size_t expected=league_fixtures(owner.league,owner.round+1).size();
require(page.rows.size()==expected&&page.total_rows==int(expected),
"pairings: Computer Tip requires the complete ordinary fixture row set");
for(const auto& row:page.rows)
require(row.raw_result==0xcc,"pairings: Computer Tip requires every visible result to be 0xcc");
const int32_t source_seed=std::bit_cast<int32_t>(g.memory.u32(::bmh::layout::CurrentMatchday));
require(source_seed>=0&&source_seed<=10000,
"pairings: Computer Tip rejects an unqualified signed Native seed");
const size_t first=result_index(owner.league,owner.round+1,0);
require(first+10<=g.results.size(),"pairings: Computer Tip ten-byte Source backup is unavailable");
std::array<uint8_t,10> original{};
if(owner.computer_tip_active) {
require(owner.computer_tip_league==owner.league&&owner.computer_tip_round==owner.round&&
owner.computer_tip_results.size()==expected,
"pairings: stale Computer Tip forecast identity");
original=owner.computer_tip_original;
for(size_t i=0;i<10;++i)
require(g.results[first+i]==original[i],"pairings: Native result slice changed under Computer Tip");
} else {
std::copy_n(g.results.begin()+static_cast<std::ptrdiff_t>(first),10,original.begin());
}
struct Input { const LeaguePairingsRow* row; int home_rating,away_rating,home_secondary,away_secondary; };
std::vector<Input> inputs;inputs.reserve(expected);
for(const auto& row:page.rows) {
require(row.source_round==owner.round&&row.fixture_index>=0&&
size_t(row.fixture_index)<expected&&original[size_t(row.fixture_index)]==0xcc,
"pairings: Computer Tip fixture is outside the original 10-byte unplayed slice");
inputs.push_back({&row,
team_average(g,row.home.runtime_team,0x3f3).value,
team_average(g,row.away.runtime_team,0x3f3).value,
team_average(g,row.home.runtime_team,0x3fc).value,
team_average(g,row.away.runtime_team,0x3fc).value});
}
// Work on a copy so any arithmetic/validation failure leaves the staged G
// object untouched. set_seed preserves its cumulative Source call count.
GameRandom staged_game=game;staged_game.set_seed(source_seed);
std::vector<LeaguePairingsTipResult> results;results.reserve(expected);
for(const auto& input:inputs) {
const auto& row=*input.row;
results.push_back({owner.league,row.source_round,row.fixture_index,
row.home.runtime_team,row.home.club_identity,row.away.runtime_team,row.away.club_identity,
row.raw_result,modern::source_tip_result(staged_game,c.computer_tip_gap,input.home_rating,input.away_rating,
input.home_secondary,input.away_secondary)});
}
game=staged_game;owner.computer_tip_active=true;
owner.computer_tip_league=owner.league;owner.computer_tip_round=owner.round;
owner.computer_tip_original=original;owner.computer_tip_results=std::move(results);
g.memory.set8(preferences_at,uint8_t(g.memory.u8(preferences_at)|0x10));
}
int filtered_fixture_count(int league,int team) {
int count=0;
for(int round=0;round<league_matchdays(league);++round)
for(const auto& fixture:league_fixtures(league,round+1))
if(fixture.home==team||fixture.away==team)++count;
return count;
}
int postponed_fixture_count(const ModernState& g,int league) {
int count=0;
for(int round=0;round<league_matchdays(league);++round) {
const auto fixtures=league_fixtures(league,round+1);
for(size_t slot=0;slot<fixtures.size();++slot)
if(modern::league_pairings_postponed_source(g.results.at(result_index(league,round+1,int(slot)))))++count;
}
require(count<=255,"pairings: Mode8 Source byte-counter overflow is outside the supported boundary");
return count;
}
void validate(const ModernState& g,const LeaguePairingsOwner& o) {
const bool national=o.runtime_club==no_team();
require(o.supported&&!o.closed&&o.manager>=0&&o.manager<4&&
size_t(o.manager)<g.manager_teams.size()&&g.memory.has(::bmh::layout::ActiveManager)&&
g.memory.u8(::bmh::layout::ActiveManager)==o.manager&&g.manager_teams[size_t(o.manager)]==o.runtime_club&&
(national||(o.runtime_club>=0&&o.runtime_club<league_clubs()))&&
size_t(o.runtime_club)<g.club_ids.size()&&
g.club_ids[size_t(o.runtime_club)]==o.club_identity,
"pairings: stale or unsupported manager identity");
require(o.league>=0&&o.league<9&&o.round>=0&&o.round<league_matchdays(o.league)&&
o.league_group<=1&&size_t(o.league)<g.league_rounds.size()&&
g.league_rounds[size_t(o.league)]<=league_matchdays(o.league),
"pairings: unsupported league/round");
require(o.active_group>=-1&&(!o.active_phase||o.active_group>=0),
"pairings: invalid active presentation phase");
require(g.memory.has(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&&
(((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0c)==0)||
(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==4||
(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==8)&&
g.memory.has(::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2+1),
"pairings: missing preferences or unsupported saved list mode");
require(g.results.size()>=kResultsSize&&g.club_ids.size()>=size_t(league_clubs())&&g.league_rounds.size()>=9&&
g.memory.has(::bmh::layout::Postponed+0xef)&&g.memory.has(::bmh::layout::CompetitionCalendar+365*2+1),
"pairings: incomplete Native schedule");
const auto selection_valid=[&](int team,int identity) {
return team<0 ? team>=-2&&identity==-1 :
team<league_clubs()&&team_league(team)==o.league&&g.club_ids.at(size_t(team))==identity;
};
require(selection_valid(o.search_first,o.search_first_identity)&&
selection_valid(o.search_second,o.search_second_identity)&&
(o.search_first!=-1 || (o.search_second==-1&&!o.search_second_click))&&
(o.search_first!=-2 || (o.search_second==-2&&!o.search_second_click))&&
(o.search_first==-1 || (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==2)&&
(!o.search_second_click || (o.search_first>=0&&o.search_second>=-1)),
"pairings: stale or invalid search selection");
const uint8_t mode=uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f);
const bool mode8=mode==8;
if(mode8) {
require(o.postponed_active&&!o.filter_active&&o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&&
o.search_first==-1&&o.search_second==-1&&o.search_first_identity==-1&&o.search_second_identity==-1&&
!o.search_second_click&&o.postponed_offset>=0&&o.postponed_offset%10==0,
"pairings: invalid postponed-list owner");
const int count=postponed_fixture_count(g,o.league);
require((count==0&&o.postponed_offset==0)||(count>0&&o.postponed_offset<count),
"pairings: stale or unreachable postponed-list window");
} else require(!o.postponed_active&&o.postponed_offset==0,
"pairings: stale postponed-list owner");
if(o.computer_tip_active) {
const size_t expected=league_fixtures(o.league,o.round+1).size();
require(mode<=3&&!o.filter_active&&!o.postponed_active&&
o.computer_tip_league==o.league&&o.computer_tip_round==o.round&&
o.round>=int(g.league_rounds.at(size_t(o.league)))&&
o.computer_tip_results.size()==expected&&g.memory.has(::bmh::layout::CurrentMatchday),
"pairings: invalid Computer Tip owner scope");
const size_t first=result_index(o.league,o.round+1,0);
require(first+10<=g.results.size(),"pairings: Computer Tip result backup is unavailable");
for(size_t n=0;n<10;++n)
require(g.results[first+n]==o.computer_tip_original[n],
"pairings: Computer Tip original result slice changed");
const auto fixtures=league_fixtures(o.league,o.round+1);
require(fixtures.size()==expected,"pairings: Computer Tip fixture count changed");
for(size_t n=0;n<expected;++n) {
const auto& tip=o.computer_tip_results[n];const auto& fixture=fixtures[n];
require(tip.league==o.league&&tip.source_round==o.round&&tip.fixture_index==int(n)&&
tip.home_runtime_team==fixture.home&&tip.away_runtime_team==fixture.away&&
tip.home_club_identity==g.club_ids.at(size_t(fixture.home))&&
tip.away_club_identity==g.club_ids.at(size_t(fixture.away))&&
tip.original_result==0xcc&&o.computer_tip_original[n]==0xcc,
"pairings: stale Computer Tip fixture identity");
}
} else require(o.computer_tip_league==-1&&o.computer_tip_round==-1&&
o.computer_tip_results.empty(),"pairings: stale inactive Computer Tip data");
if(o.filter_active) {
require(mode==4&&o.search_first==-1&&o.search_second==-1&&
o.search_first_identity==-1&&o.search_second_identity==-1&&!o.search_second_click&&
o.filter_offset>=0&&o.filter_offset%10==0&&o.filter_team>=-2,
"pairings: invalid Source club-filter mode");
if(o.filter_team>=0) {
require(o.filter_team<league_clubs()&&team_league(o.filter_team)==o.league&&
g.club_ids.at(size_t(o.filter_team))==o.filter_identity&&
(o.filter_offset==0||o.filter_offset<filtered_fixture_count(o.league,o.filter_team)),
"pairings: stale or out-of-range filtered club");
} else {
require(o.filter_team==-2&&o.filter_identity==-1&&o.filter_offset==0,
"pairings: invalid unselected club filter");
}
} else {
require(o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&&mode!=4&&(!mode8||o.postponed_active),
"pairings: stale club-filter selection");
}
}
void page_preferences(ModernState& g,const LeaguePairingsOwner& o,const LeaguePairingsConstants& c) {
const uint32_t word=::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2;
uint16_t flags=uint16_t((g.memory.u16(word)&0xfc0f)|0x170);
if(c.points_mode.at(size_t(o.league))) flags|=0x80;
g.memory.set16(word,flags);
// Move clears the temporary Computer-Tip selection after every redraw.
const uint32_t byte=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager);
g.memory.set8(byte,uint8_t(g.memory.u8(byte)&0xef));
}
int current_round(const ModernState& g,int league) {
return std::min<int>(g.league_rounds.at(size_t(league)),league_matchdays(league)-1);
}
LeaguePairingsTeam team_view(const ModernState& g,int team,int played) {
LeaguePairingsTeam out; out.runtime_team=team;out.club_identity=g.club_ids.at(size_t(team));
if(played) {
const int r=played-1;
const size_t at=(size_t(team)*13+size_t(r/3))*2;
require(at+1<g.position_history.size(),"pairings: missing Source rank history");
const unsigned word=g.position_history[at]|unsigned(g.position_history[at+1])<<8;
out.previous_rank=int((word>>((r%3)*5))&31)+1;
}
constexpr std::array<uint16_t,5> flags{0x1f1,0x1f2,0x1f4,0x1f8,0x1ff};
for(size_t n=0;n<flags.size();++n)out.strength[n]=team_average(g,team,flags[n]).value;
return out;
}
uint32_t round_date(const ModernState& g,int league,int round,const LeaguePairingsConstants& c) {
require(c.domestic_league_count>0&&c.domestic_league_count<=9,
"pairings: unsupported Source calendar constants");
require(c.calendar_class.at(size_t(league))<32,"pairings: invalid calendar mask shift");
const uint32_t mask=league>=c.domestic_league_count?0x10u:1u<<c.calendar_class.at(size_t(league));
for(int day=0;day<366;++day) {
if(modern::day_competitions(g,g.memory.u16(::bmh::layout::CompetitionCalendar+uint32_t(day)*2))&mask) {
if(round--==0)return (g.season_start+uint32_t(day))&0xffff;
}
}
// LeaguePairingsPlayedSource returns FFFF; 333f3 adds CalendarState_FormatError_RuntimeField3 and truncates to16 bits.
return (g.season_start+0xffffu)&0xffff;
}
}
bool league_pairings_played_source(uint8_t raw) {return (raw&0xcc)!=0xcc;}
bool league_pairings_postponed_source(uint8_t raw) {return (raw&0xcf)>0xcc;}
std::optional<LeaguePairingsActivePacket> league_pairings_active_packet_source(
const ModernState& g,const LeaguePairingsOwner& owner,const std::vector<MatchGroup>& groups,
std::span<const uint8_t> referee_profiles) {
validate(g,owner);
// Mode4's armed -2 sentinel still uses the ordinary selected-round list.
// A selected filter and Mode8 explicitly clear local74 in Move.
if(owner.postponed_active||(owner.filter_active&&owner.filter_team>=0))return std::nullopt;
const auto fixtures=league_fixtures(owner.league,owner.round+1);
int found=-1;
for(size_t n=0;n<groups.size();++n) {
const auto& group=groups[n];
if(group.fixtures.size()>=2&&group.fixtures[0]==fixtures.front().home&&
group.fixtures[1]==fixtures.front().away)found=int(n);
}
if(found<0)return std::nullopt;
const auto& group=groups[size_t(found)];
require(group.fixtures.size()==fixtures.size()*2,
"pairings: incomplete active fixture vector");
LeaguePairingsActivePacket packet;
packet.league=owner.league;packet.round=owner.round;packet.group_index=found;
packet.rows.reserve(fixtures.size());
for(size_t n=0;n<fixtures.size();++n) {
const auto& fixture=fixtures[n];
require(group.fixtures[n*2]==fixture.home&&group.fixtures[n*2+1]==fixture.away,
"pairings: active fixture order does not match the selected round");
require(group.desc.size()>0x50+n,
"pairings: incomplete active referee/weather descriptor");
const uint8_t referee=group.desc[0x10+n];
require(size_t(referee)<referee_profiles.size()&&size_t(referee)*2+1<g.master_database_metadata.size(),
"pairings: missing active referee identity/profile");
const size_t name=size_t(g.master_database_metadata[size_t(referee)*2])|
size_t(g.master_database_metadata[size_t(referee)*2+1])<<8;
require(name<g.referee_names.size(),"pairings: active referee name offset is outside its Native pool");
const auto first=g.referee_names.begin()+name;
const auto end=std::find(first,g.referee_names.end(),uint8_t(0));
require(end!=g.referee_names.end(),"pairings: active referee name has no terminator");
LeaguePairingsActiveRow row;
row.source_round=owner.round;row.fixture_index=int(n);
row.home_runtime_team=fixture.home;row.home_club_identity=g.club_ids.at(size_t(fixture.home));
row.away_runtime_team=fixture.away;row.away_club_identity=g.club_ids.at(size_t(fixture.away));
row.referee_index=referee;row.referee_profile=referee_profiles[size_t(referee)];
row.weather=group.desc[0x50+n];row.temperature=int8_t(group.desc[0x30+n]);
row.referee_name.assign(first,end);packet.rows.push_back(std::move(row));
}
return packet;
}
void validate_league_pairings_active_packet_source(const ModernState& g,const LeaguePairingsOwner& owner,
const LeaguePairingsActivePacket& packet) {
validate(g,owner);
require(!owner.postponed_active&&!(owner.filter_active&&owner.filter_team>=0)&&
packet.league==owner.league&&packet.round==owner.round&&packet.group_index>=0&&
packet.group_index==owner.active_group,"pairings: stale active descriptor owner");
const auto fixtures=league_fixtures(owner.league,owner.round+1);
require(packet.rows.size()==fixtures.size(),"pairings: incomplete active presentation rows");
for(size_t n=0;n<fixtures.size();++n) {
const auto& row=packet.rows[n];const auto& fixture=fixtures[n];
require(row.source_round==owner.round&&row.fixture_index==int(n)&&
row.home_runtime_team==fixture.home&&row.away_runtime_team==fixture.away&&
row.home_club_identity==g.club_ids.at(size_t(fixture.home))&&
row.away_club_identity==g.club_ids.at(size_t(fixture.away)),
"pairings: stale active row fixture identity");
require(size_t(row.referee_index)*2+1<g.master_database_metadata.size(),
"pairings: missing active referee name identity");
const size_t at=size_t(g.master_database_metadata[size_t(row.referee_index)*2])|
size_t(g.master_database_metadata[size_t(row.referee_index)*2+1])<<8;
require(at<g.referee_names.size(),"pairings: stale active referee name offset");
const auto first=g.referee_names.begin()+at;
const auto end=std::find(first,g.referee_names.end(),uint8_t(0));
require(end!=g.referee_names.end()&&row.referee_name==std::string(first,end),
"pairings: stale active referee name");
}
}
LeaguePairingsOwner open_league_pairings_source(ModernState& g,int manager,const LeaguePairingsConstants& c) {
require(manager>=0&&manager<4&&size_t(manager)<g.manager_teams.size(),"pairings: unsupported manager");
LeaguePairingsOwner out;out.manager=manager;out.runtime_club=g.manager_teams[size_t(manager)];
const bool national=out.runtime_club==no_team();
require((national||(out.runtime_club>=0&&out.runtime_club<league_clubs()))&&
size_t(out.runtime_club)<g.club_ids.size(),"pairings: unsupported or unowned manager");
out.club_identity=g.club_ids[size_t(out.runtime_club)];
// TeamLeague2 maps the Original national runtime team 0x165 to league 0.
out.league=national?0:team_league(out.runtime_club);
require(size_t(out.league)<g.league_rounds.size(),"pairings: missing Native round counter");
out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));out.supported=true;
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(manager))&0x0f)==8)out.postponed_active=true;
validate(g,out);page_preferences(g,out,c);
return out;
}
LeaguePairingsOwner edit_league_pairings_source(ModernState& g,const LeaguePairingsOwner& before,
const LeaguePairingsEvent& e,const LeaguePairingsConstants& c,GameRandom& game,WatcomRandom& rand) {
validate(g,before);auto out=before;
if(e.kind!=LeaguePairingsAction::computer_tip)clear_computer_tip(out);
const auto reset=[&] {const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager);
g.memory.set8(at,uint8_t((g.memory.u8(at)&0xf0)|1));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;
out.filter_team=out.filter_identity=-1;out.filter_offset=0;out.filter_active=false;
out.postponed_active=false;out.postponed_offset=0;};
switch(e.kind) {
case LeaguePairingsAction::presentation_redraw:
require(before.active_group>=0&&(e.value==0||e.value==1)&&bool(e.value)!=before.active_phase,
"pairings: invalid active presentation redraw");
out.active_phase=bool(e.value);break;
case LeaguePairingsAction::reset: out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));reset();break;
case LeaguePairingsAction::previous:
if(out.postponed_active) {if(out.postponed_offset>=10)out.postponed_offset-=10;break;}
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) {
if(out.filter_active&&out.filter_offset>=10)out.filter_offset-=10;
break;
}
out.round=(out.round+league_matchdays(out.league)-1)%league_matchdays(out.league);out.title_round=out.round;break;
case LeaguePairingsAction::next:
if(out.postponed_active) {
const auto page=modern::league_pairings_view_source(g,before,c);
if(page.rows.size()==10&&out.postponed_offset+10<page.total_rows)out.postponed_offset+=10;
else if(page.rows.size()==10&&out.postponed_offset==0&&page.total_rows==10)
throw std::invalid_argument("pairings: bounded Mode8 exact-ten non-progress rejected");
break;
}
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) {
if(out.filter_active&&out.filter_team>=0&&
out.filter_offset+10<filtered_fixture_count(out.league,out.filter_team))out.filter_offset+=10;
break;
}
out.round=(out.round+1)%league_matchdays(out.league);out.title_round=out.round;break;
case LeaguePairingsAction::toggle_group:
require(g.memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField2)&&g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2)==0,
"pairings: secondary leagues disabled");
out.league_group^=1;
require(size_t(out.manager)*0xb0c+0x210<g.manager_records.size(),
"pairings: missing manager league preference");
out.league=out.league_group?5:g.manager_records.at(size_t(out.manager)*0xb0c+0x210);
require(out.league>=0&&out.league<9,"pairings: invalid manager league preference");
[[fallthrough]];
case LeaguePairingsAction::select_league:
if(e.kind==LeaguePairingsAction::select_league) {
require(e.value>=0&&e.value<9,"pairings: invalid league selection");out.league=e.value;
}
if(out.league!=before.league) {
// LeagueMatchdays: retained round must be in the league and at/before
// its next round. Directparam0 does not apply the automatic reset.
if(out.round>=league_matchdays(out.league)||out.round>g.league_rounds.at(size_t(out.league)))
out.round=current_round(g,out.league);
out.title_round=out.round;
reset();
}
break;
case LeaguePairingsAction::team_info:
case LeaguePairingsAction::search_team: {
require(!out.filter_active&&!(e.kind==LeaguePairingsAction::search_team&&out.postponed_active),
"pairings: filtered rows cannot open ordered search");
require((e.kind==LeaguePairingsAction::search_team)==(out.search_first!=-1),
"pairings: row action does not match Source search ownership");
const auto view=modern::league_pairings_view_source(g,before,c);bool found=false;
for(const auto& row:view.rows)for(const auto* team:{&row.home,&row.away})
found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity;
require(found,"pairings: stale fixture team identity");
if(e.kind==LeaguePairingsAction::team_info)break;
if(!out.search_second_click) {
out.search_first=e.value;out.search_first_identity=e.expected_club_identity;
out.search_second=-1;out.search_second_identity=-1;out.search_second_click=true;
} else {
out.search_second=e.value;out.search_second_identity=e.expected_club_identity;
// LeagueMatchdays2 scans directed home/away fixtures in ascending round
// then row order. A missing self-pair keeps round and local30=1.
for(int round=0;round<league_matchdays(out.league);++round) {
const auto fixtures=league_fixtures(out.league,round+1);
if(std::any_of(fixtures.begin(),fixtures.end(),[&](const auto& fixture) {
return fixture.home==out.search_first&&fixture.away==out.search_second;
})) {
out.round=out.title_round=round;out.search_second_click=false;break;
}
}
}
break;
}
case LeaguePairingsAction::search:
out.filter_team=out.filter_identity=-1;out.filter_offset=0;out.filter_active=false;
out.postponed_active=false;out.postponed_offset=0;
out.title_round=out.round; // local34 was clamped during the prior draw.
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|2));
out.search_first=out.search_second=-2;
out.search_first_identity=out.search_second_identity=-1;out.search_second_click=false;
break;
case LeaguePairingsAction::filter_by_club:
out.postponed_active=false;out.postponed_offset=0;out.title_round=out.round;
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|4));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;
out.filter_team=-2;out.filter_identity=-1;out.filter_offset=0;out.filter_active=true;
break;
case LeaguePairingsAction::postponed_list:
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|8));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;out.filter_team=out.filter_identity=-1;out.filter_offset=0;
out.filter_active=false;out.postponed_active=true;out.postponed_offset=0;
break;
case LeaguePairingsAction::computer_tip:
prepare_computer_tip(g,out,c,game);break;
case LeaguePairingsAction::filter_club: {
require(out.filter_active,"pairings: club selection outside Source filter mode");
const auto visible=modern::league_pairings_view_source(g,before,c);bool found=false;
for(const auto& row:visible.rows)for(const auto* team:{&row.home,&row.away})
found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity;
require(found,"pairings: stale filtered-row team identity");
out.filter_team=e.value;out.filter_identity=e.expected_club_identity;
while(out.filter_offset>=filtered_fixture_count(out.league,out.filter_team)&&out.filter_offset>0)
out.filter_offset-=10;
break;
}
case LeaguePairingsAction::close:
reset();g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xef));
out.active_phase=false;out.active_group=-1;
out.closed=true;modern::stir_random(game,rand);return out;
case LeaguePairingsAction::unsupported:
throw std::invalid_argument("pairings: Original Zusatzaktion ist noch nicht verfügbar");
}
validate(g,out);
const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager);
if(e.kind!=LeaguePairingsAction::computer_tip)
g.memory.set8(at,uint8_t(g.memory.u8(at)&0xef));
return out;
}
LeaguePairingsView league_pairings_view_source(const ModernState& g,const LeaguePairingsOwner& o,
const LeaguePairingsConstants& c) {
validate(g,o);LeaguePairingsView out;out.owner=o;out.played_rounds=g.league_rounds.at(size_t(o.league));
out.total_rounds=league_matchdays(o.league);out.preferences=g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager));
const bool postponed=o.postponed_active;
if(!postponed)out.match_date=round_date(g,o.league,o.round,c);
auto append_row=[&](int round,size_t n,const Fixture& fixture) {
LeaguePairingsRow row;
row.source_round=round;row.fixture_index=int(n);
row.home=team_view(g,fixture.home,out.played_rounds);
row.away=team_view(g,fixture.away,out.played_rounds);
row.raw_result=g.results.at(result_index(o.league,round+1,int(n)));
if(o.computer_tip_active) {
const auto match=std::find_if(o.computer_tip_results.begin(),o.computer_tip_results.end(),
[&](const auto& tip) {return tip.league==o.league&&tip.source_round==round&&
tip.fixture_index==int(n)&&tip.home_runtime_team==row.home.runtime_team&&
tip.home_club_identity==row.home.club_identity&&
tip.away_runtime_team==row.away.runtime_team&&
tip.away_club_identity==row.away.club_identity;});
if(match!=o.computer_tip_results.end()) {
require(row.raw_result==match->original_result,
"pairings: Native result changed under Computer Tip forecast");
row.computer_tip_result=match->predicted_result;
}
}
if(postponed) {
for(uint32_t k=0;k<40;++k) {
const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at);
if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) {
row.postponed_queue_slot=uint8_t(k);row.postponed_day=day;
row.postponed_date=g.season_start+day;break;
}
}
} else if(!modern::league_pairings_played_source(row.raw_result)&&row.raw_result!=0xcc) {
for(uint32_t k=0;k<40;++k) {
const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at);
if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) {
row.postponed_date=g.season_start+day;break;
}
}
}
if(!o.active_phase&&!postponed&&!(o.filter_active&&o.filter_team>=0)&&round>=out.total_rounds/2) {
const uint8_t raw=g.results.at(result_index(o.league,round+1-out.total_rounds/2,int(n)));
if(modern::league_pairings_played_source(raw))row.first_leg_result=raw;
}
if(o.filter_active&&o.filter_team>=0&&row.raw_result==0xcc)
row.scheduled_date=round_date(g,o.league,round,c);
out.rows.push_back(std::move(row));
};
if(postponed) {
out.page_offset=o.postponed_offset;
for(int round=0;round<out.total_rounds;++round) {
const auto fixtures=league_fixtures(o.league,round+1);
for(size_t n=0;n<fixtures.size();++n) {
const auto raw=g.results.at(result_index(o.league,round+1,int(n)));
if(!modern::league_pairings_postponed_source(raw))continue;
if(out.total_rows>=o.postponed_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]);
++out.total_rows;
}
}
} else if(o.filter_active&&o.filter_team>=0) {
out.page_offset=o.filter_offset;
for(int round=0;round<out.total_rounds;++round) {
const auto fixtures=league_fixtures(o.league,round+1);
for(size_t n=0;n<fixtures.size();++n) {
if(fixtures[n].home!=o.filter_team&&fixtures[n].away!=o.filter_team)continue;
if(out.total_rows>=o.filter_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]);
++out.total_rows;
}
}
} else {
const auto fixtures=league_fixtures(o.league,o.round+1);
out.total_rows=int(fixtures.size());
for(size_t n=0;n<fixtures.size();++n)append_row(o.round,n,fixtures[n]);
}
return out;
}
} // namespace bmh::modern
+36
View File
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/league_pairings.hpp"
#include <array>
#include <optional>
#include <span>
#include <string>
#include <vector>
#include "modern/game/modern_state.hpp"
#include "game/random.hpp"
namespace bmh::modern {
// Normal LeagueScreenShown(2,0)->Move(0) only. The App owns the staged Native/W/G
// transaction. No mutator here calls a presenter, advances a day, or saves.
LeaguePairingsOwner open_league_pairings_source(ModernState&,int manager,const LeaguePairingsConstants&);
LeaguePairingsOwner edit_league_pairings_source(ModernState&,const LeaguePairingsOwner&,
const LeaguePairingsEvent&,const LeaguePairingsConstants&,GameRandom&,WatcomRandom&);
// Pure, bounded Source projection; renderers never call a Native/RNG mutator.
LeaguePairingsView league_pairings_view_source(const ModernState&,const LeaguePairingsOwner&,
const LeaguePairingsConstants&);
// Read only active process descriptors, never reconstruct weather/referees from
// saved bytes or run event preparation. Last first-pair match follows Move.
std::optional<LeaguePairingsActivePacket> league_pairings_active_packet_source(
const ModernState&,const LeaguePairingsOwner&,const std::vector<MatchGroup>&,
std::span<const uint8_t> referee_profiles);
void validate_league_pairings_active_packet_source(const ModernState&,const LeaguePairingsOwner&,
const LeaguePairingsActivePacket&);
bool league_pairings_played_source(uint8_t raw);
bool league_pairings_postponed_source(uint8_t raw);
} // namespace bmh::modern
+794
View File
@@ -0,0 +1,794 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/matchday.hpp"
#include "modern/game/matchday_setup.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cstdlib>
#include "modern/game/cup.hpp"
#include "game/schedule.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/table.hpp"
namespace bmh::modern {
namespace {
// Competition class of each descriptor type (MatchEngineRuntimeField9): 0 league (cards count per
// team), 1-4 cup competitions with their own card counters, 0xFF = none.
constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255,
4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0};
// Clubs per league (LeagueSizes): five leagues of 18, four regional leagues of 12.
// (the clubs per league are kLeagueSizes, schedule.hpp)
// Three points for a win in every league (CareerSession_BeginFriendlyOpponentTable_RuntimeField, index 9 = "no league" reads the
// following table byte 18, also non-zero).
constexpr bool kThreePoints[10] = {true, true, true, true, true, true, true, true, true, true};
constexpr size_t kClubRecord = 0x4a;
constexpr size_t kManagerRecord = 0xB0C;
constexpr size_t kBoard = 0x840, kBoardSlot = 0x58;
uint32_t rd32(const std::vector<uint8_t>& v, size_t o) {
return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24);
}
void wr32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(x >> (8 * i));
}
uint16_t rd16(const std::vector<uint8_t>& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); }
void wr16(std::vector<uint8_t>& v, size_t o, uint16_t x) {
v.at(o) = uint8_t(x);
v.at(o + 1) = uint8_t(x >> 8);
}
int competition_class(int type) { return type >= 0 && type < 24 ? kCompetitionClass[type] : 255; }
// TeamLeague2: league (0-8) of a club id, 9 for clubs outside the leagues.
int league_of(int team) {
if (team > 0x164) return 0;
int end = 0;
for (int l = 0; l < 9; l++) {
end += kLeagueSizes[l];
if (team < end) return l;
}
return 9;
}
// ClubRecord: record result `idx` of a club. The value of a result is
// home * home_weight - away * away_weight; `lower` keeps the smallest instead of the
// largest value. The stored result uses away_weight 1 if it was negative.
void club_record(ModernState& g, int club, int idx, int home, int away, bool lower, int home_weight, int away_weight, int opponent) {
size_t base = size_t(club) * kClubRecord;
uint8_t& r = g.club_table.at(base + 0x15 + idx);
int old_value = (r >> 4) * home_weight - (r & 0x0F) * away_weight;
int new_value = home * home_weight - away * away_weight;
if (!lower ? new_value <= old_value : old_value <= new_value) return;
if (away_weight < 0) away_weight = 1;
r = uint8_t((uint8_t(home * home_weight) << 4) + uint8_t(away * away_weight));
wr16(g.club_table, base + 0x2a + idx * 2, g.club_ids.at(opponent));
wr16(g.club_table, base + 0x3a + idx * 2, uint16_t(std::min<uint32_t>(g.date, 0xFFFF)));
}
} // namespace
bool match_score(const MatchGroup& g, int m, int& home, int& away) {
if (!g.results.empty()) {
home = g.results.at(m) >> 4;
away = g.results.at(m) & 0x0F;
return true;
}
if (g.cup_results.size() == size_t(g.matches())) {
home = g.cup_results[m] >> 5 & 0x1F;
away = g.cup_results[m] & 0x1F;
return true;
}
return false;
}
int sportschau_source_setting_index(const ModernState& state, const MatchGroup& group) {
const uint32_t id = le32(group.desc, 0xcc);
if (id <= 0x14) return id < 5 ? int(id) : std::min(int(id) + 12, 0x13);
const uint32_t source = id + 0x18;
return state.memory.has(source) ? int(uint8_t(state.memory.u8(source) + 5)) : -1;
}
SportschauFixtureView sportschau_fixture_view(const ModernState& state, const MatchGroup& group,
int group_index, int fixture_index,
const std::vector<ShowEvent>& show_events) {
SportschauFixtureView view;
if (group_index < 0 || group_index > 0xff || fixture_index < 0 || fixture_index > 0xff ||
size_t(fixture_index * 2 + 1) >= group.fixtures.size())
return view;
view.group = uint8_t(group_index);
view.fixture = uint8_t(fixture_index);
view.competition_type = group.desc.at(0);
view.fixture_flags = group.desc.at(1);
view.source_footer_variant = state.indoor ? 2 : ((group.desc.at(1) & 8) != 0 ? 1 : 0);
view.has_replay_progression_mode = state.memory.has(::bmh::layout::ReplayProgressionMode);
if (view.has_replay_progression_mode) view.replay_progression_mode = state.memory.u8(::bmh::layout::ReplayProgressionMode);
view.has_replay_chance_mode = state.memory.has(::bmh::layout::ReplayChanceMode);
if (view.has_replay_chance_mode) view.replay_chance_mode = state.memory.u8(::bmh::layout::ReplayChanceMode);
view.source_selection_available = state.sportschau_selection_available;
view.competition_id = le32(group.desc, 0xcc);
view.source_setting_index = int16_t(modern::sportschau_source_setting_index(state, group));
view.home_team = int16_t(group.fixtures.at(size_t(fixture_index * 2)));
view.away_team = int16_t(group.fixtures.at(size_t(fixture_index * 2 + 1)));
view.source_selected = view.source_selection_available && modern::sportschau_selected(state, view.home_team);
if (size_t(fixture_index) < group.end_minute.size())
view.source_played_minute = group.end_minute[size_t(fixture_index)];
auto as_bytes = [](const std::string& s) {
return std::vector<uint8_t>(s.begin(), s.end());
};
auto set_team = [&](int team, std::vector<uint8_t>& full, std::vector<uint8_t>& short_name,
bool& short_name_available,
bool& requires_font_fit, bool& requires_longest_word, uint16_t& badge_word) {
const std::string name = state.club_name(team);
full = as_bytes(name);
if (team >= 0 && size_t(team) * 2 + 1 < state.club_heap_78.size())
badge_word = uint16_t(state.club_heap_78[size_t(team) * 2] |
uint16_t(state.club_heap_78[size_t(team) * 2 + 1]) << 8);
if (team >= 0 && team < first_foreign_cup()) {
requires_font_fit = true;
if (state.memory.has(::bmh::layout::ClubShortNameOffsets + uint32_t(team))) {
const uint8_t source = state.memory.u8(::bmh::layout::ClubShortNameOffsets + uint32_t(team));
const size_t offset = source >> 4;
const size_t length = (source & 0x0f) + 1;
if (offset <= full.size()) {
short_name_available = true;
const size_t count = std::min(length, full.size() - offset);
short_name.assign(full.begin() + std::ptrdiff_t(offset),
full.begin() + std::ptrdiff_t(offset + count));
}
}
} else {
short_name = full;
short_name_available = !short_name.empty();
requires_font_fit = true;
requires_longest_word = true;
}
};
set_team(view.home_team, view.home_name, view.home_short_name, view.home_short_name_available,
view.home_name_requires_font_fit, view.home_name_requires_longest_word, view.home_badge_word);
set_team(view.away_team, view.away_name, view.away_short_name, view.away_short_name_available,
view.away_name_requires_font_fit, view.away_name_requires_longest_word, view.away_badge_word);
int home = 0, away = 0;
view.score_known = modern::match_score(group, fixture_index, home, away);
if (view.score_known) {
view.home_goals = uint8_t(home);
view.away_goals = uint8_t(away);
}
uint16_t ordinal = 0;
for (size_t i = 0; i + 1 < group.log.size(); i += 2) {
const uint16_t code_player = group.log[i];
const uint16_t team_value = group.log[i + 1];
const int team = team_value >> 7;
if (team != view.home_team && team != view.away_team) continue;
SportschauLogEvent event;
event.group = view.group;
event.fixture = view.fixture;
event.event_ordinal = ordinal++;
event.source_word_index = uint16_t(i);
event.source_code_player_word = code_player;
event.source_team_value_word = team_value;
event.source_code = uint8_t(code_player >> 12);
event.player_id = uint16_t(code_player & 0x0fff);
event.team_id = int16_t(team);
event.source_value = uint8_t(team_value & 0x7f);
event.consumes_following_pair = event.source_code == 0 || event.source_code == 1;
event.has_following_word = i + 2 < group.log.size();
event.has_following_pair = i + 3 < group.log.size();
if (event.has_following_word) {
event.following_code_player_word = group.log[i + 2];
const int player = event.following_code_player_word & 0x0fff;
if (player != 0x0fff) event.following_player_name = as_bytes(state.player_name(player));
}
if (event.has_following_pair) event.following_team_value_word = group.log[i + 3];
if (event.player_id != 0x0fff) event.player_name = as_bytes(state.player_name(event.player_id));
view.log_events.push_back(std::move(event));
}
for (const ShowEvent& event : show_events)
if (event.group == view.group && event.match == view.fixture) view.show_events.push_back(event);
return view;
}
bool book_money(ModernState& g, int manager, int32_t amount, bool force, bool statistics) {
if (g.level == 0) return true;
size_t rec = size_t(manager) * kManagerRecord;
const uint32_t balance = rd32(g.manager_records, rec + 0x314);
const uint32_t credit = rd32(g.manager_records, rec + 0x31c);
// BookMoney2 adds the Native dwords before a signed comparison and subtracts
// the amount in the same 32-bit register width. Preserve that wrap without
// C++ signed-overflow undefined behavior at the account limits.
if (!force && amount >= 0 && std::bit_cast<int32_t>(balance + credit) < amount) return false;
wr32(g.manager_records, rec + 0x314, balance - uint32_t(amount));
if (statistics) {
if (amount < 0)
wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) - uint32_t(amount));
else
wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + uint32_t(amount));
}
return true;
}
uint32_t pay_bonus(ModernState& g, int manager, int board_slot, int index, bool pay) {
size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot;
uint32_t rate = g.tactics.at(slot + 0x12 + index);
if (rate == 0) return 0;
uint32_t factor = index > 2 ? 5 : 1;
uint32_t amount = factor * (rate * rd32(g.tactics, slot + 0x50)) / 100;
if (pay) {
size_t rec = size_t(manager) * kManagerRecord;
uint32_t tax = g.manager_records.at(rec + 0x172);
if (tax != 0) amount -= ((tax >> 5 & 7) + 3) * amount * 10 / 100;
modern::book_money(g, manager, int32_t(amount), true);
wr32(g.manager_records, rec + 0x334, rd32(g.manager_records, rec + 0x334) + amount);
}
return amount;
}
void player_statistic(ModernState& g, int type, int player, int manager, int slot, int kind, int minute) {
int cls = (type == 0xb && manager >= 0 && !g.manager_teams.empty() && g.manager_teams[0] == no_team())
? 3
: int8_t(competition_class(type));
if (cls < 0 || cls >= 4) return;
Player& p = g.players.at(player);
const uint32_t w364 = p.w364;
const size_t board = manager >= 0 ? size_t(manager) * kBoard + size_t(slot) * kBoardSlot : 0;
if (kind == 0) { // appearance
if (cls == 3 && (g.player_bonus.at(player) & 0x7F) < 0x7F) g.player_bonus.at(player)++;
if (manager >= 0) {
modern::pay_bonus(g, manager, slot, 2, true);
if (cls < 3) g.tactics.at(board + 7 + cls)++;
wr16(g.tactics, board + 0x48, uint16_t(rd16(g.tactics, board + 0x48) + 1));
}
if (cls == 0) p.w364 = (w364 & 0x03FFFFFFu) | ((w364 >> 26) + 1) << 26; // league games
} else if (kind == 1) { // goal
if (manager >= 0) {
modern::pay_bonus(g, manager, slot, 0, true);
wr16(g.tactics, board + 0x4a, uint16_t(rd16(g.tactics, board + 0x4a) + 1));
if (cls == 0) g.manager_records.at(size_t(manager) * kManagerRecord + 0x1ae + std::min(minute, 89) / 5)++;
}
// league goals in bits 2-7 (a 64th goal carries into bit 8, as in the original)
if (cls == 0) p.w364 = (w364 & 0xFFFFFF03u) | ((((w364 >> 2) & 0x3F) << 2) + 4);
} else if (kind == 2) { // assist
if (manager >= 0) wr16(g.tactics, board + 0x4c, uint16_t(rd16(g.tactics, board + 0x4c) + 1));
if (cls == 0) p.w368 = (p.w368 & 0xFF03FFFFu) | ((((p.w368 >> 18) & 0x3F) + 1) << 18);
}
}
void finish_match(ModernState& g, MatchGroup& grp, int m, int minute, GameRandom& game) {
if (grp.end_minute.at(m) == 0) grp.end_minute.at(m) = uint8_t(minute);
for (int side = 0; side < 2; side++) {
int manager = g.manager_of(grp.fixtures.at(m * 2 + side));
if (manager < 0) continue;
int home = 0, away = 0;
modern::match_score(grp, m, home, away);
int own = side ? away : home, opp = side ? home : away;
int points = 0;
if (own == opp) points = 1;
if (int8_t(own) > int8_t(opp)) points = 2;
for (int slot = 0; slot < 24; slot++) {
size_t at = size_t(manager) * kBoard + size_t(slot) * kBoardSlot;
int start = int8_t(g.tactics.at(at + 0x10)); // minute the player came on
for (int i = 0; i < points; i++) modern::pay_bonus(g, manager, slot, 1, true);
if (start >= 126) continue;
// Getting used to the place: a quarter of the minutes played (half in the
// competitions 5 and 7), at most 99.
int8_t delta = int8_t((minute - start) / 4);
if (grp.desc.at(0) == 5 || grp.desc.at(0) == 7) delta = int8_t(delta / 2);
if (g.indoor) start = int8_t(start) >> 2;
int used = int8_t(g.tactics.at(at + 0xf)) + delta;
g.tactics.at(at + 0xf) = uint8_t(std::clamp(used, 0, 99));
// The player's own place (bytes 0/1) moves one step towards the board place.
if (game.range(0, 90) < minute - start) {
for (int k = 0; k < 2; k++) {
uint8_t& cur = g.tactics.at(at + k);
uint8_t target = g.tactics.at(at + 0x41 + k);
if (cur < target) cur++;
if (cur > target) cur--;
}
}
}
}
}
void update_club_table(ModernState& g, int home, int away, int hg, int ag) {
if (g.indoor || g.club_table.empty()) return;
const size_t H = size_t(home) * kClubRecord, A = size_t(away) * kClubRecord;
auto add16 = [&](size_t o, int v) { wr16(g.club_table, o, uint16_t(rd16(g.club_table, o) + v)); };
// Only the first league and the regional leagues keep points in this table (the
// condition tests the home club only).
const bool league = home < kLeagueSizes[0] || (home >= german_clubs() && home < league_clubs());
const int win_points = kThreePoints[league_of(home)] ? 3 : 2;
if (league) {
add16(H + 0x20, hg);
add16(H + 0x22, ag);
add16(A + 0x20, ag);
add16(A + 0x22, hg);
}
uint8_t h[21], a[21]; // streaks: t * 3 + (0 all, 1 home, 2 away)
std::copy_n(g.club_table.begin() + H, 21, h);
std::copy_n(g.club_table.begin() + A, 21, a);
club_record(g, home, 2, hg, ag, false, 1, 0, away); // most goals scored at home
club_record(g, away, 7, hg, ag, false, 1, 0, home); // most goals conceded away
club_record(g, home, 3, hg, ag, false, 0, -1, away); // most goals conceded at home
club_record(g, away, 6, hg, ag, false, 0, -1, home); // most goals scored away
auto bump = [](uint8_t* s, int t, int j) { s[t * 3 + j]++, s[t * 3]++; };
auto clear = [](uint8_t* s, int t, int j) { s[t * 3 + j] = 0, s[t * 3] = 0; };
// streak 5: without conceding, 6: without scoring
if (ag == 0) bump(h, 5, 1), bump(a, 6, 2);
else clear(h, 5, 1), clear(a, 6, 2);
if (hg == 0) bump(h, 6, 1), bump(a, 5, 2);
else clear(h, 6, 1), clear(a, 5, 2);
if (ag < hg) { // home win
if (league) {
add16(H + 0x1e, win_points);
add16(H + 0x24, 1);
add16(A + 0x28, 1);
}
bump(h, 0, 1);
for (int t = 1; t < 4; t++) clear(h, t, 1);
club_record(g, home, 0, hg, ag, false, 1, 1, away); // biggest home win
club_record(g, away, 5, hg, ag, false, 1, 1, home); // biggest away defeat
bump(h, 4, 1);
clear(a, 0, 2), clear(a, 2, 2), clear(a, 4, 2);
bump(a, 1, 2), bump(a, 3, 2);
} else if (hg == ag) { // draw
if (league) {
add16(H + 0x1e, 1);
add16(A + 0x1e, 1);
add16(H + 0x26, 1);
add16(A + 0x26, 1);
}
clear(h, 0, 1), clear(h, 1, 1);
for (int t = 2; t < 5; t++) bump(h, t, 1);
clear(a, 0, 2), clear(a, 1, 2);
for (int t = 2; t < 5; t++) bump(a, t, 2);
} else { // away win
if (league) {
add16(A + 0x1e, win_points);
add16(H + 0x28, 1);
add16(A + 0x24, 1);
}
bump(a, 0, 2);
for (int t = 1; t < 4; t++) clear(a, t, 2);
clear(h, 0, 1), clear(h, 2, 1), clear(h, 4, 1);
bump(a, 4, 2);
bump(h, 1, 1), bump(h, 3, 1);
club_record(g, home, 1, hg, ag, true, 1, 1, away); // biggest home defeat
club_record(g, away, 4, hg, ag, true, 1, 1, home); // biggest away win
}
std::copy_n(h, 21, g.club_table.begin() + H);
std::copy_n(a, 21, g.club_table.begin() + A);
// Human managers keep their club's best streaks (manager record +0x5e).
for (int side = 0; side < 2; side++) {
int club = side ? away : home;
const uint8_t* s = side ? a : h;
for (size_t k = 0; k < g.manager_teams.size(); k++) {
if (g.manager_teams[k] != club) continue;
for (int i = 0; i < 21; i++) {
uint8_t& best = g.manager_records.at(k * kManagerRecord + 0x5e + i);
if (best < s[i]) best = s[i];
}
}
}
}
void update_morale(ModernState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand) {
uint8_t& morale = g.team_morale.at(team);
const int value = morale & 0x3F;
int sign = 1;
int diff = int16_t(side + (own_goals - opp_goals) + (5 - value / 5));
int step = std::abs(25 - value) / 5;
if (diff < 0 || (diff == 0 && value > 25)) {
sign = -1;
diff = -diff;
}
// Far from the middle (25) morale moves slowly towards the extremes.
if ((sign == 1 && value > 12) || (sign == -1 && value < 37)) step = 5 - step;
if (int16_t(step) == 0) step = 1;
diff = std::clamp(diff, 1, 3);
int range = int16_t(step * diff);
if (range > 12) range = 12;
if (range == 0) return;
int v = int16_t(value + sign * int16_t(rand.range(1, range)));
v = std::clamp(v, 0, 0x2f);
morale = uint8_t(v | (morale & 0xC0));
}
void develop_players(ModernState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand) {
const int type = grp.desc.at(0);
for (int side = 0; side < 2; side++) {
const int team = grp.fixtures.at(m * 2 + side);
if (!(team < first_foreign_cup() || team == no_team())) continue;
const uint8_t cls = (type == 0xb && team == no_team()) ? 3 : uint8_t(competition_class(type));
const int manager = g.manager_of(team);
const SquadRange range = squad_range(team);
// 1 in 11: the team gets the next trend of the rotation (none/down, neutral, up);
// the rotation is steered by the balance of all attribute changes so far.
if (game.range(0, 10) == 0) {
if (g.development_balance < -50) g.trend_rotation = 2;
if (g.development_balance > 50) g.trend_rotation = 0;
uint16_t& f = g.team_flags.at(team);
f = uint16_t(((f & 0xFFF8) + g.trend_rotation * 2) & 0xFFFF);
if (++g.trend_rotation == 3) g.trend_rotation = 0;
}
const int8_t trend = int8_t(((g.team_flags.at(team) >> 1) & 3) - 1);
int capped = 0; // local_30: attributes that hit 99 (carries over between players)
for (size_t s = range.first; s < range.first + range.count; s++) {
const int player = g.squad_slots.at(s) & 0x0FFF;
if (player == 0xFFF) break;
Player& p = g.players.at(player);
const int odds = manager >= 0 ? 6 : 3;
if (trend != 0 && game.range(0, 3) == 0) {
int8_t d = trend;
if (rand.range(0, 4) == 0) d = int8_t(-trend);
// form (shift 0, kept within 35-65), technique (7), condition (14)
uint32_t w = p.w35c;
for (int sh = 0; sh < 15; sh += 7) {
if (sh >= 7 && capped == 0 && game.range(0, odds) != 0) continue;
const int8_t old = int8_t((w >> sh) & 0x7F);
int8_t v = int8_t(old + d);
if (capped != 0 || game.range(0, 1) != 0) v = int8_t(v + d);
if (sh != 0) {
if (v < 0) v = 0;
if (v > 99) {
// Quirk of the original: the first attribute to pass 99 restarts
// the loop - 99 is written to the form and technique and
// condition are processed (again).
if (capped == 0) sh = 0;
v = 99;
capped++;
} else if (capped != 0) {
capped--;
}
} else {
v = int8_t(std::clamp<int>(v, 0x23, 0x41));
}
if (sh != 0) g.development_balance += v - old;
w = (w & ~(0x7Fu << sh)) + (uint32_t(int32_t(v)) << sh);
}
p.w35c = w;
// the seven skills follow the team trend (1 in 9 each)
uint32_t k = p.w368;
for (int sh = 0; sh < 13; sh += 2) {
if (game.range(0, 8) != 0) continue;
int v = int((p.w368 >> sh) & 3) + trend;
v = std::clamp(v, 0, 3);
k = (k & ~(3u << sh)) + (uint32_t(v) << sh);
}
p.w368 = k;
}
if (p.w364 & 0x1000) // played in this match
modern::player_statistic(g, type, player, manager, int(s - range.first), 0, 0x5a);
if (p.w35c >> 27) continue; // injured players are handled elsewhere
if (cls != 0xFF) {
const int duration = (p.w364 >> 16) & 0xF;
if (duration != 0 && !(p.w364 & 0x100000)) {
// injury (not a ban) heals by one match; in cups the card counter restarts
if (cls != 0) {
if (p.w368 >> 24 & 1) p.w368 &= 0xF8FFFFFFu;
else p.w368 = (p.w368 & 0xF8FC3FFFu) | 0x4000u;
}
p.w364 = (p.w364 & 0xFFE0FFFFu) | uint32_t(duration - 1) << 16;
} else if (cls == 0) {
// league: every fifth yellow card (booked in this match) bans for one match
int yellow = (p.w368 >> 14) & 0xF;
if ((g.squad_slots.at(s) & 0x1000) && yellow > 4 && yellow % 5 == 0) p.w364 |= 0x10000u;
}
}
g.squad_slots.at(s) &= 0xCFFF; // clear the booked/substituted slot flags
if (cls == 0) continue;
// Cups: move the card counters of this competition into the player's card word
// and load those of the next competition (the w368 card bits are shared).
if (p.w368 >> 24 & 1) p.w368 |= 0xC000u;
uint16_t& cards = g.player_cards.at(player);
switch (cls) {
case 1: p.w364 = (p.w364 & 0xFFFFFCFFu) | ((p.w368 >> 14) & 3) << 8; break;
case 2: p.w364 = (p.w364 & 0xFFFFF3FFu) | ((p.w368 >> 14) & 3) << 10; break;
case 3: cards = uint16_t((cards & 0x3FFF) | (p.w368 & 0xC000)); break;
case 4: cards = uint16_t((cards & 0xCFFF) | ((p.w368 >> 14) & 3) << 12); break;
default: break;
}
p.w368 = (p.w368 & 0xF8FC3FFFu) | uint32_t((cards >> 5) & 0xF) << 14 | uint32_t((cards >> 9) & 7) << 24;
if (p.w35c >> 27 == 0) p.w364 = (p.w364 & 0xFFE0FFFFu) | ((p.w364 >> 13) & 7) << 16;
}
}
}
void process_group(ModernState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay) {
auto owned = grp;
modern::process_group(g, owned, game, rand, report, group_index, sportschau, show_events, replay, nullptr);
}
void process_group(ModernState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay,
const SportschauRatingTables* ratings) {
const int type = grp.desc.at(0);
auto store_awards = [&] {
if (group_index < 0 || group_index >= 6) return;
const uint32_t base = ::bmh::layout::MatchdayGroupDescriptors + uint32_t(group_index) * 0xd0;
for (size_t i = 0; i < 11; ++i) {
if (g.memory.has(base + 0x70 + uint32_t(i)))
g.memory.set8(base + 0x70 + uint32_t(i), grp.desc.at(0x70 + i));
if (g.memory.has(base + 0x9c + uint32_t(i * 2 + 1)))
g.memory.set16(base + 0x9c + uint32_t(i * 2), le16(grp.desc, 0x9c + i * 2));
}
};
if (ratings) {
// FinishEvent/BuildSideRecords reset eleven score bytes, retaining old slot ids.
std::fill_n(grp.desc.begin() + 0x70, 11, uint8_t(0));
store_awards();
}
// The original walks the fixtures with a pointer (puVar2) that only moves on in the
// morale step of a played match. After a match that was not played, the club records and
// the morale of every following match are therefore booked on the teams of the match
// before it (the player development and the manager records use the match index).
size_t cursor = 0;
for (int m = 0; m < grp.matches(); m++) {
// The original keeps local_70 (kickoff_void_mask) separately from the descriptor:
// desc+0xb8 also gains ended-match bits as the minute loop runs. Its fixture pointer
// advances only for played matches, so a void fixture must not advance `cursor`.
if (grp.kickoff_void_mask & (1u << m)) continue;
// A postponed league match can also retain its 0xCD result byte.
if (!grp.results.empty() && (grp.results.at(size_t(m)) & 0xCC) == 0xCC) continue;
int home = 0, away = 0;
if (!modern::match_score(grp, m, home, away)) {
report.fail("matchday processing needs the score");
return;
}
const int ht = grp.fixtures.at(cursor), at = grp.fixtures.at(cursor + 1);
cursor += 2;
if (type == 0 || type == 10) modern::update_club_table(g, ht, at, home, away);
// MatchdayIntro sits between table updates and morale. Core owns its enabled
// replay scene draws; the old fixture callback remains a pure observer.
if ((sportschau || replay || ratings) && group_index >= 0) {
const auto view = sportschau_fixture_view(g, grp, group_index, m,
show_events ? *show_events : std::vector<ShowEvent>{});
if (replay) present_sportschau_replay(g, grp, view, game, rand, *replay);
if (ratings) { rate_sportschau_players(g, grp, view, rand, *ratings); store_awards(); }
if (sportschau) sportschau(g, view);
}
modern::update_morale(g, ht, home, away, 0, rand);
modern::update_morale(g, at, away, home, 1, rand);
modern::manager_match_record(g, grp, m, home, away, report);
if (report.unsupported) return;
modern::develop_players(g, grp, m, game, rand);
}
}
void stir_random(GameRandom& game, WatcomRandom& rand) {
int n = int16_t(rand.range(100, 300));
for (int i = 0; i < n; i++) game.range(0, 1);
}
bool league_screen_shown(const std::vector<uint8_t>& buttons, int param_1, int param_2, int league) {
if (param_2 == 0 || param_2 >= 200) return true; // called from the desk: always shown
int kind = param_1 - 1;
if (param_1 == 2 && (param_2 == 90 || param_2 == 120)) kind = 2;
int row = league;
if (league > 4) row = std::min(league + 12, 19);
if (param_2 == 45 && kind == 0) return false;
return buttons.at(size_t(kind + row * 9)) == 0;
}
int table_position(const ModernState& g, int team) {
if (team >= league_clubs()) return 2;
int league = league_of(team);
int rounds = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0;
if (rounds == 0) return -1;
unsigned u = unsigned(rounds - 1);
int word = int16_t(rd16(g.position_history, (size_t(u / 3) + size_t(team) * 13) * 2));
return (word >> ((u % 3) * 5)) & 0x1F;
}
void rate_manager(ModernState& g, int manager, int rating, int competition) {
uint8_t* hist = g.manager_ratings.data() + size_t(competition) * 10 + size_t(manager) * 0x3c;
std::copy_backward(hist, hist + 9, hist + 10); // Int16T: shift the last 9 up
hist[0] = uint8_t(rating);
int sum = 0;
for (int s = 0; s < 10; s++) sum = int16_t(sum + ((100 - 10 * s) * hist[s]) / 100);
wr16(g.manager_records, size_t(manager) * kManagerRecord + 0x8aa + size_t(competition) * 2, uint16_t(sum));
}
void manager_match_record(ModernState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report) {
const int type = grp.desc.at(0);
for (size_t k = 0; k < g.manager_teams.size(); k++) {
const size_t rec = k * kManagerRecord;
int side = -1, opponent = 0;
for (int s = 0; s < 2; s++)
if (g.manager_teams[k] == grp.fixtures.at(m * 2 + s)) {
side = s;
opponent = grp.fixtures.at(m * 2 + 1 - s);
break;
}
if (side < 0) continue;
// opponent id as the original keeps it: its low byte (0xFE for ids >= 256)
const int opp = opponent < 0x100 ? opponent : 0xFE;
// last results (home | away << 4) and fixtures, newest first
std::copy_backward(g.manager_records.begin() + rec + 0x212, g.manager_records.begin() + rec + 0x217,
g.manager_records.begin() + rec + 0x218);
std::copy_backward(g.manager_records.begin() + rec + 0x292, g.manager_records.begin() + rec + 0x2a6,
g.manager_records.begin() + rec + 0x2aa);
g.manager_records.at(rec + 0x212) = uint8_t(home_goals + (away_goals << 4));
for (int i = 0; i < 2; i++) wr16(g.manager_records, rec + 0x292 + i * 2, uint16_t(grp.fixtures.at(m * 2 + i)));
int own = side ? away_goals : home_goals, against = side ? home_goals : away_goals;
int rating = side ? 110 : 90; // an away game counts more
if (uint8_t(own) > uint8_t(against)) {
// league win bonus from the sponsor (record +0x173 thousands, less for
// higher +0x210 levels)
int bonus = g.manager_records.at(rec + 0x173);
if (type == 0 && bonus != 0) {
int level = g.manager_records.at(rec + 0x210);
if (level > 2) level--;
int32_t amount = (4 - level) * bonus * 1000;
if (g.level != 0) {
wr32(g.manager_records, rec + 0x314, rd32(g.manager_records, rec + 0x314) + uint32_t(amount));
wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) + uint32_t(amount));
}
}
rating += 20;
}
if (uint8_t(own) < uint8_t(against)) rating -= 20;
// MatchdayRuntimeField (u16 every 4 bytes): competitions that rate the manager. A league match
// counts the table place; a cup match its weight plus twice the rounds played in the
// stage and in every earlier one (link +0x15). All go into the league history (0).
static const uint16_t kRatingWeight[14] = {1, 12, 16, 20, 18, 0, 0, 0, 0, 14, 1, 0, 12, 10};
const uint16_t weight = type < 14 ? kRatingWeight[type] : 0;
if (weight != 0) {
if (type != 0) {
int add = weight;
uint32_t e = le32(grp.desc, 0xcc);
for (int guard = 0; guard < 64; guard++) {
add += g.memory.u8(e + 0x1d) * 2;
const int8_t previous = int8_t(g.memory.u8(e + 0x15));
if (previous == -1) break;
e = modern::cup_entry_address(previous);
}
rating += int16_t(add);
} else {
int league = league_of(g.manager_teams[k]);
int size = league < 9 ? kLeagueSizes[league] : 0;
rating += (size - modern::table_position(g, g.manager_teams[k])) * 4;
}
rating = std::clamp(int16_t(rating), int16_t(0), int16_t(200));
modern::rate_manager(g, int(k), rating, 0);
}
if (opp < first_foreign_cup()) {
size_t at = k * 0x690 + size_t(opp) * 10 + (side == 1 ? 5 : 0);
std::copy_backward(g.manager_results.begin() + at, g.manager_results.begin() + at + 4,
g.manager_results.begin() + at + 5);
g.manager_results.at(at) = uint8_t(own + (against << 4));
}
}
}
// ManagerOf(manager, 0, value): the manager's position of this season.
static void store_season_position(ModernState& g, int manager, int value) {
int season = std::min(g.season, 0x31);
g.manager_records.at(size_t(manager) * kManagerRecord + 0xda + size_t(season) * 3) = uint8_t(value);
}
// StoreStrengthHistory: strength and position history of a human manager's club (38 entries).
static void store_strength_history(ModernState& g, int manager) {
const size_t rec = size_t(manager) * kManagerRecord;
const int team = g.manager_teams.at(manager);
int n = g.manager_records.at(rec + 0x284);
if (n < 0x26) {
g.manager_records.at(rec + 0x284) = uint8_t(n + 1);
} else {
std::copy(g.manager_records.begin() + rec + 0x223, g.manager_records.begin() + rec + 0x248,
g.manager_records.begin() + rec + 0x222);
std::copy(g.manager_records.begin() + rec + 0x249, g.manager_records.begin() + rec + 0x26e,
g.manager_records.begin() + rec + 0x248);
n = 0x25;
}
g.manager_records.at(rec + 0x222 + n) = uint8_t(team_average(g, team, 0xFF).value);
int pos = modern::table_position(g, team);
if (pos == -1) pos = (kLeagueSizes[g.manager_records.at(rec + 0x210)] - 1) >> 1;
g.manager_records.at(rec + 0x248 + n) = uint8_t(pos);
}
void advance_league_rounds(ModernState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report,
const CompetitionWinnerHook& winner) {
// CalendarFirstLeague / CalendarLeagueCounts: first league and league count of competition bits 0-7
const uint8_t* kFirst = kGroupLeague; // (schedule.hpp: the groups of the loaded game)
const uint8_t* kCount = kGroupLeagues;
for (int bit = 0; bit < 19; bit++) {
if (!(competitions >> bit & 1)) continue;
if (bit >= 5) {
report.fail("cup round bookkeeping (AdvanceCup)");
return;
}
const int end = bit < 4 ? bit + 1 : 8;
for (int c = bit; c < end; c++) {
for (int league = kFirst[c]; league < kFirst[c] + kCount[c]; league++) {
if (league == 0) {
for (size_t m = 0; m < g.manager_teams.size(); m++) {
modern::advance_youth_teams(g, int(m), rand);
const size_t rec = m * kManagerRecord;
if (g.league_rounds.at(0) == 0x10) wr32(g.manager_records, rec + 0x320, rd32(g.manager_records, rec + 0x308));
uint8_t& d = g.manager_records.at(rec + 0x220); // point deduction countdown
if (d >> 5 == 1) d = (d & 0x1F) < 2 ? 0 : uint8_t((d & 0xE0) | ((d & 0x1F) - 1));
}
}
const int round = g.league_rounds.at(league);
g.league_rounds.at(league) = uint8_t(round + 1);
LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, kThreePoints[league] ? 1 : 0);
const int first = league_first_team(league);
for (int i = 0; i < t.size; i++) {
const int team = first + i;
const int rank = t.rank(i);
size_t at = (size_t(round / 3) + size_t(team) * 13) * 2;
wr16(g.position_history, at, uint16_t(rd16(g.position_history, at) | rank << ((round % 3) * 5)));
const int manager = g.manager_of(team);
if (manager >= 0) {
int base = first;
if (league_first_team(3) <= base) base -= 18;
store_season_position(g, manager, base + rank + 1);
store_strength_history(g, manager);
}
}
// OnceSecondDivisionLeagueHasPlayedAll, once the second division (league 2) has played all its rounds
// (in the last competition of the loop, after each of its leagues): the
// clubs placed 1-2 in leagues 2 and 3 (TablePosition, positions counted from 0)
// go into the team list of the promotion play-off (Teams), its results
// (MatchdayGroupWorkspace) are cleared and competition MatchdayRuntimeField2 (0xd) starts
if (c + 1 == end && g.league_rounds.at(2) == league_matchdays(2)) {
uint32_t n = 0;
for (int l = 2; l < 4; l++)
for (int team = league_first_team(l); team < league_first_team(l) + kLeagueSizes[l]; team++) {
const uint8_t pos = uint8_t(modern::table_position(g, team));
if (pos != 0 && pos < 3) g.memory.set16(::bmh::layout::Teams + n++ * 2, uint16_t(team));
}
for (uint32_t i = 0; i < 0x20; i++) g.memory.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc);
for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xd)
if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == 0xd) break;
if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) {
g.memory.set8(::bmh::layout::ActiveSelectors + i, 0xd);
break;
}
}
}
// the first division is over: its leader (OnTableJust(0, 0) on the table just
// computed) is champion - the winner screen (CompetitionWinnerScreen(0, 0), clears
// CareerSession_BeginFriendlyOpponentTable_ExecutableField2), the list of title holders (ListTitleHoldersAf(club, 0)), a human
// champion's record (+0x8a4) and Cup_AdvanceCup_RuntimeField6
if (league == 0 && g.league_rounds.at(0) == league_matchdays(0)) {
int champion = -1;
for (int i = 0; i < t.size && champion < 0; i++)
if (t.rank(i) == 0) champion = first + i;
if (champion < 0) champion = 0; // (OnTableJust returns 0 when none is found)
if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner)
winner(g, {0, uint16_t(champion)});
if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) g.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
g.memory.set16(::bmh::layout::Titles + uint32_t(std::min<int>(g.season, 0x31)) * 2, uint16_t(champion));
const int manager = g.manager_of(champion);
if (manager >= 0) {
const size_t at = size_t(manager) * kManagerRecord + 0x8a4;
wr16(g.manager_records, at, uint16_t(rd16(g.manager_records, at) + 1));
}
g.memory.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, uint16_t(champion));
}
}
}
}
}
} // namespace bmh::modern
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/matchday.hpp"
// What happens to a matchday after the final whistle (BMH.exe V2.24 + supported rule profile patch).
//
// The matchday driver (the function around 0x39xxx that calls EndPhase for every
// phase) continues after the last phase with, per match group and match:
// 1. UpdateClubTable league record of both clubs (points, goals, streaks, records)
// 2. morale both teams' morale moves towards the result (Watcom rand)
// 3. ManagerMatchRecord a human manager's match record, bonuses and rating
// 4. DevelopPlayers player development: team trends move form/technique/condition and
// skills (game RNG), appearances, injuries heal by one matchday,
// yellow card bans, card counters per competition
// Before that, the end of every phase calls FinishMatch per match: it stores the end
// minute and lets a human manager's players get used to their places on the tactics
// board and earn their bonus (game RNG).
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/sportschau_presentation.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// Score of match m of a group (MatchScore, read mode): league result byte or the cup
// result of the current leg. Returns false if the score is not known.
bool match_score(const MatchGroup& g, int m, int& home, int& away);
// BookMoney2: books `amount` from a human manager's account (record +0x314). Without
// `force` a payment larger than balance + credit (+0x31c) is refused (the original shows a
// message). Game level 0 has no money at all.
// With `statistics` (the caller sets FinanceStatisticsEnabled) the amount is also added to the
// income (+0x874, negative amounts) or expense (+0x8a0) statistics.
bool book_money(ModernState& g, int manager, int32_t amount, bool force, bool statistics = false);
// PayBonus: bonus of one player on the tactics board: the board's bonus rate for
// `index` (slot byte 0x12 + index: 0 goal, 1 point, 2 appearance, ...) times the player's
// bonus base (slot +0x50) / 100, five-fold for index > 2. With `pay` the tax (record
// +0x172) is deducted and the amount is paid. Returns the amount.
uint32_t pay_bonus(ModernState& g, int manager, int board_slot, int index, bool pay);
// PlayerStatistic: statistics of one player. kind 0 appearance, 1 goal, 2 assist.
// competition_type = descriptor byte 0; `manager` = human manager of the player's team
// or -1; `slot` = the player's slot relative to the squad start (tactics board index).
void player_statistic(ModernState& g, int competition_type, int player, int manager, int slot, int kind, int minute);
// FinishMatch for match m at the end of a phase lasting `minute` minutes.
void finish_match(ModernState& g, MatchGroup& grp, int m, int minute, GameRandom& game);
// UpdateClubTable: league record of home and away club after a result.
void update_club_table(ModernState& g, int home, int away, int home_goals, int away_goals);
// Morale step of the matchday driver for one side (0 home, 1 away) of a finished match.
void update_morale(ModernState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand);
// DevelopPlayers: player development and bookkeeping for both teams of match m.
void develop_players(ModernState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand);
// Steps 1, 2 and 4 for every match of a group that was played (voided matches, e.g.
// awarded 0:2, are skipped). Human records and bonuses use manager_match_record.
void process_group(ModernState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index = -1, const SportschauFixtureHook& sportschau = {},
const std::vector<ShowEvent>* show_events = nullptr,
const SportschauReplayHooks* replay = nullptr);
// Loaded Source caller retains mutable descriptor award ownership; legacy raw
// probes without executable policy keep their existing immutable input API.
void process_group(ModernState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay,
const SportschauRatingTables* ratings);
// ManagerMatchRecord: a human manager's record of match m (last results and fixtures, league
// win bonus, the manager rating via ManagerMatchRecord2 and the results per opponent).
void manager_match_record(ModernState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report);
// TablePosition: current table position of a team (-1 before the first round).
int table_position(const ModernState& g, int team);
// ManagerMatchRecord2: adds a match rating (0-200) to a manager's history of competition
// `competition` and stores the weighted average in the manager record (+0x8aa).
void rate_manager(ModernState& g, int manager, int rating, int competition);
// StirRandom: when a result or table screen (LeagueScreenShown) is left, the game stirs its
// random numbers: WatcomRandom(100, 300) game draws are thrown away.
void stir_random(GameRandom& game, WatcomRandom& rand);
// LeagueScreenShown(param_1, param_2): whether the screen is shown at all. param_1 1 = table,
// 2 = results; param_2 = the phase end minute (90 / 120 / 45 ...); league = descriptor
// +0xcc (CareerSession_BeginFriendlyOpponentTable_RuntimeField2). The desk buttons (block LeaguePresentationOptions, 9 bytes per league) switch it off.
bool league_screen_shown(const std::vector<uint8_t>& buttons, int param_1, int param_2, int league);
// The rest of AdvanceTurn after a matchday: for every competition bit of the day (bits
// 0-4 = leagues) the round counter LeagueRoundCounters advances, the table is recomputed and
// each club's rank is added to the position history (*LeagueRankHistory); human managers get their
// season position and strength history updated. This API accepts league bits only;
// finish_event dispatches bits 5+ separately through advance_cup.
void advance_league_rounds(ModernState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report,
const CompetitionWinnerHook& winner = {});
// TicketPriceDraws: the random draws of a human manager's (disabled) ticket price drift.
void ticket_price_draws(const ModernState& g, int manager, WatcomRandom& rand);
// Modern version of the function sportschau_presentation.hpp declares for Classic.
int sportschau_source_setting_index(const ModernState& state, const MatchGroup& group);
} // namespace bmh::modern
File diff suppressed because it is too large. Load diff
+149
View File
@@ -0,0 +1,149 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
#include "game/matchday_setup.hpp"
// Before the first minute of a matchday (BMH.exe V2.24 + supported rule profile patch).
//
// When "Weiter" reaches a day with a calendar event, AdvanceTurn prepares the matchday:
// 1. DayCompetitions2 builds one match group per league playing today (FixturesFromGenerateFixtures):
// fixtures of the next round, the result bytes of that round, and per match the
// weather and the referee (MatchWeather). Every team is then prepared for the match
// (PrepareTeam: cards of this competition, injuries, line-up flags) and gets an
// automatic line-up (Int2 mode 100). CycleManagerOptions advances the human
// managers' option byte 0 to the next enabled setting.
// 2. CurrentMatchday = WatcomRandom(0, 10000); PrepareEvent shuffles the order in which
// the human managers see their pre-match desks (one game draw per manager).
// 3. The matchday driver FinishEvent (called through the supported rule profile wrapper
// MatchdaySetupOperation) starts: "played" flags are cleared, the human tactics boards note who
// starts, every group's unplayed result bytes are set to 0:0 (anything else voids
// the match), and per match the attendance (Attendance) and the side records
// (BuildSideRecords3 + BuildSideRecords2) are computed.
// After that the minute loop (match_engine.hpp) runs.
//
// Ported for league matchdays of computer teams. Cups, indoor tournaments, the winter
// break postponements, human teams in a match (pre-match desk, own stadium, income) and
// Teams with fewer than 8 fit players receive the original 0:2 forfeit award.
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// Globals of the original that the preparation reads but that are not part of ModernState.
// The 0xD0-byte descriptor of match group `index` as it is left in memory (block MatchdayGroupDescriptors) from
// the previous matchday: the preparation only overwrites what it needs, so for example
// the referee bytes of matches without referee keep old values.
Bytes group_descriptor(const ModernState& g, size_t index);
// Writes the descriptors back (the per-match bytes, void mask, attendance, league/cup).
void store_group_descriptors(ModernState& g, const std::vector<MatchGroup>& groups, bool with_log = false);
// MatchWeather: temperature (descriptor +0x30), rain (+0x50) and referee (+0x10) of
// match m of a group.
void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand);
// PrepareTeam: prepares the squad of `team` before a match of a competition of class
// `cls` (MatchEngineRuntimeField9[type]: 0 league, 1-4 cups with their own card counters, 0xFF none).
// `index` is the team's position in the flat fixture list (home 0, away 1, ...).
void prepare_team(ModernState& g, int team, int cls, int index);
// DayCompetitions2(..., 1): builds the match groups of the competitions in `competitions`
// (SavedCompetition) and prepares all teams. Returns the groups in the order of the original.
// DayCompetitions: the competitions of a day from its calendar entry (CompetitionCalendar): the low
// 15 bits, with special entries mapped (0x4001 group -> 0x8000, 0x4002 -> layout field indoor
// tournament, 0x4004 -> layout field, 0x4006 -> national-only flag or nothing) and the four league
// groups 0x1e00 rotating with the season.
uint32_t day_competitions(const ModernState& g, uint16_t entry);
// IndoorTournamentDraw: the draw of an indoor tournament (eight clubs, the host names it).
void indoor_tournament_draw(ModernState& g, GameRandom& game, WatcomRandom& rand);
// The part of IndoorTournamentDraw that also runs before the Masters (CupRuntimeField != 0, no draw):
// before the first tournament the Masters points (Cup_AdvanceCup_ExecutableField) and invitations
// (MatchdaySetup_IndoorTournamentDraw_RuntimeField) are cleared; the name becomes "In ", the results of block MatchdayGroupWorkspace 0xCC and
// the played counters of the cup entries 25-29 0.
void indoor_tournament_reset(ModernState& g);
std::vector<MatchGroup> setup_matchday(ModernState& g, uint32_t competitions, const MatchdayContext& ctx,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// MatchdayNeedsManagerDesks / AdvanceTurn: after preparation and manager-order shuffling,
// F6 (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField == 0) admits the whole manager desk loop only if a manager plays.
// Postponed/already played league fixtures do not count. Opening/closing season
// desks, national friendlies and the Source auto-continue latch retain their gates.
// Read-only; callers still simulate an event whose desks are skipped.
bool matchday_needs_manager_desks(const ModernState&, uint16_t calendar_entry,
const std::vector<MatchGroup>&);
// CycleManagerOptions: option byte 0 of every human manager moves on to the next setting that
// is enabled in the manager record (+0x218, a bit mask of settings 1-8).
void cycle_manager_options(ModernState& g);
// MatchModeBits plus the flags added by BuildSideRecords: the "mode bits" passed to the
// attendance. Bits 0-4 a crowd interest value (per competition type, rising towards the
// end of the league season), 0x20 random spread, 0x80 no league match, 0x100 cup of
// class 1, 0x200 other cups.
int match_mode_bits(const ModernState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report);
// Attendance: attendance of a match. For a human home club also the gate and kiosk
// income, the attendance statistics of its record and a possible riot (message, damage).
// competition_type = byte 0 of the group descriptor (MatchdaySetupRuntimeField14). Bits 0x180
// select cup gate sharing, including the away human manager's income/statistics.
int attendance(ModernState& g, int home, int away, int bits, int temperature, int rain, int competition_type,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// PrepareEvent(ManagerCount, NextDeskManager): shuffles the order of the human managers' pre-match
// desks in place - the order of the matchday before is shuffled again, not 0, 1, ... - and
// returns it (manager indices). One game draw per manager: entry i swaps with entry G(0, n - 1).
std::vector<int> shuffle_manager_order(ModernState& g, GameRandom& game);
// The start of FinishEvent up to the first minute: flags, void masks, attendance and side
// records for every match of every group, including the live match choice (AutoLineup) and
// the man marking of human managers (KickOff). Human teams draw from `game` in their
// ratings (team_rating).
void kick_off(ModernState& g, std::vector<MatchGroup>& groups, const MatchdayContext& ctx, WatcomRandom& rand,
GameRandom& game, MinuteReport& report, bool select_sportschau = false,
uint16_t club_threshold = 90);
} // namespace bmh::modern
namespace bmh::modern {
// CurrentMatchday = WatcomRandom(0, 10000), drawn by AdvanceTurn after the preparation (kept
// in the savegame).
inline void draw_matchday_number(ModernState& g, WatcomRandom& rand) {
const int v = rand.range(0, 10000);
if (g.memory.has(::bmh::layout::CurrentMatchday)) g.memory.set32(::bmh::layout::CurrentMatchday, uint32_t(v));
}
} // namespace bmh::modern
namespace bmh::modern {
// BuildPoolsCoupon, at a human manager's pre-match desk: the pools coupon (block DeskActions_SubmitPoolsCoupon_RuntimeField) - up
// to 11 of today's matches between clubs of similar strength (team_average 0x1ff within
// 17); CareerSession_DispatchToto_RuntimeField = their number.
// Teams without a squad (national teams) draw their average from `rand` (TeamRating).
void build_pools_coupon(ModernState& g, const std::vector<MatchGroup>& groups, WatcomRandom* rand = nullptr);
// EvaluatePoolsCoupon(0) at full time of that matchday: the results of the coupon's matches,
// MatchdaySetup_EvaluatePoolsCoupon_RuntimeField[i] = 1 home win, 0 draw, 2 away win.
void evaluate_pools_coupon(ModernState& g, const std::vector<MatchGroup>& groups);
// EvaluatePoolsCoupon(1) at the end of the matchday: with 11 matches on the coupon every human
// manager's tip (Coupon + manager * 0x14: stake u32, tips +8..+0x12) is settled - the
// stake is booked (BookMoney2, may fail: "Ihr Tototipp wurde nicht berücksichtigt ..."
// MatchdaySetup_SettlePoolsCoupon_TextPointer), the hits counted (+0x13), from 9 on the stake times the quota
// (MatchdaySetupRuntimeField13: 10, 20, 50) is won (+4) and booked; the stake is cleared. The coupon's
// matches are counted again in the groups of the matchday (CareerSession_DispatchToto_RuntimeField; the outcomes stay
// those read after the second half, PoolsOpenFlag / MatchdaySetup_EvaluatePoolsCoupon_RuntimeField). The toto screen
// it shows (LeagueTableRangeDialog) draws nothing.
void settle_pools_coupon(ModernState& g, const std::vector<MatchGroup>& groups);
// Modern version of the function sportschau_presentation.hpp declares for Classic.
bool sportschau_selected(const ModernState& g, int home);
} // namespace bmh::modern
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/game/modern_state.hpp"
#include "modern/game/matchday.hpp"
#include "modern/game/prediction.hpp"
namespace bmh::modern {
namespace {
// The shared match core passes the GameState base; Modern games always hold a ModernState.
void statistic(GameState& g, int competition_type, int player, int manager, int slot, int kind, int minute) {
player_statistic(static_cast<ModernState&>(g), competition_type, player, manager, slot, kind, minute);
}
int prediction(GameState& g, int team, int mode, std::array<uint8_t, 24>& buf, int* size_word) {
return table_prediction(static_cast<ModernState&>(g), team, mode, buf, size_word);
}
} // namespace
const SeasonHooks& season_hooks() {
static const SeasonHooks hooks{&statistic, &prediction};
return hooks;
}
} // namespace bmh::modern
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The game state of the Modern season core.
//
// Modern started as a fork of the Classic season core (docs/new_engine). Its season
// functions take ModernState instead of GameState: the shared parts (formats, match
// core, line-ups, ratings) keep working on the GameState base, and overload resolution
// always prefers the Modern season function over a Classic one of the same name.
// Modern-only data (world layout, UTF-8 names, ...) is added here, never to GameState.
#include <cstddef>
#include <utility>
#include "game/state.hpp"
#include "game/world_layout.hpp"
namespace bmh::modern {
// Dimensions of the running world (WorldLayout). Modern code uses these accessors where
// the Classic sources have the fixed numbers (138 league clubs, 90 German clubs, 168, the
// pool slots 0xb70/0xb9c/0xbec/0xc00, 3150 slots); no_team() replaces kNoTeam (0x165).
inline int league_clubs() { return world_layout().league_teams; }
inline int german_clubs() { return world_layout().german_teams; }
inline int first_foreign_cup() { return world_layout().first_foreign_cup(); }
inline size_t transfer_list_slot() { return world_layout().transfer_list; }
inline size_t free_agent_slot() { return world_layout().free_agents; }
inline size_t foreign_offer_slot() { return world_layout().foreign_offers; }
inline size_t pool_end_slot() { return world_layout().pool_end; }
inline size_t total_squad_slots() { return world_layout().total_slots; }
// The callbacks the shared match core uses for season functions (SeasonHooks).
const SeasonHooks& season_hooks();
struct ModernState : GameState {
ModernState() { season_hooks = &modern::season_hooks(); }
// Takes over a state built by shared code (save loading, career setup).
ModernState(GameState&& g) : GameState(std::move(g)) { season_hooks = &modern::season_hooks(); }
ModernState(const GameState& g) : GameState(g) { season_hooks = &modern::season_hooks(); }
};
} // namespace bmh::modern
+990
View File
@@ -0,0 +1,990 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/month.hpp"
#include "game/trace.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <optional>
#include <string>
#include <vector>
#include "game/lineup.hpp"
#include "modern/game/matchday.hpp"
#include "game/messages.hpp"
#include "modern/game/prediction.hpp"
#include "game/schedule.hpp"
#include "modern/game/season.hpp"
#include "modern/game/weekly.hpp"
#include "game/human_buyer_sale.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xB0C; // manager record
constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kTransferList = ::bmh::layout::EditorList;
constexpr uint32_t kListEntry = 0x58;
// MonthRuntimeField2: development steps by strength / 10; the ten bytes after it (PlayerCard_PlayerCardMarketValue_RuntimeField)
// are the extra value above 500 points.
constexpr uint8_t kDevelopment[20] = {6, 6, 6, 5, 5, 5, 4, 4, 3, 1, 10, 15, 20, 30, 40, 45, 55, 75, 85, 95};
// BalancePlanRuntimeField5: value of the facilities (maintenance per month), u16 per facility.
constexpr uint16_t kFacilityValue[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600,
2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000};
// BalancePlanRuntimeField6: monthly income of facilities 0-5 per level.
constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000};
// MonthRuntimeField3: share of the new list entries per kind (free agents, big clubs, foreign
// agents, small clubs), percent.
constexpr int16_t kListShare[4] = {47, 35, 10, 8};
// MonthRuntimeField4 / MonthRuntimeField5: players a club wants per position (big / small squads).
constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4};
uint32_t rd32(const std::vector<uint8_t>& v, size_t o) {
return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16) | uint32_t(v.at(o + 3)) << 24;
}
void wr32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i));
}
void add32(std::vector<uint8_t>& v, size_t o, int32_t x) { wr32(v, o, rd32(v, o) + uint32_t(x)); }
// BoughtEntry: index + 1 of a player in the table of players bought for later / on loan
// (Career_RemoveJoinLoans_RuntimeField), 0 if none.
int bought_entry(const ModernState& g, int player) {
for (int k = 0; k < 200; k++) {
const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4);
if (e != 0 && int(e & 0xFFF) == player) return k + 1;
}
return 0;
}
// PlayerOnTransferListFirstPoolSlots: index + 1 of the list entry of the player in an absolute squad slot (the
// first 44 pool slots), 0 if he is not on the list.
int list_index(const ModernState& g, int slot) {
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
for (int s = int(transfer_list_slot()); s < int(transfer_list_slot()) + 0x2c; s++)
if ((g.squad_slots[size_t(s)] & 0xFFF) == player) return s - int(transfer_list_slot()) + 1;
return 0;
}
// FirstFreeSlotSquad(start, count): first empty squad slot from `start`, -1 if none.
int free_slot(const ModernState& g, int start, int count) {
for (int s = start; s < start + count && s < int(g.squad_slots.size()); s++)
if (g.squad_slots[size_t(s)] == 0xFFF) return s;
return -1;
}
// ListPlayer: puts the player in an absolute squad slot on the transfer list: the first
// free list slot, asking price and demand percentages, 5-8 weeks, the market value; human
// managers with a matching search profile are told.
bool list_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report) {
StaticMemory& mem = g.memory;
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
if (bought_entry(g, player) != 0) {
report.fail("transfer list: the player is bought for later (internal error 0x38)");
return false;
}
if (list_index(g, slot) != 0) {
report.fail("transfer list: the player is listed already (ListPlayer message box)");
return false;
}
// (the original passes 0xb70 + 0x28 as the count: the search runs on past the list)
const int free = free_slot(g, int(transfer_list_slot()), int(transfer_list_slot()) + 0x28);
if (free == -1) return false; // message box MonthRuntimeField6
if (free >= int(transfer_list_slot()) + 0x2c) {
report.fail("transfer list: the free slot lies beyond the list (the original overwrites memory)");
return false;
}
g.squad_slots[size_t(free)] = uint16_t(player);
const uint32_t e = kTransferList + uint32_t(free - int(transfer_list_slot())) * kListEntry;
if (slot < int(transfer_list_slot())) {
const int seller = modern::slot_team(slot);
uint16_t field = uint16_t(seller);
mem.set16(e + 8, field);
if (g.manager_of(seller) >= 0) mem.set8(e + 9, uint8_t(mem.u8(e + 9) | 0x80));
mem.set8(e + 0x54, uint8_t(rand.range(0x4b, 0x7a)));
mem.set8(e + 0x55, uint8_t(rand.range(0x5c, 100)));
if (seller >= german_clubs()) mem.set8(e + 0x54, uint8_t(mem.u8(e + 0x54) + rand.range(5, 0xf)));
} else {
mem.set16(e + 8, 0xFFF);
mem.set8(e + 0x54, uint8_t(rand.range(0x46, 0x69)));
mem.set8(e + 0x55, uint8_t(rand.range(0x3c, 0x60)));
}
mem.set8(e + 0x56, uint8_t(rand.range(5, 8)));
uint32_t fee = 0, salary = 0;
modern::market_value(g, slot, 0, mem.u8(e + 0x54), fee, salary, 1, 0, rand);
mem.set32(e + 0x2c, fee);
mem.set32(e + 0x30, salary);
for (int b = 0; b < 4; b++) mem.set16(e + uint32_t(b) * 2, 0xFFFF);
for (size_t m = 0; m < g.manager_teams.size(); m++) modern::search_profile_news(g, int(m), e, g.squad_slots[size_t(free)]);
return true;
}
// PickFreeAgent(from, to): a random free agent in the pool slots from..to-1 who is not on
// the list and not bought for later.
int pick_free_agent(const ModernState& g, int from, int to, WatcomRandom& rand, MinuteReport& report) {
std::vector<int> slots;
for (int s = from; s < to; s++) {
const int p = g.squad_slots.at(size_t(s)) & 0xFFF;
if (p != 0xFFF && list_index(g, s) == 0 && bought_entry(g, p) == 0) slots.push_back(s);
}
if (slots.empty()) {
report.fail("transfer list: no free agent (internal error 0x26)");
return -1;
}
return slots[size_t(rand.range(0, int(slots.size()) - 1))];
}
// InPseudoSquad: the player of a slot also plays in the squad of the pseudo club 0x165.
bool in_pseudo_squad(const ModernState& g, int slot) {
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
const SquadRange r = squad_range(no_team());
for (size_t s = r.first; s < r.first + r.count; s++)
if ((g.squad_slots[s] & 0xFFF) == player) return true;
return false;
}
// Int5(first, last): a computer club (every second one, starting alternately at the
// first or second, MonthRuntimeField7) with too many goalkeepers or too many players in a line
// puts one of them on the list. With no club found in first..last the search is repeated
// over the big clubs.
void list_club_player(ModernState& g, int first, int last, WatcomRandom& rand, MinuteReport& report) {
const int8_t* wanted = first < german_clubs() ? kWantedBig : kWantedSmall; // Attempt
for (;;) {
std::vector<int16_t> teams(static_cast<size_t>(league_clubs()));
std::vector<uint32_t> keys(static_cast<size_t>(league_clubs()));
int n = 0; // local_14
g.list_toggle = g.list_toggle + 1 == 2 ? 0 : g.list_toggle + 1;
int best_line = 0; // local_1c, keeps its value between the clubs
for (int team = first + g.list_toggle; team < last; team += 2) {
if (g.manager_of(team) >= 0) continue;
const SquadRange range = squad_range(team);
int8_t count[4] = {0, 0, 0, 0}; // local_50
const int players = int16_t(modern::squad_count(g, team, 3));
for (int s = 0; s < players; s++) {
const int p = g.squad_slots.at(range.first + size_t(s)) & 0xFFF;
if (p != 0xFFF) count[g.players.at(size_t(p)).w364 & 3]++;
}
int key_base = 0, line = 0;
bool add = false;
if (rand.range(0, 1) + 2 < count[0]) {
// three or four goalkeepers
line = 0;
key_base = count[0] + 100;
add = true;
} else if (players > 0xd) {
const int flags = (g.team_flags.at(size_t(team)) >> 0xc) & 3;
if (rand.range(0, flags * 2 + 2) != 0) {
int8_t most = 0; // local_28
for (int k = 1; k < 4; k++) {
const int8_t over = int8_t(count[k] - wanted[k]);
if (most < over) most = over, best_line = k;
}
int chosen = best_line;
if (most == 0) chosen = rand.range(1, 3);
key_base = most * 8;
const int8_t room = int8_t(range.count - ((team < german_clubs() ? 1 : 0) + 2));
if (room < players) key_base += (players - room) * 4;
line = chosen;
add = true;
}
}
if (add) {
const int a = rand.range(0, 5), b = rand.range(0, 5);
keys[n] = uint32_t((key_base + a - b) * 4 + int8_t(line));
teams[n] = int16_t(team);
n++;
}
}
int pick = league_clubs(); // sVar11
int slot = -1; // unaff_EDI: the slot tried last
if (n != 0) {
quicksort_by_key(teams.data(), keys.data(), n);
for (pick = 0; pick < n; pick++) {
const int team = teams[pick];
const SquadRange range = squad_range(team);
const int players = int16_t(modern::squad_count(g, team, 2));
const int line = int(keys[pick] & 3);
int tries = 0;
bool again;
do {
slot = int(range.first) + rand.range(0, players - 1);
const int p = g.squad_slots.at(size_t(slot)) & 0xFFF;
const bool taken = bought_entry(g, p) != 0 || list_index(g, slot) != 0;
tries++;
again = int(g.players.at(size_t(p)).w364 & 3) != line || in_pseudo_squad(g, slot) || taken;
} while (tries < 0x23 && again);
if (tries < 0x23) break;
}
// (when no club had a fitting player the slot tried last is listed all the same)
}
if (pick < league_clubs()) {
list_player(g, slot, rand, report);
return;
}
if (first == 0) {
report.fail("transfer list: no club to take a player from (internal error 0x28)");
return;
}
first = 0;
last = german_clubs();
}
}
// CareerFirstSteps: new players on the transfer list. The number depends on how full the list
// is (at most 37 entries); free agents of the pool are preferred while there are many.
void new_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report) {
uint8_t count[5] = {0, 0, 0, 0, 0}; // local_18: listed, free agents, foreign, listed of both
for (int s = int(transfer_list_slot()); s < int(pool_end_slot()); s++) {
if (g.squad_slots.at(size_t(s)) == 0xFFF) continue;
if (!(s < int(transfer_list_slot()) + 0x28 || int(transfer_list_slot()) + 0x2c <= s)) continue;
const int cls = s < int(free_agent_slot()) ? 0 : s < int(foreign_offer_slot()) ? 1 : 2;
count[cls]++;
if (cls != 0 && list_index(g, s) != 0) count[cls + 2]++;
}
uint8_t add[4] = {0, 0, 0, 0}; // local_10
const int r = rand.range(2, 0x16);
uint8_t n = uint8_t(r);
if (count[0] + int8_t(r) >= 0x26) {
n = uint8_t(0x25 - count[0]);
if (int8_t(n) <= 0) return;
}
count[1] = uint8_t(count[1] - count[3]);
count[2] = uint8_t(count[2] - count[4]);
for (int16_t u = count[1]; n != 0 && u > 0x36; u--) n--, add[0]++;
for (int16_t u = count[2]; n != 0 && u > 0xe; u--) n--, add[2]++;
for (int k = 0; k < 4; k++) add[k] = uint8_t(add[k] + int8_t(kListShare[k] * int8_t(n) / 100));
if (count[1] < add[0]) {
add[1] = uint8_t(add[1] + ((add[0] - count[1]) >> 1));
add[0] = count[1];
}
if (count[2] < add[2]) {
add[3] = uint8_t(add[3] + ((add[2] - count[2]) >> 1));
add[2] = count[2];
}
int8_t total = 0;
for (int k = 0; k < 4; k++) total = int8_t(total + add[k]);
if (total < 4) add[1] = uint8_t(add[1] + rand.range(2, 4));
if (add[3] == 0 && add[1] != 0 && rand.range(0, 10) == 5) add[3]++, add[1]--;
// (MonthRuntimeField8, a debug switch for club players only, is 0)
for (int k = 0; k < 4 && !report.unsupported; k++) {
uint8_t left = add[k];
if (left == 0) continue;
switch (k) {
case 0:
case 2:
while (left != 0 && !report.unsupported) {
const int slot = k == 0 ? pick_free_agent(g, int(free_agent_slot()), int(foreign_offer_slot()), rand, report)
: pick_free_agent(g, int(foreign_offer_slot()), int(pool_end_slot()), rand, report);
if (slot < 0) return;
if (list_player(g, slot, rand, report)) left--;
}
break;
case 1:
while (left-- != 0 && !report.unsupported) list_club_player(g, 0, german_clubs(), rand, report);
break;
case 3:
while (left-- != 0 && !report.unsupported) list_club_player(g, german_clubs(), league_clubs(), rand, report);
break;
}
}
}
// Loaned players whose time is up go back to their clubs (part of DayStepRest2).
void return_loans(ModernState& g, WatcomRandom& rand, GameRandom* game, MinuteReport& report) {
StaticMemory& mem = g.memory;
for (int s = 0; s < int(transfer_list_slot()) && !report.unsupported; s++) {
const int player = g.squad_slots.at(size_t(s)) & 0xFFF;
if (player == 0xFFF) continue;
const int k = bought_entry(g, player) - 1;
if (k < 0) continue;
const uint32_t e = mem.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4);
const int owner = int(e >> 12 & 0x3FF), club = int(e >> 22 & 0x3FF); // local_30, local_28
const int owner_manager = g.manager_of(owner);
const int borrower_manager = g.manager_of(club);
// Human owners have a saved tactics-board row in ClubInfo_FormatError_RuntimeField and a matching
// player ID/manager in Career_CareerManagersEnd_RuntimeField/ClubInfo_FormatError_RuntimeField2 (Fail). Restore it on expiry;
// AI owners have no snapshot. Stage the complete return so malformed state
// or a failed lineup cannot lose the loan ledger first.
if (owner_manager >= 0 || borrower_manager >= 0) {
const uint8_t remaining = mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k));
if (remaining != 1) {
// Source decrements an unsigned byte and returns only when the
// decremented byte is zero (DayStepRest2). A malformed/stale zero
// therefore wraps to 0xff instead of expiring immediately.
mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), uint8_t(remaining - 1));
continue;
}
if ((owner_manager >= 4) || (owner_manager >= 0 &&
(!mem.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField + 0x17) || !mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField + 0x41f) ||
!mem.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + 0x0b) || !mem.has(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager))))) {
report.fail("month change: human-owner loan record is incomplete");
return;
}
int snapshot_slot = -1;
if (owner_manager >= 0) {
for (int i = 0; i < 12; ++i) {
if (mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(i) * 2) == uint16_t(player) &&
mem.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2 + uint32_t(i)) == uint8_t(owner_manager)) {
snapshot_slot = i;
break;
}
}
}
const SquadRange owner_range = squad_range(owner);
const int owner_slot = free_slot(g, int(owner_range.first), int(owner_range.count));
const SquadRange borrower_range = squad_range(club);
bool borrower_has_player = false;
for (size_t i = 0; i < borrower_range.count; ++i)
if ((g.squad_slots.at(borrower_range.first + i) & 0x0fff) == player) borrower_has_player = true;
if ((owner_manager >= 0 && snapshot_slot < 0) || owner_slot < 0 || !borrower_has_player ||
(owner_manager >= 0 && size_t(owner_manager) * kBoard +
size_t(owner_range.count) * kBoardSlot > g.tactics.size())) {
report.fail("month change: human-owner loan cannot be restored safely");
return;
}
if (borrower_manager >= 0 && !g.loan_return_screen) {
report.fail("month change: expiring human-borrower loan needs its Source return dialog owner");
return;
}
ModernState staged = g;
try {
staged.memory.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), 0);
staged.memory.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0);
staged.squad_slots.at(size_t(owner_slot)) = uint16_t(player);
if (!modern::remove_from_seller(staged, club, player, report)) return;
if (owner_manager >= 0) {
const size_t board = size_t(owner_manager) * kBoard +
size_t(owner_slot - int(owner_range.first)) * kBoardSlot;
const uint32_t snapshot = ::bmh::layout::ClubInfo_FormatError_RuntimeField + uint32_t(snapshot_slot) * uint32_t(kBoardSlot);
for (size_t b = 0; b < kBoardSlot; ++b)
staged.tactics.at(board + b) = staged.memory.u8(snapshot + uint32_t(b));
staged.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + uint32_t(snapshot_slot) * 2, 0x0fff);
const uint8_t count = staged.memory.u8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager));
if (count == 0) {
report.fail("month change: human-owner loan count is inconsistent");
return;
}
staged.memory.set8(::bmh::layout::DeskActions_Unsupported_RuntimeField + uint32_t(owner_manager), uint8_t(count - 1));
}
// DayStepRest2 posts the return notice to whichever owner/borrower
// managers exist.
const std::string notice = message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer) + staged.player_name(player) +
message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer2) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer3) + staged.club_name(club) +
message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer4) + staged.club_name(owner) + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer5);
if (borrower_manager >= 0) {
const int keep = staged.loan_return_screen(staged, borrower_manager,
notice + message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer6));
if (keep < 0) {
report.fail("month change: human-borrower loan return dialog stopped");
return;
}
if (keep != 0) {
// DayStepRest2 makes the borrower the active manager before
// RowWhose/Range2. The two W(90,100) draws occur even
// when all four special offer slots are occupied.
staged.memory.set8(::bmh::layout::ActiveManager, uint8_t(borrower_manager));
int offer = 0;
while (offer < 4 && staged.memory.u32(::bmh::layout::OfferSlots + uint32_t(offer) * 4) != 0xffffffffu)
++offer;
if (offer < 4 && (!game || !staged.loan_return_offer_screen)) {
report.fail("month change: OpenTransferEditor return-offer editor has no typed runtime owner");
return;
}
WatcomRandom offer_rand = rand;
std::optional<GameRandom> offer_game;
if (game) offer_game = *game;
const int percent = offer_rand.range(90, 100);
const int demand = offer_rand.range(90, 100);
if (offer < 4) {
const uint32_t entry = kTransferList + uint32_t(40 + offer) * kListEntry;
uint16_t team_word = uint16_t(owner);
if (owner_manager >= 0) team_word |= 0x8000;
staged.memory.set16(entry + 8, team_word);
for (int bid = 0; bid < 4; ++bid)
staged.memory.set16(entry + uint32_t(bid) * 2, 0xffff);
staged.memory.set8(entry + 0x54, uint8_t(percent));
staged.memory.set8(entry + 0x55, uint8_t(demand));
uint32_t fee = 0, salary = 0;
modern::market_value(staged, owner_slot, 0, uint8_t(percent), fee, salary, 1, 0, offer_rand);
staged.memory.set32(entry + 0x2c, fee);
staged.memory.set32(entry + 0x30, salary);
const int source_slot = int(transfer_list_slot()) + 40 + offer;
staged.squad_slots.at(size_t(source_slot)) = uint16_t(player);
staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4,
uint32_t(player) * 0x400 + uint32_t(borrower_manager));
// A modal may replace staged (and its hook) while paused.
// Own the active callable until the synchronous invocation returns.
const auto present_return_offer = staged.loan_return_offer_screen;
const int submitted = present_return_offer(staged, *offer_game, offer_rand,
borrower_manager, source_slot, 40 + offer, HumanBuyerSaleHooks{});
if (submitted < 0) {
report.fail("month change: OpenTransferEditor return-offer editor stopped");
return;
}
// The original month caller performs this cleanup only
// after OpenTransferEditor has returned from the actual editor.
staged.squad_slots.at(size_t(int(transfer_list_slot()) + 40 + offer)) = 0x0fff;
staged.memory.set32(::bmh::layout::OfferSlots + uint32_t(offer) * 4, 0xffffffffu);
}
rand = offer_rand;
if (game && offer_game) *game = *offer_game;
}
}
std::string return_notice = notice;
if (borrower_manager >= 0) {
const SquadRange returned_borrower_range = squad_range(club);
for (size_t i = 0; i < returned_borrower_range.count; ++i) {
if ((staged.squad_slots.at(returned_borrower_range.first + i) & 0x0fff) == player) {
return_notice += message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer7) + staged.club_name(club) +
message_text(staged, ::bmh::layout::Month_ReturnLoans_TextPointer8);
break;
}
}
}
uint32_t managers = 0x80000000u;
if (borrower_manager >= 0) managers = 1u << borrower_manager;
if (owner_manager >= 0) managers |= 1u << owner_manager;
post_composed(staged, int64_t(managers), return_notice);
auto_lineup(staged, owner, owner_manager >= 0 ? 0xe4 : 100);
auto_lineup(staged, club, borrower_manager >= 0 ? 0xe4 : 100);
} catch (const std::exception&) {
report.fail("month change: human-owner loan cannot be restored safely");
return;
}
g = std::move(staged);
continue;
}
const uint8_t months = uint8_t(mem.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k)) - 1);
mem.set8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(k), months);
if (months != 0) continue;
mem.set32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4, 0);
const SquadRange range = squad_range(owner);
const int slot = free_slot(g, int(range.first), int(range.count));
if (slot == -1) {
report.fail("month change: no room for a returning player (internal error 0x2e)");
return;
}
g.squad_slots[size_t(slot)] = uint16_t(player);
if (!modern::remove_from_seller(g, club, player, report)) return;
modern::lineup_after_transfer(g, owner);
modern::lineup_after_transfer(g, club);
}
}
// OriginalFinancePreview(1): the month's expenses of a human manager: facility maintenance
// (BMHExeXa), record +0x854/+0x858, the wages of the squad (MonthlyPay with flags
// 14), all six monthly environment budgets and the debt
// service (+0x179 x 1000); each booked in the statistics.
int32_t monthly_expenses(ModernState& g, int m) {
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(m) * kRecord;
int32_t sum = 0;
for (int i = 0; i < 0xe; i++) sum += kFacilityValue[i];
for (int i = 0xe; i < 0x16; i++) sum += (r.at(rec + 0x2e + size_t(i)) & 7) * kFacilityValue[i];
add32(r, rec + 0x87c, sum);
for (int k = 1; k < 3; k++) {
const int32_t v = int32_t(rd32(r, rec + 0x850 + size_t(k) * 4));
add32(r, rec + 0x890 + size_t(k) * 4, v);
sum += v;
}
// MonthlyPay(manager, 14): salaries (+0x50) and bonus bases (+0x4e) of the board
int32_t wages = 0;
uint32_t bonus = 0;
for (size_t s = 0; s < 24; s++) {
const size_t slot = size_t(m) * kBoard + s * kBoardSlot;
if (g.tactics.at(slot + 0x3d) == 0xFF) continue;
bonus = uint32_t(g.tactics.at(slot + 0x4e) | (g.tactics.at(slot + 0x4f) & 0x7F) << 8);
const int32_t salary = int32_t(rd32(g.tactics, slot + 0x50));
add32(r, rec + 0x338, salary);
add32(r, rec + 0x33c, int32_t(bonus));
wages += salary + int32_t(bonus);
}
sum += wages;
for (int k = 0; k < 6; k++) {
const int32_t v = modern::environment_monthly_cost(g, m, k);
if (k >= 3 && k <= 5) add32(r, rec + 0x878 + size_t(k) * 4, v);
else add32(r, rec + 0x880, v);
sum += v;
}
const int debt = r.at(rec + 0x179);
if (debt != 0) {
add32(r, rec + 0x8a0, debt * 1000);
sum += debt * 1000;
}
return sum < 0 ? 0 : sum;
}
// FinanceTotalsFromGame3(1): the month's income: facilities (FacilityIncome) and the 16 advertising
// contracts (record +0xa34), booked in the statistics.
int32_t monthly_income(ModernState& g, int m) {
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(m) * kRecord;
int32_t sum = 0;
for (int k = 0; k < 6; k++) {
const uint8_t v = r.at(rec + size_t(k));
if (v == 0) continue;
const int level = k == 0 ? ((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32
sum += level * kFacilityIncome[k];
}
add32(r, rec + 0x86c, sum);
for (int k = 0; k < 16; k++) {
const int32_t v = int32_t(rd32(r, rec + 0xa34 + size_t(k) * 0xc));
add32(r, rec + (k < 14 ? 0x860 : k == 14 ? 0x85c : 0x864), v);
sum += v;
}
return sum;
}
// The monthly bookkeeping of the players on a human manager's tactics board.
void board_month(ModernState& g, int m, WatcomRandom& rand, MinuteReport& report, GameRandom* game) {
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(m) * kRecord;
const SquadRange range = squad_range(g.manager_teams.at(size_t(m)));
auto board = [&](int s) { return size_t(m) * kBoard + size_t(s) * kBoardSlot; };
// the value history has 12 months; when it is full it moves on by one
int month = r.at(rec + 0x286); // local_24
if (month < 0xc) {
r.at(rec + 0x286) = uint8_t(month + 1);
} else {
for (int s = 0; s < 24; s++) {
if (g.squad_slots.at(range.first + size_t(s)) == 0xFFF) continue;
for (int k = 0; k < 3; k++) {
const size_t at = board(s) + 0x19 + size_t(k) * 0xc;
std::copy(g.tactics.begin() + long(at + 1), g.tactics.begin() + long(at + 0xc), g.tactics.begin() + long(at));
}
}
month = 0xb;
}
for (int s = 0; s < 24; s++) {
// (a player who leaves closes the gap: the same row is looked at again, or after the
// contracts screen all rows from the first one - those done are marked 0x80)
next_player:
const size_t b = board(s);
const int player = g.squad_slots.at(range.first + size_t(s)) & 0xFFF;
if (player == 0xFFF || (g.tactics.at(b + 0xb) & 0x80)) continue;
g.tactics.at(b + 0xb) |= 0x80;
if (rand.range(0, 0xb) == 0) {
const uint32_t limit = uint32_t(rand.range(0x11, 0x17));
if (limit < (g.players.at(size_t(player)).w364 >> 21 & 0x1F) && !(g.tactics.at(b + 0xb) & 0x20)) {
// he wants to end his career at the end of his contract
g.tactics.at(b + 0xb) |= 0x20;
post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer));
}
}
g.tactics.at(b + 0x11)++;
if (rand.range(0, 6) == 0) {
// the mood (+0x0d) drifts back towards 100
const int d = std::abs(100 - g.tactics.at(b + 0xd));
if (int16_t(d) != 0) {
int16_t step = int16_t(d) < 0xb ? 1 : 10;
if (g.tactics.at(b + 0xd) > 100) step = int16_t(-step);
g.tactics.at(b + 0xd) = uint8_t(std::clamp(step + g.tactics.at(b + 0xd), 0, 0xff));
}
}
if (g.tactics.at(b + 0x43) != 0) {
g.tactics.at(b + 0x43)--;
if ((g.tactics.at(b + 0x43) & 0x3f) == 0) g.tactics.at(b + 0x43) = 0;
}
if (g.tactics.at(b + 0xc) != 0xFF) g.tactics.at(b + 0xc)--; // contract months (BalancePlan_BalanceFromGame_RuntimeField is 0)
if (g.tactics.at(b + 0xc) <= 1) {
if (g.tactics.at(b + 0xc) != 0) {
// "'s Vertrag läuft in einem Monat ab. ..." (string at ContractExpiryWarningText)
post_composed(g, m, g.player_name(player) +
kContractEndsSoonText);
} else if (!(g.tactics.at(b + 0xb) & 0x20)) {
// the contract has ended: "... Vertrag ist ausgelaufen" (Month_BoardMonth_TextPointer4) and the
// contracts screen; without a renewal the message is posted and he goes
const std::string text = g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer4);
const int renewed = g.contract_screen ? g.contract_screen(g, m, s) : -2;
if (renewed == -2) {
report.fail("month change: a contract ends (the contracts screen InstallDefaultHooks)");
return;
}
if (renewed < 0) return;
if (renewed == 0) {
post_composed(g, m, text);
if (!game) {
report.fail("month change: a player goes (MonthChange) without the game generator");
return;
}
if (!modern::release_player(g, int(range.first) + s, *game, rand, report)) return;
s = 0;
goto next_player;
}
} else {
// he ends his career (flag 0x20, see above): Month_BoardMonth_TextPointer2, then his club gets
// a compensation, Month_BoardMonth_TextPointer3 + the amount (AddToSquad with W(15, 30)
// percent, 1 year, rounded down to 10000)
post_composed(g, m, g.player_name(player) + message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer2));
const int percent = rand.range(0xf, 0x1e);
uint32_t fee = 0, salary = 0;
modern::market_value(g, int(range.first) + s, 0, percent, fee, salary, 1, 0, rand);
fee = fee / 10000 * 10000;
post_composed(g, m, message_text(g, ::bmh::layout::Month_BoardMonth_TextPointer3) + format_amount(g, int32_t(fee)) + ".");
add32(r, rec + 0x314, int32_t(fee)); // MonthRuntimeField9: the balance, not booked
if (!game) {
report.fail("month change: a player retires (MonthChange) without the game generator");
return;
}
if (!modern::release_player(g, int(range.first) + s, *game, rand, report)) return;
goto next_player;
}
}
// the value history of the month
uint32_t fee = 0, salary = 0;
modern::market_value(g, int(range.first) + s, 0, 100, fee, salary, 0, 0, rand);
const size_t h = b + size_t(month);
g.tactics.at(h + 0x19) = uint8_t(std::min<uint32_t>(fee / 8000, 0xff));
const uint32_t w = g.players.at(size_t(player)).w35c;
g.tactics.at(h + 0x25) = uint8_t((((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) * 3 >> 1) * 0xff) / 300);
g.tactics.at(h + 0x31) = uint8_t(std::min<uint32_t>(((w & 0x7F) * 0x8c) / 0x5a, 0xff));
}
for (int s = 0; s < 24; s++) g.tactics.at(board(s) + 0xb) &= 0x7F;
}
// MonthChange2: share prices grow by 2.5 %, dividends, loans between the managers.
void shares_and_loans(ModernState& g) {
StaticMemory& mem = g.memory;
std::vector<uint8_t>& r = g.manager_records;
static const int kShareFactor[6] = {15, 18, 21, 24, 27, 30}; // MonthRuntimeField10
const int managers = int(g.manager_teams.size());
for (int k = 0; k < 6; k++) {
const uint32_t at = ::bmh::layout::FundBlock + uint32_t(k) * 0x1c;
uint32_t price = mem.u32(at);
price += ((price / 10000) * 0x19 / 10) * 10;
mem.set32(at, price);
// (a bug of the original: only the last manager's dividend is kept and it is booked
// for the manager after the last one)
int32_t dividend = 0;
for (int m = 0; m < managers; m++)
dividend = int32_t(mem.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c) *
((price * uint32_t(kShareFactor[k])) / 10000));
modern::book_money(g, managers, -dividend, true);
add32(r, size_t(managers) * kRecord + 0x870, dividend);
}
for (int m = 0; m < managers; m++)
for (int l = 0; l <= managers; l++) {
const uint32_t e = ::bmh::layout::Loans + uint32_t(l) * 0x18 + uint32_t(m) * 0x78;
const int32_t rate = int32_t(mem.u32(e + 8));
if (rate == 0) continue;
modern::book_money(g, m, rate, true);
add32(r, size_t(m) * kRecord + 0x89c, rate);
if (l != 0) {
add32(r, size_t(l - 1) * kRecord + 0x870, rate);
modern::book_money(g, l - 1, -rate, true);
}
mem.set32(e + 0x14, mem.u32(e + 0x14) + uint32_t(rate));
mem.set32(e + 0x10, mem.u32(e + 0x10) + 1);
if (int32_t(mem.u32(e + 0xc)) <= int32_t(mem.u32(e + 0x10)))
for (uint32_t i = 0; i < 0x18; i++) mem.set8(e + i, 0);
}
}
} // namespace
bool list_transfer_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report) {
return list_player(g, slot, rand, report);
}
void new_transfer_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report) { new_list_entries(g, rand, report); }
void market_value(const ModernState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years,
int extra, WatcomRandom& rand) {
if (years > 4) years = 4;
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
const Player& p = g.players.at(size_t(player));
int age = int((p.w364 >> 21) & 0x1F) + 1; // local_24
if (age > 0x14) age = 0x14;
const int position = int(p.w364 & 3);
uint16_t value[2] = {uint16_t((p.w35c >> 7) & 0x7F), uint16_t((p.w35c >> 14) & 0x7F)}; // technique, condition
uint8_t growth = 100; // local_14
if (age > 10) growth = uint8_t(age * -10 - 0x38);
for (int k = 0; k < 2; k++)
for (int s = 0; s < years - 1; s++)
value[k] = uint16_t((uint32_t(growth) * kDevelopment[int16_t(value[k]) / 10]) / 100 + value[k]);
const int ad = std::abs(0xb - age) & 0xFF;
int points = ((int16_t(value[0]) + int16_t(value[1])) * 5) / 2 + 0x96 - ad * 2; // local_2c
points = std::clamp(points, 0xc, 0x26c);
if (points > 500) points += points < 600 ? kDevelopment[10 + (points - 500) / 10] : 100;
points = (((points >> 2) + 1) * points * ((points >> 3) + 100)) / 10;
int16_t factor = int16_t(((p.w364 >> 26) & 0x3F) >> 2); // experience
if (position == 0) {
factor = int16_t(factor + 0x6e);
} else {
const int16_t skill = int16_t((int((p.w364 >> 10) & 0x3F) * 3 + int((p.w368 >> 7) & 0x3F)) >> 1);
const int t = (position * skill) / 3;
factor = int16_t(factor + 100 + (int16_t(t) >> 1));
}
fee = uint32_t((percent * ((factor * points) / 100)) / 100);
if (fee < 50000) fee = uint32_t(rand.range(50000, 80000));
salary = fee / 0x28;
// (local_24 holds 11 - age by now, the variable of the age difference above: younger
// players ask for more per extra year, older ones for less)
salary = ((uint32_t(extra * (0xb - age) + 100) * salary) / 10000) * 100;
if (loan == 1) fee >>= 2;
// BMH_MARKET_TRACE=1: the factors of one valuation (diagnosis of #40; no state, no draws)
if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1')
std::fprintf(stderr, "[market_value player %d (%s) pos %d age_raw %d TE %d KO %d -> points %d factor %d percent %d years %d extra %d: fee %u salary %u]\n",
player, g.player_name(player).c_str(), position, age, int((p.w35c >> 7) & 0x7F), int((p.w35c >> 14) & 0x7F),
points, int(factor), percent, years, extra, fee, salary);
}
std::array<uint32_t, 4> contract_demands(ModernState& g, int manager, int row, bool from_desk, WatcomRandom& rand) {
const SquadRange range = squad_range(g.manager_teams.at(size_t(manager)));
const int slot = int(range.first) + row;
const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot;
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
const int age = int((g.players.at(size_t(player)).w364 >> 21) & 0x1F) + 1; // local_24
// Difficulty (Range3 always returns 1, so the level is used)
const int percent = g.level + 100;
std::array<uint32_t, 4> demand{};
for (int k = 0; k < 4; k++) {
// per year beyond the current contract the salary changes by 11 - age percent
const int extra = int8_t(uint8_t(k - (g.tactics.at(b + 0xc) + 6) / 0xc + 1));
uint32_t fee = 0, salary = 0;
modern::market_value(g, slot, 0, percent, fee, salary, k + 1, extra, rand);
salary = (g.tactics.at(b + 0xd) * salary) / 100; // his mood
const bool refuses = age + k >= 0x24 || (g.tactics.at(b + 0xb) & 0x60);
if (const char* trace = std::getenv("BMH_MARKET_TRACE"); trace && trace[0] == '1')
std::fprintf(stderr, "[contract_demands player %d years %d: mood +0x0d %d, flags +0x0b %02x, refuses %d -> %u]\n",
player, k + 1, int(g.tactics.at(b + 0xd)), int(g.tactics.at(b + 0xb)), int(refuses), salary);
demand[size_t(k)] = refuses && from_desk ? 0xFFFFFFFFu : salary;
}
return demand;
}
bool contract_offer(ModernState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request,
bool screen_row, WatcomRandom& rand, const std::array<uint8_t, 7>* proposed_bonuses) {
const int team = g.manager_teams.at(size_t(manager));
const SquadRange range = squad_range(team);
const int slot = int(range.first) + row;
const size_t b = size_t(manager) * kBoard + size_t(row) * kBoardSlot;
const int player = g.squad_slots.at(size_t(slot)) & 0xFFF;
const size_t bonus_at = b + 0x12;
std::array<uint8_t, 7> current_bonuses{};
for (size_t i = 0; i < current_bonuses.size(); ++i) {
current_bonuses[i] = g.tactics.at(bonus_at + i);
if (proposed_bonuses && (*proposed_bonuses)[i] > (i < 3 ? 20 : 200)) return false;
}
// the longer he is at the club (+0x11, months), the less he insists
int loyalty = g.tactics.at(b + 0x11) / rand.range(8, 0xc); // local_3c
if (int16_t(loyalty) > 6) loyalty = 6;
// the offer counts with 80 % of the bonus he can expect (ContractOffer with the fitness
// correction on a copy of his board row whose salary is the offer: its +0x50 is the
// offer variable local_f0 that follows the copy on the stack)
std::array<uint8_t, 24> buf;
const int predicted = modern::table_prediction(g, team, 4, buf);
const int rank = predicted == 0 ? 0xB : predicted + 1;
uint8_t saved[4];
std::copy(g.tactics.begin() + long(b + 0x50), g.tactics.begin() + long(b + 0x54), saved);
for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i));
if (proposed_bonuses)
std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at));
const uint32_t bonus = modern::expected_bonus(g, manager, rank, row, player, true);
std::copy(saved, saved + 4, g.tactics.begin() + long(b + 0x50));
if (proposed_bonuses)
std::copy(current_bonuses.begin(), current_bonuses.end(), g.tactics.begin() + long(bonus_at));
const uint32_t worth = offer + (bonus * 0x50) / 100; // uVar12
if (std::getenv("BMH_TRACE"))
std::printf(" [offer %u: loyalty %d, rank %d, bonus %u, worth %u, demand %u]\n", offer, loyalty, rank, bonus, worth,
demand);
// what he wants: W(80, 100) - 2 x loyalty percent of his demand (a request of his own:
// the whole demand)
const uint32_t wanted = (request ? 100u : uint32_t(rand.range(0x50, 100) - 2 * int16_t(loyalty))) * demand;
if (std::getenv("BMH_TRACE")) std::printf(" [wanted %u / 100]\n", wanted);
if ((offer * 100u) / demand < 0x3d || worth < wanted / 100) {
// "Der Spieler lehnt ab" (CareerSession_Reject_TextPointer6, a message box): he is offended (+0x4f bit 7)
// and in a worse mood
g.tactics.at(b + 0x4f) |= 0x80;
if (g.tactics.at(b + 0xd) < 0xfb) g.tactics.at(b + 0xd) = uint8_t(g.tactics.at(b + 0xd) + 5);
if (screen_row) g.tactics.at(b + 0xb) |= 0x40; // he will not talk again
return false;
}
// accepted (CareerSession_Reject_TextPointer5): the new salary and term; his mood is what the offer is worth
// against his market salary for that term
for (int i = 0; i < 4; i++) g.tactics.at(b + 0x50 + size_t(i)) = uint8_t(offer >> (8 * i));
g.tactics.at(b + 0xc) = uint8_t((column + 1) * 0xc);
uint32_t fee = 0, salary = 0;
modern::market_value(g, slot, 0, 100, fee, salary, column, 0, rand);
g.tactics.at(b + 0xd) = uint8_t(std::clamp<uint32_t>((worth * 100) / salary, 100, 0xff));
if (proposed_bonuses)
std::copy(proposed_bonuses->begin(), proposed_bonuses->end(), g.tactics.begin() + long(bonus_at));
return true;
}
bool contract_bonuses(ModernState& g, int manager, int row, const std::array<uint8_t, 7>& rates) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return false;
const int team = g.manager_teams[size_t(manager)];
if (team == no_team()) return false;
const SquadRange range = squad_range(team);
if (row < -1 || (row >= 0 && size_t(row) >= range.count) || range.first + range.count > g.squad_slots.size())
return false;
for (size_t i = 0; i < rates.size(); ++i)
if (rates[i] > (i < 3 ? 20 : 200)) return false;
const size_t board = size_t(manager) * 0x840;
if (board + size_t(range.count) * 0x58 > g.tactics.size()) return false;
bool changed = false;
const size_t first_row = row < 0 ? 0 : size_t(row);
const size_t end_row = row < 0 ? range.count : size_t(row) + 1;
// The original checks the whole selected scope before committing any of it.
for (size_t r = first_row; r < end_row; ++r) {
const int player = g.squad_slots.at(range.first + r) & 0x0fff;
if (player == 0x0fff) continue;
if (size_t(player) >= g.players.size()) return false;
const size_t b = board + r * 0x58;
for (size_t i = 0; i < rates.size(); ++i) {
const uint8_t old = g.tactics.at(b + 0x12 + i);
changed |= rates[i] > old;
}
}
for (size_t i = 0; i < rates.size(); ++i) {
bool found = false;
uint8_t minimum = 0xff;
for (size_t r = first_row; r < end_row; ++r) {
if ((g.squad_slots.at(range.first + r) & 0x0fff) == 0x0fff) continue;
found = true;
minimum = std::min(minimum, g.tactics.at(board + r * 0x58 + 0x12 + i));
}
if (found && rates[i] < minimum) return false;
}
if (!changed) return false;
for (size_t r = first_row; r < end_row; ++r) {
const int player = g.squad_slots.at(range.first + r) & 0x0fff;
if (player == 0x0fff) continue;
const size_t b = board + r * 0x58;
for (size_t i = 0; i < rates.size(); ++i)
if (rates[i] > g.tactics.at(b + 0x12 + i)) g.tactics.at(b + 0x12 + i) = rates[i];
}
return true;
}
ContractInsuranceResult contract_insurance(ModernState& g, int manager, int row, int insurance_type,
uint8_t months) {
ContractInsuranceResult out;
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || insurance_type < 0 || insurance_type >= 4 ||
months < 1 || months > 60) return out;
const int team = g.manager_teams[size_t(manager)];
if (team == no_team()) return out;
const SquadRange range = squad_range(team);
if (row < 0 || size_t(row) >= range.count || range.first + size_t(row) >= g.squad_slots.size()) return out;
const int player = g.squad_slots.at(range.first + size_t(row)) & 0x0fff;
if (player == 0x0fff || size_t(player) >= g.players.size()) return out;
const size_t b = size_t(manager) * 0x840 + size_t(row) * 0x58;
if (b + 0x54 > g.tactics.size() || (g.tactics.at(b + 0x0b) & 0x60) != 0 ||
g.tactics.at(b + 0x43) != 0 || (g.players[size_t(player)].w35c >> 27) != 0) return out;
const uint32_t salary = uint32_t(g.tactics.at(b + 0x50)) |
(uint32_t(g.tactics.at(b + 0x51)) << 8) | (uint32_t(g.tactics.at(b + 0x52)) << 16) |
(uint32_t(g.tactics.at(b + 0x53)) << 24);
const uint32_t fee = (((uint32_t(insurance_type * 10 + 10) * salary) / 1000) * 10);
const uint16_t old_fee = uint16_t(g.tactics.at(b + 0x4e) | (uint16_t(g.tactics.at(b + 0x4f)) << 8));
g.tactics.at(b + 0x43) = uint8_t(months | uint8_t(insurance_type << 6));
// The original clears the old amount but preserves the high flag before adding the
// term's monthly premium into the 16-bit field.
const uint16_t base = uint16_t(old_fee & 0x8000);
const uint16_t stored = uint16_t(base + uint16_t(fee));
g.tactics.at(b + 0x4e) = uint8_t(stored);
g.tactics.at(b + 0x4f) = uint8_t(stored >> 8);
out.accepted = true;
out.monthly_fee = uint16_t(fee);
return out;
}
void search_profile_news(ModernState& g, int manager, uint32_t list, int player) {
const StaticMemory& mem = g.memory;
const size_t rec = size_t(manager) * kRecord;
auto b = [&](size_t off) { return int(g.manager_records.at(rec + off)); };
const int team = g.manager_teams.at(size_t(manager));
player &= 0xFFF;
if (team == no_team() || (mem.u16(list + 8) & 0x7FFF) == team || (b(0x1f6) & 0x40)) return;
const uint32_t w364 = g.players.at(size_t(player)).w364, w35c = g.players.at(size_t(player)).w35c;
// position wanted (or none selected) and age within the range
if (b(0x1f6 + (w364 & 3)) == 0 && b(0x1f9) + b(0x1f8) + b(0x1f7) + b(0x1f6) != 0) return;
const int age = int((w364 >> 21) & 0x1F);
if (age < b(0x1fa) || age > b(0x1fb)) return;
// strength by the selected attributes (condition, technique, form; none = all three)
int8_t selected = int8_t(b(0x200) + b(0x1fe) + b(0x1ff));
if (selected == 0) selected = 3;
int sum = 0, n = 0, form = 0;
if (b(0x1fe) != 0 || selected == 3) sum = int((w35c >> 14) & 0x7F), n = 1;
if (b(0x1ff) != 0 || selected == 3) sum = int16_t(sum) + int((w35c >> 7) & 0x7F), n++;
if (b(0x200) != 0 || selected == 3) form = int(w35c & 0x7F);
int16_t strength;
if (n == 0) {
strength = int16_t((form - 0x23) * 3 + 10);
} else {
strength = int16_t(uint32_t(sum) / uint32_t(n));
if (form != 0) strength = int16_t(uint32_t(strength * int16_t((int16_t(form) >> 3) + 0x5e)) / 100);
}
if (strength < b(0x1fc) || strength > b(0x1fd)) return;
// left / right foot and wing preferences (w35c bits 21-23 and 24-26)
const int lane = int((w35c >> 21) & 7), foot = int((w35c >> 24) & 7);
bool low_foot = b(0x201) || b(0x203), high_foot = b(0x202) || b(0x204);
if (low_foot && high_foot) low_foot = high_foot = false;
bool low_lane = b(0x201) || b(0x202), high_lane = b(0x203) || b(0x204);
if (low_lane && high_lane) low_lane = high_lane = false;
if ((low_lane && lane >= 3) || (high_lane && lane <= 4) || (low_foot && foot >= 3) || (high_foot && foot <= 4)) return;
// the price class (asking price 70..130 %) against the classes wanted
int8_t price_class = int8_t((mem.u8(list + 0x54) - 0x46) / 0x14);
price_class = std::clamp<int8_t>(price_class, 0, 2);
const int8_t classes = int8_t(b(0x207) + b(0x205) + b(0x206));
int highest = 2;
while (highest >= 0 && b(0x205 + size_t(highest)) == 0) highest--;
if (classes == 0 || price_class <= highest)
post_composed(g, manager, message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer) + g.player_name(player) + message_text(g, ::bmh::layout::Month_SearchProfileNews_TextPointer2));
}
void month_change(ModernState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game) {
StaticMemory& mem = g.memory;
std::vector<uint8_t>& r = g.manager_records;
const int managers = int(g.manager_teams.size());
// 1. advertising contracts
turn_step = "month_change: advertising";
if (mem.u8(::bmh::layout::GameMode) != 1 && mem.u8(::bmh::layout::CareerDuration) != 1)
for (int m = 0; m < managers; m++)
for (int k = 0; k < 0x12; k++) {
const size_t c = size_t(m) * kRecord + 0xa34 + size_t(k) * 0xc;
if (r.at(c + 5) == 0 && (r.at(c + 6) & 0x80)) {
wr32(r, c, 0);
r.at(c + 6) = 0;
}
if (r.at(c + 5) != 0 && --r.at(c + 5) == 0) {
if ((r.at(c + 6) & 0x7F) == 0) wr32(r, c, 0);
else turn_step = "month_change: advertising text", post_text(g, m, text_id(::bmh::layout::Month_MonthChange_TextPointer)); // the contract can be renewed
}
}
// 2. new players on the transfer list
turn_step = "month_change: new list entries";
new_list_entries(g, rand, report);
if (report.unsupported) return;
// 3. loans
turn_step = "month_change: loans";
return_loans(g, rand, game, report);
if (report.unsupported) return;
// 4. the human managers
turn_step = "month_change: managers";
for (int m = 0; m < managers && !report.unsupported; m++) {
const size_t rec = size_t(m) * kRecord;
for (int k = 0; k < 3; k++)
modern::rate_manager(g, m, uint8_t(int8_t(int32_t(mem.u32(::bmh::layout::Month_MonthChange_RuntimeField + uint32_t(k) * 4 + uint32_t(m) * 0x24)) / 0x96)),
k + 1);
const int32_t expenses = monthly_expenses(g, m);
const int32_t income = monthly_income(g, m);
modern::book_money(g, m, expenses - income, true);
for (int k = 0; k < 2; k++)
modern::rate_manager(g, m, uint8_t(int8_t(((rd32(r, rec + 0x854 + size_t(k) * 4) / 5000) * 200) / 7)), k + 4);
board_month(g, m, rand, report, game);
}
if (report.unsupported) return;
// 5. shares and loans
turn_step = "month_change: shares";
shares_and_loans(g);
}
} // namespace bmh::modern
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/month.hpp"
// The month change (DayStepRest2), run by the day step (DayStepRest) of the first day of
// a month in the full game (CompetitionSelection bit 0), after the training / weekly processing:
//
// 1. advertising contracts of the human managers count down (record +0xa34, 18 x 0xC)
// 2. new players on the transfer list (CareerFirstSteps): free agents of the pool and players
// the computer clubs want to sell
// 3. loaned players whose time is up return to their clubs (table Career_RemoveJoinLoans_RuntimeField)
// 4. per human manager: the monthly ratings (ManagerMatchRecord2), expenses minus income, and the
// monthly bookkeeping of every squad player on the tactics board (contract months,
// mood, value history, retirement wishes)
// 5. share prices grow, dividends and loans between managers are booked (MonthChange2)
//
// Monthly bookkeeping uses Watcom draws; player moves also require the game RNG.
// Human decisions use caller-supplied contract/loan presenters. Missing context
// and invalid state report through MinuteReport, rather than guessing a decision.
#include <array>
#include <cstdint>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// `game` is needed when a player leaves at the end of his contract (MonthChange).
void month_change(ModernState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr);
// CareerFirstSteps: new players on the transfer list (part of the month change; also at the
// start of a season).
void new_transfer_list_entries(ModernState& g, WatcomRandom& rand, MinuteReport& report);
// AddToSquad(slot, loan, percent, &fee, &salary, years, extra): market value (fee) and
// salary of the player in an absolute squad slot, from strength, age, position and
// experience; `percent` scales the fee, `years` - 1 steps of expected development raise
// it, `extra` * (11 - age) percent change the salary. A fee below 50000 is replaced by W(50000,
// 80000); a loan (1) costs a quarter.
void market_value(const ModernState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years,
int extra, WatcomRandom& rand);
// ContractBonuses, the salary page of the contract talks (contracts screen InstallDefaultHooks): the
// four demands for 1-4 years when the talks open, AddToSquad with the level + 100 percent
// and the salary rise for the years beyond the current contract, times the player's mood
// (+0xd) / 100. Opened from the desk (`from_desk`, param_5 0x80) a player of 36 or more
// at the end of the term, or one flagged 0x20 / 0x40, wants no contract (no-contract sentinel).
std::array<uint32_t, 4> contract_demands(ModernState& g, int manager, int row, bool from_desk, WatcomRandom& rand);
// ContractBonuses "OK" with an offer for `column` + 1 years against that column's demand: W(8, 12)
// (loyalty from the months at the club, +0x11) and - unless the player asked himself
// (`request`, param_5 0x40) - W(80, 100). The offer plus 80 % of the expected bonus
// (ContractOffer) must reach that percentage of the demand, and the offer itself 61 %.
// Accepted: salary, term and mood (+0x50, +0xc, +0xd) change, AddToSquad for the term.
// Rejected: the player is offended (+0x4f bit 7, mood + 5); for the row whose contract
// ended (`screen_row`) he will not talk again (+0xb bit 6). Returns whether he accepted.
bool contract_offer(ModernState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request,
bool screen_row, WatcomRandom& rand,
const std::array<uint8_t, 7>* proposed_bonuses = nullptr);
// ContractBonuses "Prämien" page. `row == -1` edits the squad's shared proposal; each
// stored row is raised to the requested value. A bonus-only submission is accepted only
// when it does not lower any player's current rate, and must change at least one rate.
bool contract_bonuses(ModernState& g, int manager, int row, const std::array<uint8_t, 7>& rates);
// ContractBonuses insurance button: one-time per player, duration 1..60 months, and insurance
// category bound to the selected 1..4 year term. This action consumes no RNG.
ContractInsuranceResult contract_insurance(ModernState& g, int manager, int row, int insurance_type,
uint8_t months);
// SearchProfileNews(manager, list entry, player, 1): tells a human manager about a new player on
// the transfer list that matches his search profile (record +0x1f6 .. +0x207).
void search_profile_news(ModernState& g, int manager, uint32_t list, int player);
// Put an existing squad slot on the shared transfer list (human desk action).
bool list_transfer_player(ModernState& g, int slot, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh::modern
+234
View File
@@ -0,0 +1,234 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/national.hpp"
#include <algorithm>
#include <cstring>
#include "game/lineup.hpp"
#include "game/match_engine.hpp"
#include "modern/game/month.hpp"
#include "modern/game/weekly.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kManagerRecord = 0xb0c;
constexpr size_t kBoard = 0x840; // one manager's tactics board (24 x 0x58)
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kDesktops = ::bmh::layout::Desktops; // desktop layouts, 0x360 per manager slot
constexpr size_t kDesktop = 0x360;
constexpr uint8_t kNominated[4] = {3, 5, 7, 5}; // NationalRuntimeField: keepers, defence, midfield, attack
// the manager's team (record +0x290) as the port caches it
void refresh_manager_teams(ModernState& g) {
for (size_t m = 0; m < g.manager_teams.size(); m++) {
const size_t at = m * kManagerRecord + 0x290;
g.manager_teams[m] = int16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
}
// a byte of the original's static data, created on first use (not every one is saved)
uint8_t& static_byte(ModernState& g, uint32_t address) {
if (!g.memory.has(address)) g.memory.add_block(address, 1);
return g.memory.at(address);
}
} // namespace
void swap_manager_slots(ModernState& g, int a, int b) {
if (a == b) return;
std::swap_ranges(g.manager_records.begin() + long(size_t(a) * kManagerRecord),
g.manager_records.begin() + long(size_t(a + 1) * kManagerRecord),
g.manager_records.begin() + long(size_t(b) * kManagerRecord));
std::swap_ranges(g.tactics.begin() + long(size_t(a) * kBoard), g.tactics.begin() + long(size_t(a + 1) * kBoard),
g.tactics.begin() + long(size_t(b) * kBoard));
if (g.memory.has(kDesktops))
for (size_t i = 0; i < kDesktop; i++) {
const uint32_t pa = kDesktops + uint32_t(size_t(a) * kDesktop + i);
const uint32_t pb = kDesktops + uint32_t(size_t(b) * kDesktop + i);
const uint8_t t = g.memory.u8(pa);
g.memory.set8(pa, g.memory.u8(pb));
g.memory.set8(pb, t);
}
refresh_manager_teams(g);
}
int add_to_squad(ModernState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand) {
// FirstFreeSlotSquad(start, 0x18): the first free slot of the squad
int slot = -1;
for (int s = squad_start; s < squad_start + 24; s++)
if (g.squad_slots.at(size_t(s)) == kEmptySlot) {
slot = s;
break;
}
if (slot < 0) return -1; // (the original shows the message PendingOffer_FormatError_ExecutableField)
g.squad_slots.at(size_t(slot)) = g.squad_slots.at(size_t(from_slot));
modern::new_board_entry(g, manager, slot - squad_start, slot, rand);
return slot;
}
void new_board_entry(ModernState& g, int manager, int index, int slot, WatcomRandom& rand) {
uint8_t* e = &g.tactics.at(size_t(manager) * kBoard + size_t(index) * kBoardSlot);
std::memset(e + 7, 0, 3);
std::memset(e + 0x19, 0, 0x24);
e[10] = 2;
for (int k = 0; k < 4; k++) e[2 + k] = index < 2 ? 1 : uint8_t(rand.range(2, 0x27));
e[0x3f] = 0xff;
e[0x46] = 0xff, e[0x47] = 0x0f; // u16 0xfff
e[0x44] = 0xff, e[0x45] = 0x0f;
e[0] = 10;
e[1] = 4;
e[0xe] = 0x59;
e[0xf] = uint8_t(rand.range(0x28, 0x3c));
e[0x11] = 0;
e[0x43] = 0;
e[0x4e] = 0, e[0x4f] = 0;
e[0x3d] = index < 11 ? 0 : index <= 0x10 ? 1 : 2;
e[0xc] = 0x18;
// AddToSquad(slot, 0, W(95, 105), &fee, &salary (+0x50), 2 years, no extra)
const int percent = rand.range(0x5f, 0x69);
uint32_t fee = 0, salary = 0;
modern::market_value(g, slot, 0, percent, fee, salary, 2, 0, rand);
for (int k = 0; k < 4; k++) e[0x50 + k] = uint8_t(salary >> (8 * k));
std::memset(e + 0x12, 0, 7);
}
bool national_team_day(ModernState& g, WatcomRandom& rand, MinuteReport& report) {
StaticMemory& mem = g.memory;
const SquadRange national = squad_range(no_team());
// NationalSquadEmptied: the national squad is emptied
for (size_t s = national.first; s < national.first + national.count; s++) g.squad_slots.at(s) = kEmptySlot;
// SwapManagerSlots2 (called whether or not a take-over is already in effect): a manager flagged
// as Bundestrainer takes the national team over in slot 0. ActiveManager is what the day
// step's manager loop (DayStepRest) leaves: the number of managers.
(void)mem;
(void)report;
modern::national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(g.date - g.season_start));
const uint8_t coach = static_byte(g, ::bmh::layout::CoachActive); // CoachActive
if (coach == 0) modern::swap_manager_slots(g, 4, 0); // slot 0 becomes the spare slot 4
// the strongest available German players per position (NationalRuntimeField of each), kept in
// ascending order: a stronger one pushes the weakest out
int16_t best[4][7] = {}, slots[4][7] = {};
for (size_t s = 0; s < transfer_list_slot(); s++) {
const int id = g.squad_slots.at(s) & 0xfff;
if (id == 0xfff) continue;
const Player& p = g.players.at(size_t(id));
const bool fit = (p.w35c >> 27) == 0 || ((p.w364 >> 16) & 0x1f) == 0;
if (!fit || modern::nationality(g, id) != 0) continue;
const int pos = int(p.w364 & 3);
int16_t strength = int16_t(p.strength(false)); // Strength(w35c, 0)
if (pos > 1) strength = int16_t(strength + ((p.w364 >> 2) & 0x3f) + (((p.w368 >> 18) & 0x3f) >> 1));
if (s > 0x86f) strength = int16_t((strength * 0xb) / 10); // (the clubs from slot 0x870 on)
int i = 0;
// NationalTeamDay caps the insertion index at the positional quota. Guard
// before indexing: the full seven-player row has no C++ eighth element.
while (i < kNominated[pos] && strength > best[pos][i]) i++;
if (i == 0) continue;
const int j = i - 1;
// Int16T: entries 1..j move down one place, the new one takes place j
for (int k = 0; k < j; k++) best[pos][k] = best[pos][k + 1], slots[pos][k] = slots[pos][k + 1];
best[pos][j] = strength;
slots[pos][j] = int16_t(s);
}
// PendingOfferAnswer for each, weakest first, into the board of slot 0
for (int pos = 0; pos < 4; pos++)
for (int k = 0; k < kNominated[pos]; k++) modern::add_to_squad(g, 0, slots[pos][k], int(national.first), rand);
// Int2(0x165, 0xe4) with manager 0's option byte (ManagerAutomation) at 1
const uint8_t option = g.manager_options.at(0);
g.manager_options.at(0) = 1;
try {
auto_lineup(g, no_team(), 0xe4);
} catch (const std::exception& ex) {
report.fail(std::string("national team line-up: ") + ex.what());
}
if (coach == 0) modern::swap_manager_slots(g, 4, 0);
g.manager_options.at(0) = option;
return coach != 0; // (with a Bundestrainer his desk follows: AdvanceTurn's local_28 = 4)
}
// ---------------------------------------------------------------------------------------
// The Bundestrainer (national coach). A manager flagged in his record (+0x21c), every
// manager in the world game without leagues (CompetitionSelection == 2) and the only manager of a
// one-manager game coaches the national team on international days: SwapManagerSlots2 moves his
// slot 0 to the spare slot 4 and puts the national team's record (kept in slot 4 between the
// international periods) into slot 0; NationalCoachHandBack swaps them back. CoachActive tells
// whether the swap is in effect, OriginalManagerCount keeps the number of managers meanwhile.
namespace {
void set_manager_count(ModernState& g, int managers) {
static_byte(g, ::bmh::layout::ManagerCount) = uint8_t(managers); // ManagerCount
g.manager_teams.assign(size_t(managers), 0); // (the typed copy, one entry per manager)
}
} // namespace
void national_coach_take_over(ModernState& g, int active_manager, uint16_t source_season_day) {
StaticMemory& mem = g.memory;
int managers = int(g.manager_teams.size());
static_byte(g, ::bmh::layout::OriginalManagerCount) = uint8_t(managers); // OriginalManagerCount = ManagerCount
static_byte(g, ::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3) = uint8_t(active_manager); // ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager
// DaysIntoSeason == 1 (the first day after the saved season origin): the national team's
// mood byte loses its top bit before coach eligibility is checked.
const bool first_day = source_season_day == 1;
if (first_day) g.team_morale.at(no_team()) &= 0x7f;
const bool world_only = mem.u32(::bmh::layout::CompetitionSelection) == 2;
// (the loop bound is ManagerCount itself, which a take-over sets to 1)
for (int m = 0; m < managers; m++) {
uint8_t* rec = &g.manager_records.at(size_t(m) * kManagerRecord);
if (rec[0x21c] == 0 && !world_only && managers != 1) continue;
// the national team's record (slot 4) gets the coach's portrait (+0x221) and name
// (+0xa8, StrcpySoHallReplacesItsCurrentTournament = strcpy)
uint8_t* spare = &g.manager_records.at(4 * kManagerRecord);
spare[0x221] = rec[0x221];
for (size_t i = 0;; i++) {
spare[0xa8 + i] = rec[0xa8 + i];
if (rec[0xa8 + i] == 0) break;
}
managers = 1;
set_manager_count(g, 1);
modern::swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0)
uint8_t* coach = &g.manager_records.at(0);
coach[0x290] = uint8_t(no_team() & 0xff), coach[0x291] = uint8_t(no_team() >> 8); // CupDraw_FormatError_RuntimeField2 = 0x165
coach[0x218] = g.manager_records.at(4 * kManagerRecord + 0x218); // NationalRuntimeField2 = NationalRuntimeField3
g.manager_teams.at(0) = no_team();
auto_lineup(g, no_team(), 0xe4); // Int2(0x165, 0xe4)
static_byte(g, ::bmh::layout::CoachActive) = 1;
if (first_day) g.team_morale.at(no_team()) |= 0x80;
}
}
void national_coach_hand_back(ModernState& g) {
if (static_byte(g, ::bmh::layout::CoachActive) == 0) return;
const int managers = static_byte(g, ::bmh::layout::OriginalManagerCount);
set_manager_count(g, managers); // ManagerCount = OriginalManagerCount
modern::swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) (refreshes the typed teams)
static_byte(g, ::bmh::layout::CoachActive) = 0;
}
bool national_coach_active(const ModernState& g) { return !g.manager_teams.empty() && g.manager_teams[0] == no_team(); }
void national_coach_after_load(ModernState& g) {
// NationalCoachAfterLoad's end, loading as well as saving: the take-over is done again
if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0)
modern::national_coach_take_over(g, g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0,
uint16_t(g.date - g.season_start));
}
ModernState national_coach_save_form(const ModernState& g) {
// NationalCoachAfterLoad's start: the slots swapped back, CoachActive kept at 1
ModernState s = g;
if (s.memory.has(::bmh::layout::CoachActive) && s.memory.u8(::bmh::layout::CoachActive) != 0) {
modern::national_coach_hand_back(s);
s.memory.set8(::bmh::layout::CoachActive, 1);
}
return s;
}
} // namespace bmh::modern
+65
View File
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/national.hpp"
// The national team (BMH.exe V2.24 + supported rule profile patch), team id 0x165 (no_team()), squad slots
// 0xc00-0xc17 (LargeSquadClubCount).
//
// With the world game on (CompetitionSelection bit 1) the calendar holds national team days (entry
// 0x4006, DayCompetitions -> national-only flag). On such a day AdvanceTurn calls NationalTeamDay, which
// nominates the squad: the manager slots are swapped so that slot 0 is a spare one
// (SwapManagerSlots(4, 0); a Bundestrainer instead takes slot 0 over with the national team,
// SwapManagerSlots2), the 3 goalkeepers, 5 defenders, 7 midfielders and 5 forwards
// (NationalRuntimeField) of the highest strength among the available German players of all clubs
// join the national squad with a fresh tactics board entry (PendingOfferAnswer), the national team
// gets its line-up (Int2(0x165, 0xe4)) and the slots are swapped back. Without a
// Bundestrainer the day then prepares an empty matchday (no desk, no match).
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// SwapManagerSlots(a, b): manager slots a and b change places - the manager records (0xb0c
// bytes), the tactics boards (0x840) and the desktop layouts (block Desktops, 0x360).
void swap_manager_slots(ModernState& g, int a, int b);
// PendingOfferAnswer(manager, from_slot, -1, squad_start): the player of the absolute squad slot
// `from_slot` gets the first free slot of the squad starting at `squad_start` (24 slots;
// the slot value is copied with its flags) and a fresh entry on the tactics board of
// manager slot `manager`: neutral settings, familiarity W(40, 60), the four attribute
// bytes W(2, 39) each (1 for the first two places) and the salary of a 2-year contract
// at W(95, 105) percent (AddToSquad). Returns the new absolute slot, -1 if the squad is full.
int add_to_squad(ModernState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand);
// The board part of PendingOfferAnswer (also called with a given place `index`): the entry of
// the player in absolute squad slot `slot` on the tactics board of `manager`.
void new_board_entry(ModernState& g, int manager, int index, int slot, WatcomRandom& rand);
// NationalTeamDay: the national team day (see above). Returns whether a Bundestrainer manages
// the national team (CoachActive) - then his desk follows (AdvanceTurn: local_28 = 4).
bool national_team_day(ModernState& g, WatcomRandom& rand, MinuteReport& report);
// The Bundestrainer (national coach), see national.cpp. SwapManagerSlots2: notes the number of
// managers (OriginalManagerCount) and `active_manager` (ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager); a manager
// flagged in his record (+0x21c), every manager in the world game without leagues
// (CompetitionSelection == 2) and the only manager of a one-manager game takes the national team over:
// the national team's record (slot 4) gets his name and portrait, the number of managers
// becomes 1, slots 4 and 0 change places, slot 0 manages team 0x165 and copies +0x218 from
// slot 4, the national team gets its line-up (Int2(0x165, 0xe4)) and
// CoachActive = 1.
// `source_season_day` is the 16-bit value visible in DaysIntoSeason at this exact Source call
// site. It is not always `g.season_day()`: DailyInterest advances the counter before
// quiet-day rest but after rest on the completed-event path.
void national_coach_take_over(ModernState& g, int active_manager, uint16_t source_season_day);
// NationalCoachHandBack: with CoachActive set the slots change places again, the number of managers
// is restored from OriginalManagerCount and CoachActive cleared.
void national_coach_hand_back(ModernState& g);
// CupDraw_FormatError_RuntimeField2 == 0x165: slot 0 manages the national team.
bool national_coach_active(const ModernState& g);
// NationalCoachAfterLoad (saving and loading): the savegame holds the slots swapped back with
// CoachActive still 1; afterwards (and so after loading) SwapManagerSlots2 takes over again.
void national_coach_after_load(ModernState& g);
// The state as NationalCoachAfterLoad writes it (for the savegame writer and comparisons).
ModernState national_coach_save_form(const ModernState& g);
} // namespace bmh::modern
+396
View File
@@ -0,0 +1,396 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/other_games.hpp"
#include <algorithm>
#include <array>
#include <stdexcept>
#include <utility>
#include "formats/binary.hpp"
#include "modern/game/cup.hpp"
#include "game/schedule.hpp"
namespace bmh::modern {
namespace {
constexpr uint32_t kActiveSelectors = ::bmh::layout::ActiveSelectors;
constexpr uint32_t kSelectorCount = 8;
constexpr size_t kTextCompetitionNames = (::bmh::layout::CupDraw_FormatError_ExecutableField6 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextCompetitionButtonNames = (::bmh::layout::OtherGames_Layout_ExecutableField - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextRoundHeadings = (::bmh::layout::CupDraw_FormatError_ExecutableField4 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextGroupRound = (::bmh::layout::Calendar_Information_TextPointer2 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextGroupCaption = (::bmh::layout::CupDraw_FormatError_ExecutableField5 - ::bmh::layout::TextPointerTable) / 4;
[[noreturn]] void invalid(const char* why) { throw FormatError(std::string("other games: ") + why); }
std::string text(const TextDb& texts, size_t index) {
if (index >= texts.strings.size()) invalid("missing Source TEXTD entry");
return texts.strings[index];
}
bool in_descriptor_table(int entry) { return entry >= 0 && entry < kCupEntries; }
// Bounded port of FindCup's literal scan cursor. On a matching descriptor, its +0x17 link
// wins, else +0x16; a zero link falls back to entry0 in Source. The scan cursor itself advances
// only on a nonmatch and returns the just-followed pointer immediately when the cursor is0.
// Malformed/no-match paths fail closed instead of returning Source's invalid one-past-table ptr.
int resolve_linked_entry(const StaticMemory& memory, int competition, int ordinal) {
if (ordinal < 0 || ordinal >= kCupEntries) invalid("linked occurrence outside Source bounds");
int cursor = 0, current = 0, remaining = ordinal;
std::vector<uint8_t> seen(size_t(kCupEntries) * kCupEntries * kCupEntries, 0);
for (size_t step = 0; step < seen.size(); ++step) {
if (!in_descriptor_table(cursor) || !in_descriptor_table(current))
invalid("Source linked resolver left descriptor table");
const size_t key = (size_t(cursor) * kCupEntries + size_t(current)) * kCupEntries + size_t(remaining);
if (seen[key]) invalid("cycle in Source linked resolver");
seen[key] = 1;
const uint32_t address = modern::cup_entry_address(current);
if (!memory.has(address + 0x19)) invalid("truncated Source descriptor ID");
if (int16_t(memory.u16(address + 0x18)) == competition) {
if (remaining == 0) return current;
const int parallel = int8_t(memory.u8(address + 0x17));
const int next = int8_t(memory.u8(address + 0x16));
if (parallel != 0) current = parallel;
else if (next != 0) current = next;
else invalid("Source linked occurrence reaches its no-link fallback");
if (!in_descriptor_table(current)) invalid("invalid Source linked descriptor link");
--remaining;
if (cursor == 0) return current;
} else {
++cursor;
if (cursor >= kCupEntries) invalid("Source linked resolver cursor wrapped without a match");
current = cursor;
}
}
invalid("Source linked resolver exceeded bounded traversal");
}
std::vector<OtherGamesLinkedPage> source_linked_pages(const StaticMemory& memory, int selected) {
std::vector<OtherGamesLinkedPage> pages;
int first = selected;
std::array<bool, kCupEntries> seen{};
while (in_descriptor_table(first)) {
if (seen[size_t(first)]) invalid("cycle while locating first Source group selector");
seen[size_t(first)] = true;
const uint8_t group = memory.u8(modern::cup_entry_address(first) + 0x1e);
if ((group >> 4) == 0) break;
if (first == 0) invalid("Source group selector would walk before descriptor table");
--first; // InDescriptorTable moves one adjacent descriptor left until group index0.
}
while (true) {
if (!in_descriptor_table(first) || seen[size_t(first)]) {
// The first adjacent scan above marks visited entries; reset its cycle guard before
// following signed previous-stage links.
if (!in_descriptor_table(first)) invalid("invalid Source first group descriptor");
}
seen[size_t(first)] = true;
const int previous = int8_t(memory.u8(modern::cup_entry_address(first) + 0x15));
if (previous == -1) break;
if (!in_descriptor_table(previous) || seen[size_t(previous)]) invalid("invalid Source previous-stage link");
first = previous;
}
// InDescriptorTable suppresses the linked-page selector before enumerating groups when the first
// stage has no +0x16 continuation.
if (memory.u8(modern::cup_entry_address(first) + 0x16) == 0) return pages;
int stage = first;
std::array<bool, kCupEntries> stage_seen{};
while (in_descriptor_table(stage)) {
if (stage_seen[size_t(stage)]) invalid("cycle in Source linked-stage selector");
stage_seen[size_t(stage)] = true;
int group_entry = stage;
const uint8_t count = memory.u8(modern::cup_entry_address(stage) + 0x1e) & 0x0f;
for (int group = 0; group < count; ++group) {
if (!in_descriptor_table(group_entry)) invalid("parallel group left descriptor table");
const uint32_t address = modern::cup_entry_address(group_entry);
pages.push_back({int(pages.size()), group_entry, int16_t(memory.u16(address + 0x18)),
int(memory.u8(address + 0x1e) >> 4), int(count)});
const bool has_adjacent = memory.u8(address + 0x17) != 0;
if (group + 1 < count && !has_adjacent)
invalid("parallel group count lacks adjacent Source entry");
// Source checks +0x17 after every emitted sibling, including the final one; when
// present it advances to the adjacent descriptor before reading its +0x16 stage.
if (has_adjacent) ++group_entry;
}
const int next = int8_t(memory.u8(modern::cup_entry_address(group_entry) + 0x16));
if (next == 0) break;
if (!in_descriptor_table(next)) invalid("invalid Source next-stage selector link");
stage = next;
}
return pages;
}
void validate_team(const ModernState& game, uint16_t team) {
// CupGroupOverviewEffects indexes ClubIdentities directly; this screen has no empty-club fallback.
if (team == 0x0fff) invalid("Source row references the empty-club sentinel");
if (team >= game.club_ids.size()) invalid("club id outside loaded name table");
}
OtherGamesRow make_row(const ModernState& game, int home, int away, uint16_t result, int match) {
if (home < 0 || home > 0xffff || away < 0 || away > 0xffff) invalid("invalid team id");
const uint16_t h = uint16_t(home), a = uint16_t(away);
validate_team(game, h);
validate_team(game, a);
OtherGamesRow row;
row.home_team = home;
row.away_team = away;
row.home_name = game.club_name(home);
row.away_name = game.club_name(away);
row.source_result = result;
row.played = result != 0xcccc;
if (row.played) {
row.home_goals = (result >> 5) & 0x1f;
row.away_goals = result & 0x1f;
}
row.source_match = match;
return row;
}
OtherGamesClubMetadata source_metadata(const ModernState& game, int team) {
OtherGamesClubMetadata out;
bool manager_owned = game.manager_of(team) >= 0;
constexpr size_t kNationalOriginalClub = 4 * 0xb0c + 0x290;
if (!manager_owned && !game.manager_teams.empty() && game.manager_teams[0] == no_team() &&
game.manager_records.size() >= kNationalOriginalClub + 2) {
const int original_club = int(uint16_t(game.manager_records[kNationalOriginalClub] |
uint16_t(game.manager_records[kNationalOriginalClub + 1]) << 8));
manager_owned = original_club == team;
}
if (team >= first_foreign_cup() && !manager_owned) {
const size_t at = size_t(team - first_foreign_cup());
if (at >= game.foreign_strength.size()) invalid("missing Source foreign-strength byte");
out.foreign_strength = game.foreign_strength[at];
return out;
}
if (team >= first_foreign_cup() && team != no_team())
invalid("manager-controlled foreign-club row needs live TeamRating W-generator context");
constexpr std::array<uint16_t, 5> kFlags{0x0f1, 0x0f2, 0x0f4, 0x0f8, 0x0ff};
for (size_t i = 0; i < kFlags.size(); ++i)
out.averages[i] = team_average(game, team, kFlags[i]).value;
out.has_squad_values = true;
return out;
}
void attach_source_values(const ModernState& game, OtherGamesRow& row) {
row.home_metadata = source_metadata(game, row.home_team);
row.away_metadata = source_metadata(game, row.away_team);
}
void add_second_leg_and_winner(OtherGamesRow& row, uint16_t second, bool present,
bool visible, uint8_t flags) {
row.source_second_leg = second;
row.second_leg_array_present = present;
row.second_leg_visible = visible;
if (present) {
// The second fixture is reversed relative to the primary row: its low field belongs
// to the first displayed club and its high field to the second displayed club.
row.second_leg_home_goals = second & 0x1f;
row.second_leg_away_goals = (second >> 5) & 0x1f;
}
if (row.source_result == 0xcccc) return;
int home = row.home_goals;
int away = row.away_goals;
// CupTie reads the second result whenever the descriptor has an array pointer,
// independently of whether its separate detail line is visible or contains 0xcccc.
const uint16_t winner_second = present ? second : 0;
const int home_total = home + (winner_second & 0x1f);
const int away_total = away + ((winner_second >> 5) & 0x1f);
home = home_total;
away = away_total;
if ((flags & 0x10) && home == away && (row.source_result >> 11) == 0) {
home += winner_second & 0x1f;
away += row.away_goals;
}
row.source_winner = home > away ? 0 : away > home ? 1 : 2;
}
} // namespace
OtherGamesProjection other_games_from_game(const ModernState& game, const TextDb& texts,
int competition, int linked_page, int requested_round,
OtherGamesDisplayMode display_mode, int participant_offset,
bool source_new_selection) {
const StaticMemory& memory = game.memory;
if (competition < 0 || competition >= 0x14) invalid("unsupported competition selector");
if (linked_page < 0 || linked_page >= kCupEntries) invalid("invalid linked-page index");
if (!memory.has(kActiveSelectors) || !memory.has(kActiveSelectors + kSelectorCount - 1))
invalid("missing live active-competition selector list");
OtherGamesProjection out;
for (uint32_t i = 0; i < kSelectorCount; ++i) {
const uint8_t id = memory.u8(kActiveSelectors + i);
if (id == 0x14) {
out.selectors.push_back({int(i), -1, {}, false});
continue;
}
if (id > 0x14 || !in_descriptor_table(modern::find_cup(memory, id)))
invalid("active selector has no supported competition descriptor");
out.selectors.push_back({int(i), int(id), text(texts, kTextCompetitionButtonNames + id), true});
}
int entry = resolve_linked_entry(memory, competition, linked_page);
if (source_new_selection) {
std::array<bool, kCupEntries> advanced{};
while (in_descriptor_table(entry)) {
if (advanced[size_t(entry)]) invalid("cycle while advancing completed Source stages");
advanced[size_t(entry)] = true;
const uint32_t at = modern::cup_entry_address(entry);
const uint8_t next = memory.u8(at + 0x16);
if (next == 0) break;
const int count = memory.u8(at + 0x1b);
if (modern::cup_round(memory, entry) < count) break;
if (!in_descriptor_table(next)) invalid("completed stage points outside descriptor table");
entry = next;
}
}
const uint32_t address = modern::cup_entry_address(entry);
const uint8_t flags = memory.u8(address + 0x14);
const int team_count = memory.u8(address + 0x1a);
const int rounds = memory.u8(address + 0x1b);
const int live_round = modern::cup_round(memory, entry);
if (team_count < 0 || team_count > 0x40 || rounds <= 0 || rounds > 0x40)
invalid("descriptor dimensions outside Source bounds");
const int round = requested_round < 0 ? std::min(live_round, rounds - 1) : requested_round;
if (round < 0 || round >= rounds) invalid("requested round outside descriptor");
out.competition = competition;
out.descriptor_competition = int16_t(memory.u16(address + 0x18));
out.linked_page = linked_page;
out.entry_index = entry;
out.entry_address = address;
out.flags = flags;
out.knockout = (flags & 4) != 0;
out.two_legs = (flags & 1) != 0;
out.current_round = live_round;
out.round = round;
out.rounds = rounds;
out.group_index = memory.u8(address + 0x1e) >> 4;
out.group_count = memory.u8(address + 0x1e) & 0xf;
out.title = text(texts, kTextCompetitionNames + size_t(competition));
out.linked_pages = source_linked_pages(memory, entry);
int round_text = ((flags & 4) ? round : 0) + 1 + memory.u8(address + 0x1c);
if (memory.u8(address + 0x1c) == 1 && round == 0) --round_text;
if (round_text < 0 || round_text >= 32) invalid("Source round-heading index outside table");
out.round_heading = text(texts, kTextRoundHeadings + size_t(round_text));
if (kTextRoundHeadings + size_t(round_text) == kTextGroupRound && out.round_heading.size() > 0x10)
out.round_heading[0x10] = char('1' + linked_page);
if (kTextRoundHeadings + size_t(round_text) == kTextGroupCaption && out.round_heading.size() > 0x19)
out.round_heading[0x19] = char('0' + (linked_page == 0 ? 1 : linked_page));
// Source +0x1a is participants in this round. The detail/compact toggle is gated on this
// value, and detail mode's ordinary window is 16 participant slots (eight matches).
out.source_participant_count = team_count >> (round & 31);
out.display_mode_toggle_available = out.source_participant_count > 0x10;
if (display_mode != OtherGamesDisplayMode::compact && display_mode != OtherGamesDisplayMode::detail)
invalid("unknown Source display mode");
const OtherGamesDisplayMode effective_mode = out.source_participant_count <= 0x10
? OtherGamesDisplayMode::detail : display_mode;
out.display_mode = effective_mode;
if (participant_offset < 0 || participant_offset > 0x7f || participant_offset % 0x10 != 0)
invalid("participant window offset is not a Source 16-slot boundary");
// Compact draws the whole round, but the caller separately retains local14.
// Detail redraw only ORs CareerSession_DispatchOtherGames_RuntimeField's high bit; it never resets a retained cursor,
// even when a Source ID-versus-slot selection quirk leaves it past this list.
if (effective_mode == OtherGamesDisplayMode::compact) participant_offset = 0;
out.participant_offset = participant_offset;
out.round_arrows_visible = effective_mode == OtherGamesDisplayMode::detail && rounds > 1;
// CupGroupOverviewEffects selects the second-leg result array only for descriptors with the exact
// two-leg/knockout flags and when the displayed round has reached that leg.
const uint8_t played = memory.u8(address + 0x1d);
const bool second_leg = out.knockout && (played % 2 != 0 || round < played / 2) && (flags & 5) == 5;
// CupGroupOverviewEffects gates the fixture panel if this knockout round is in the future, or any
// descriptor in its +0x15 predecessor chain has not completed all its source rounds.
int predecessor = int8_t(memory.u8(address + 0x15));
std::array<bool, kCupEntries> seen_predecessors{};
while (predecessor != -1) {
if (!in_descriptor_table(predecessor) || seen_predecessors[size_t(predecessor)])
invalid("invalid/cyclic predecessor descriptor chain");
seen_predecessors[size_t(predecessor)] = true;
const uint32_t pred = modern::cup_entry_address(predecessor);
if (modern::cup_round(memory, predecessor) < memory.u8(pred + 0x1b)) out.unfinished_predecessor = true;
predecessor = int8_t(memory.u8(pred + 0x15));
}
out.fixtures_available = !out.unfinished_predecessor && (!out.knockout || round <= live_round);
out.display_mode_toggle_available = out.fixtures_available && out.source_participant_count > 0x10;
if (out.descriptor_competition == 12) out.scheduled_day_mode = true;
// Source paints TEXTD1186 and returns before touching team/result/schedule arrays for a
// blocked future or unfinished stage. Preserve that boundary for incomplete live records.
if (!out.fixtures_available) return out;
const uint32_t team_list = memory.pointer(address);
const uint32_t first_results = memory.pointer(address + 0x0c);
const uint32_t second_results = memory.pointer(address + 0x10);
if (team_count != 0 && team_list == 0) invalid("missing Source team list");
if (team_count != 0 && first_results == 0) invalid("missing Source result list");
if (out.knockout && second_leg && second_results == 0) invalid("missing Source second-leg results");
int participant_base = 0;
std::vector<Fixture> group_fixtures;
if (out.knockout) {
participant_base = uint8_t(modern::cup_round_offset(memory, entry, round));
} else {
const int table_teams = modern::cup_group_schedule_teams(memory, address);
if (table_teams <= 0) invalid("unsupported Source group-round schedule table");
const int rounds_per_leg = rounds / ((flags & 1) + 1);
if (rounds_per_leg <= 0) invalid("invalid group schedule leg count");
group_fixtures = generate_fixtures(table_teams, round + 1, rounds_per_leg, 0);
}
int row_participants = out.knockout ? out.source_participant_count : team_count;
int visible_participants = row_participants;
if (out.knockout && effective_mode == OtherGamesDisplayMode::detail)
visible_participants = std::min(visible_participants, 0x10);
const int begin = participant_offset;
const int end = out.knockout ? std::min(row_participants, begin + visible_participants) : row_participants;
if (out.scheduled_day_mode && !memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) invalid("missing live Source date for scheduled competition");
for (int p = out.knockout ? begin : 0; p + 1 < end; p += 2) {
int home = -1, away = -1, match = p / 2;
size_t result_slot = 0;
if (out.knockout) {
const int slot = participant_base + p;
if (!memory.has(team_list + uint32_t(slot) * 2 + 1)) invalid("truncated Source knockout team list");
home = memory.u16(team_list + uint32_t(slot) * 2);
away = memory.u16(team_list + uint32_t(slot + 1) * 2);
result_slot = size_t(slot / 2);
} else {
const int fixture = p / 2;
if (size_t(fixture) >= group_fixtures.size()) invalid("group fixture count does not match descriptor");
const Fixture& f = group_fixtures[size_t(fixture)];
if (!memory.has(team_list + uint32_t(f.home) * 2 + 1) ||
!memory.has(team_list + uint32_t(f.away) * 2 + 1)) invalid("truncated Source group team list");
home = memory.u16(team_list + uint32_t(f.home) * 2);
away = memory.u16(team_list + uint32_t(f.away) * 2);
result_slot = size_t(round) * size_t(team_count / 2) + size_t(fixture);
}
const uint32_t result_address = first_results + uint32_t(result_slot * 2);
if (!memory.has(result_address + 1)) invalid("truncated Source result list");
const uint16_t result = memory.u16(result_address);
OtherGamesRow row = make_row(game, home, away, result, match);
if (out.scheduled_day_mode) {
row.kind = OtherGamesRowKind::scheduled_competition;
row.played = false;
row.home_goals = row.away_goals = 0;
row.scheduled_source_day = uint32_t(memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)) +
uint32_t(int32_t(int16_t(result)));
} else if (out.knockout) {
uint16_t second = 0xcccc;
const bool second_present = second_results != 0;
if (second_results != 0) {
const uint32_t second_address = second_results + uint32_t(result_slot * 2);
if (!memory.has(second_address + 1)) invalid("truncated Source second-leg result list");
second = memory.u16(second_address);
}
add_second_leg_and_winner(row, second, second_present, second_leg, flags);
}
attach_source_values(game, row);
out.rows.push_back(std::move(row));
}
if (!out.knockout && team_count > 2) out.group_tables.push_back(modern::cup_group_table(memory, address));
return out;
}
} // namespace bmh::modern
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/other_games.hpp"
#include <cstdint>
#include <array>
#include <string>
#include <vector>
#include "formats/textd.hpp"
#include "modern/game/modern_state.hpp"
#include "game/table.hpp"
namespace bmh::modern {
// Source local20==0 (`compact`) draws the complete round in dense six-pixel rows;
// local20==1 (`detail`) draws a 16-participant window in the taller 16-pixel layout.
// One Source row in the ordinary CupGroupOverviewEffects desk view. Names and text are kept in
// Original encoding so the presentation layer can pass them through the existing FNT3 path.
// Const projection of the ordinary menu-5 call to CupGroupOverviewEffects. This API intentionally models
// only the visible values: Original entry separately updates serialized CareerSession_FormatError_RuntimeField3/selector-12 state,
// while complete/compact and page navigation persist the active manager's CareerSession_DispatchOtherGames_RuntimeField byte. It is
// therefore not evidence that the entire Original menu interaction is Native-neutral.
// `linked_page` follows the descriptor's Source +0x17 parallel-group link, then +0x16 next-stage
// link. `round == -1` selects CupRound's live round; otherwise it is range-checked.
// `participant_offset` is Source's low-seven-bit display cursor (multiples of 16). The
// displayed-round group row list remains complete; the mode/offset applies to knockout rows.
OtherGamesProjection other_games_from_game(const ModernState& game, const TextDb& texts,
int competition = 0, int linked_page = 0,
int round = -1,
OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail,
int participant_offset = 0,
bool source_new_selection = true);
} // namespace bmh::modern
+176
View File
@@ -0,0 +1,176 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/poach.hpp"
#include <algorithm>
#include "game/messages.hpp"
#include "modern/game/month.hpp"
#include "modern/game/weekly.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kAttempts = 0x8b6; // five player ids, 0xffff free
constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 rows of 0x58 bytes
constexpr uint32_t kListRow = 0x58;
constexpr uint32_t kOfferSlots = ::bmh::layout::OfferSlots; // OfferSlots: 4 words, -1 free
// Attempt: how many players of each position a club wants (MonthRuntimeField4 / MonthRuntimeField5)
constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4};
uint16_t attempt(const ModernState& g, int m, int i) {
const size_t at = size_t(m) * kRecordSize + kAttempts + size_t(i) * 2;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
// PoachAttemptsLeft(player, club): the asking percentage of the club for the player, or -1 with
// the reason in `messages`. A club of a human manager asks 100 %.
int club_asking_percent(const ModernState& g, int player, int club, std::vector<std::string>& messages, WatcomRandom& rand) {
if (g.manager_of(club) >= 0) return 100;
const Player& p = g.players.at(size_t(player));
const int position = int(p.w364 & 3);
const int strength = p.strength(true); // Strength(w35c, 1)
const int8_t* wanted = club < german_clubs() ? kWantedBig : kWantedSmall;
// SquadCount(club, 0): the fit players
if (modern::squad_count(g, club, 0) < (club < german_clubs() ? 3 : 0) + 0xe) {
messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer) + g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer2));
return -1;
}
int sum[4], count[4];
for (int k = 0; k < 4; k++) {
// QuoteNationalFriendlyMatch with 0x607 + the position bit: sum of the fit players and their number
const TeamAverage a = team_average(g, club, uint16_t((1 << (k + 4)) + 0x607));
sum[k] = int16_t(a.value);
count[k] = int8_t(a.players);
}
const int short_of = int16_t(wanted[position] - count[position]); // local_24
if (short_of >= 3 || (short_of == 0 && position == 0)) {
// the club needs him (a club always keeps its second goalkeeper)
messages.push_back(g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer3));
return -1;
}
int percent = short_of < 0 ? short_of * 0x18 + 0x8c : short_of * 16 + 0x82; // local_34
if (percent < 0x5a) percent = 0x5a;
int averages = 0;
for (int k = 0; k < 4; k++) averages = int16_t(averages + sum[k] / count[k]);
const int team = averages / 4;
int relative = team != 0 ? int16_t(strength * 100 / team) : 100; // local_30
if (relative < 0x65) {
percent -= std::clamp(100 - relative, 0, 0x14); // ClampInteger
} else {
const int over = int16_t(relative - 100) >> 1;
percent = int16_t(percent + int16_t(over * over));
}
if (short_of != 0 && percent >= 0x100) {
messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer4)); // FINANCIAL FAIRPLAY
return -1;
}
if (percent > 0xbe) percent = 0xbe;
return uint8_t(rand.range(0xc, 0x14) + percent);
}
} // namespace
int poach_attempts_left(const ModernState& g, int manager) {
int left = 0;
for (int i = 0; i < 5; i++)
if (attempt(g, manager, i) == 0xffff) left++;
return left;
}
PoachStart start_poach(ModernState& g, int manager, int squad_slot, WatcomRandom& rand) {
PoachStart out;
out.manager = manager;
out.squad_slot = squad_slot;
const size_t rec = size_t(manager) * kRecordSize;
if (attempt(g, manager, 4) != 0xffff) {
out.status = PoachStatus::attempts_used;
out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2));
return out;
}
if (g.manager_records.at(rec + 0x220) >> 5 == 1) { // PushBack
out.status = PoachStatus::transfer_ban;
out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer));
return out;
}
if (squad_slot < 0 || size_t(squad_slot) >= transfer_list_slot() || g.squad_slots.at(size_t(squad_slot)) == 0xfff) return out;
out.player = g.squad_slots.at(size_t(squad_slot)) & 0xfff;
out.club = modern::slot_team(squad_slot); // SlotTeam
if (out.club < 0 || out.club == g.manager_teams.at(size_t(manager))) return out;
// BoughtEntry: a player on loan (table Career_RemoveJoinLoans_RuntimeField)
for (int k = 0; k < 200; k++) {
const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4);
if (e != 0 && int(e & 0xfff) == out.player) {
out.status = PoachStatus::on_loan;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer));
return out;
}
}
for (int i = 0; i < 5; i++)
if (attempt(g, manager, i) == out.player) {
out.status = PoachStatus::tried_before;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer2));
return out;
}
// PlayerOnTransferListFirstPoolSlots: the player is on the transfer list (first 44 pool slots)
for (size_t s = transfer_list_slot(); s < transfer_list_slot() + 0x2c; s++)
if ((g.squad_slots.at(s) & 0xfff) == out.player) {
out.status = PoachStatus::on_transfer_list;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer3));
return out;
}
const int percent = club_asking_percent(g, out.player, out.club, out.messages, rand);
if (percent < 0) {
out.status = PoachStatus::club_refuses;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer5));
return out;
}
out.asking_percent = percent;
// RowWhose: a special row whose OfferSlots word is free
int k = 0;
while (k < 4 && g.memory.u32(kOfferSlots + uint32_t(k) * 4) != 0xffffffffu) k++;
if (k == 4) {
out.status = PoachStatus::market_busy;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer4));
modern::finish_poach(g, out);
return out;
}
out.offer_row = k;
const int demand = rand.range(0x50, 100);
// Range2(slot, 0, percent, demand, 0, k): the row like a market row of the club.
// (Its salary floor for a club of a human manager searches the buyer's own squad for
// the player and so never applies; the 0x8000 flag of the club word is kept.)
const uint32_t row = kTransferList + uint32_t(0x28 + k) * kListRow;
uint16_t club_word = uint16_t(out.club);
if (g.manager_of(out.club) >= 0) club_word |= 0x8000;
g.memory.set16(row + 8, club_word);
for (int b = 0; b < 4; b++) g.memory.set16(row + uint32_t(b) * 2, 0xffff);
g.memory.set8(row + 0x54, uint8_t(percent));
g.memory.set8(row + 0x55, uint8_t(demand));
uint32_t fee = 0, salary = 0;
modern::market_value(g, squad_slot, 0, uint8_t(percent), fee, salary, 1, 0, rand);
g.memory.set32(row + 0x2c, fee);
g.memory.set32(row + 0x30, salary);
g.squad_slots.at(transfer_list_slot() + 0x28 + size_t(k)) = uint16_t(out.player);
out.status = PoachStatus::ready;
return out;
}
void finish_poach(ModernState& g, const PoachStart& poach) {
if (poach.offer_row >= 0) {
g.squad_slots.at(transfer_list_slot() + 0x28 + size_t(poach.offer_row)) = 0xfff;
g.memory.set32(kOfferSlots + uint32_t(poach.offer_row) * 4, 0xffffffffu);
}
for (int i = 0; i < 5; i++)
if (attempt(g, poach.manager, i) == 0xffff) {
const size_t at = size_t(poach.manager) * kRecordSize + kAttempts + size_t(i) * 2;
g.manager_records.at(at) = uint8_t(poach.player);
g.manager_records.at(at + 1) = uint8_t(poach.player >> 8);
break;
}
}
} // namespace bmh::modern
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/poach.hpp"
// Poaching ("Abwerben", transfer screen menu 17, H2 p. 70; BMH.exe V2.24 + supported rule profile patch):
// the manager picks a player of another club in the league tables and makes him an offer
// that is decided at once. Button 4 of the transfer screen Reset:
//
// - at most five attempts per season: the players tried are kept in manager record
// +0x8b6 (5 words, 0xffff free; cleared at the season start, season.cpp) - CareerSession_DispatchPoachUi_TextPointer2
// - not with a transfer ban (record +0x220 >> 5 == 1, PushBack, CareerSession_DispatchPoachUi_TextPointer)
// - not for a player on loan (BoughtEntry, Poach_StartPoach_TextPointer), not twice for the same player
// (Poach_StartPoach_TextPointer2), not for a player on the transfer list (PlayerOnTransferListFirstPoolSlots, Poach_StartPoach_TextPointer3)
// - the club must let him go (PoachAttemptsLeft): its squad must be big enough, the position
// must not be short (and a club keeps its second goalkeeper); the asking percentage
// follows how much the club needs him and how good he is compared with the team
// - the offer uses one of the special list rows 40..43 (RowWhose: a row whose
// OfferSlots word is free, else "Transfermarkt überlastet"), prepared like a market
// row by Range2: asking percentage, demand W(80, 100), market value and salary.
//
// The offer itself is the ordinary offer editor (desk_actions.hpp, OpenTransferEditor) on that
// row with `poach` set; its submit (SubmitTransferBidSourceHumanBuyer) decides at once. finish_poach frees the
// row again and counts the attempt, as the original does when the editor returns.
#include <string>
#include <vector>
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// Attempts left this season (record +0x8b6).
int poach_attempts_left(const ModernState& g, int manager);
// Button 4 after the player was picked (FriendlyMatchScreen returned `squad_slot`): the checks,
// PoachAttemptsLeft, RowWhose and Range2. Draws W(12, 20) (asking percentage), W(80,
// 100) (demand) and what the market value draws. `market_busy` counts the attempt itself.
PoachStart start_poach(ModernState& g, int manager, int squad_slot, WatcomRandom& rand);
// When the offer editor has returned: the pool slot of the row is emptied, its OfferSlots
// word freed and the attempt recorded in +0x8b6.
void finish_poach(ModernState& g, const PoachStart& poach);
} // namespace bmh::modern
+205
View File
@@ -0,0 +1,205 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/prediction.hpp"
#include <string>
#include <stdexcept>
#include "modern/game/matchday.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh::modern {
namespace {
constexpr size_t kRecord = 0xB0C; // manager record
constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58; // one slot of the board
// Static league tables of V2.24 (not part of the savegame):
// (European places per league, CareerSession_InstallLeagueSizes_RuntimeField, are kLeagueEurope of the loaded game; league 0 uses 4)
// (the relegation places per league, CareerSession_InstallLeagueSizes_RuntimeField2, are kLeagueRelegation of the loaded game)
// Text of a pointer variable of the text table TextPointerTable.
} // namespace
int table_prediction(ModernState& g, int team, int mode, std::array<uint8_t, 24>& buf, int* size_word) {
buf.fill(1);
int league = team_league(team); // local_30
if (league >= kLeagueCount) return 0; // reads CareerRuntimeField6[0] = 0 as the round count
const int rounds = int8_t(g.league_rounds.at(size_t(league))); // local_1c
const int matchdays = league_matchdays(league); // LeagueMatchdayCounts
if (rounds < 2 || matchdays <= rounds) return 0;
const int manager = g.manager_of(team); // local_18, 0xFF = none
// (Fill would refresh the desk warning flags PredictionRuntimeField.. here; they are
// run-time only and not needed by the game logic.)
const size_t rec = size_t(manager) * kRecord;
const int size = kLeagueSizes[league]; // local_2c
if (size_word) *size_word = size; // (stored as a word, see the header)
if (team >= league_clubs()) return 9;
const int pos = team - league_first_team(league); // local_24
const int target[3] = {0, league == 0 ? 4 : kLeagueEurope[league], size - kLeagueRelegation[league]};
int from = 0; // local_10
if (mode > 3) {
from = rounds - 5 * (mode >> 2);
if (from < 0) from = 0;
}
auto per_game = [&](const LeagueTable& t, int club) {
const int games = t.games(club);
return games ? t.points[club] * 500 / games : 0; // the original divides by zero here
};
int own_rate = 1500; // local_34: three points per remaining game
if (mode != 1) own_rate = per_game(compute_league_table(g, league, from, rounds, 3, 0), pos);
const LeagueTable full = compute_league_table(g, league, 0, rounds, 7, 0);
int points[20] = {}, remaining[20] = {}; // acStack_60, acStack_4c
for (int c = 0; c < size; c++) {
points[c] = full.points[c];
remaining[c] = int8_t(matchdays - full.games(c));
}
// The scratch table the rates of the other clubs are read from: the recent form table
// for mode >= 4, otherwise still the full table.
const LeagueTable rates = mode > 3 ? compute_league_table(g, league, from, rounds, 3, 0) : full;
uint16_t own = uint16_t(points[pos] * 500 + remaining[pos] * own_rate); // local_28 (low word)
int ahead = size; // local_20: ranks that are out of reach
if (mode == 1) {
ahead = 0;
for (int c = 0; c < size; c++) ahead += int(own) < points[c] * 500;
}
for (int r = 0; r < ahead; r++) buf.at(size_t(r)) = 0;
int league_index = league; // local_30 is changed by the league name of message 1
if (mode == 1) {
for (int k = 0; k < 3; k++) {
if (buf.at(size_t(target[k])) != 0) continue;
if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> k & 1)) continue;
// the goal can no longer be reached
if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << k);
std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer2);
if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer3);
if (k == 1) {
std::string tail;
if (league_index == 0) {
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer4);
} else if (league_index == 2 || league_index == 3) {
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer5);
} else {
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer6);
if (league_index > 2) league_index--;
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer + uint32_t(league_index) * 4); // league name
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer7);
}
msg += tail;
}
if (k == 2) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer8);
if (manager >= 0) post_composed(g, manager, msg);
}
own = uint16_t(points[pos] * 500);
}
int behind = 0; // local_14: clubs that can no longer catch up
for (int c = 0; c < size; c++) {
if (c == pos) continue;
int rate;
if (mode == 1) rate = 1500;
else if (mode == 2) rate = 0;
else rate = int16_t(per_game(rates, c));
if (uint16_t(points[c] * 500 + remaining[c] * rate) < own) behind++;
}
int r = 0;
for (; r < behind; r++) buf.at(size_t(size - r - 1)) = 0xFF;
if (mode != 1) {
if (r == size) r++; // cannot happen: the club itself is never counted
buf.at(size_t(size - r - 1)) = 1;
}
if (mode == 1) {
for (int k = 0; k < 3; k++) {
if (buf.at(size_t(target[k])) != 0xFF) continue;
if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> (k + 3) & 1)) continue;
// the goal is secured (or relegation avoided / certain)
if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << (k + 3));
std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer9);
if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer10);
else if (k == 1)
msg += message_text(g, league_index == 0 ? ::bmh::layout::Prediction_TablePrediction_TextPointer11 : (league_index == 2 || league_index == 3) ? ::bmh::layout::Prediction_TablePrediction_TextPointer12 : ::bmh::layout::Prediction_TablePrediction_TextPointer13);
else msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer14);
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer15);
// without a manager the original posts to "manager" 0xFE; not needed here
if (manager >= 0) post_composed(g, manager, msg);
}
}
int first = 0;
while (first < 24 && buf[size_t(first)] == 0) first++;
return (first + 1) & 0xFF;
}
static uint32_t season_bonus_impl(ModernState& g, int manager, int team, int board_slot, int rank, bool pay) {
const int league = team_league(team);
uint32_t amount = 0;
if (league == 0 && rank == 0) amount = modern::pay_bonus(g, manager, board_slot, 3, pay);
if (amount == 0 && rank < 5) amount = modern::pay_bonus(g, manager, board_slot, 4, pay);
if (amount == 0 && rank < 10) amount = modern::pay_bonus(g, manager, board_slot, 5, pay);
if (amount == 0 && league < kLeagueCount && rank < kLeagueSizes[league] - kLeagueRelegation[league])
amount = modern::pay_bonus(g, manager, board_slot, 6, pay);
return amount;
}
uint32_t season_bonus(ModernState& g, int manager, int board_slot, int rank, bool pay) {
return season_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),board_slot,rank,pay);
}
static uint32_t expected_bonus_impl(ModernState& g, int manager, int team, int rank, int board_slot, int player, bool fitness) {
static const uint8_t kPerSeason[3] = {0, 34, 25}; // PredictionRuntimeField2: -, points, appearances
static const uint8_t kGoals[4] = {0, 2, 4, 8}; // PredictionRuntimeField3: goals by position
const int position = int(g.players.at(size_t(player)).w364 & 3);
if (rank == 0xFF) {
std::array<uint8_t, 24> buf;
const int r = modern::table_prediction(g, team, 4, buf);
rank = r == 0 ? 0xB : r + 1;
}
const size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot;
const uint32_t base = uint32_t(g.tactics.at(slot + 0x50) | g.tactics.at(slot + 0x51) << 8 |
g.tactics.at(slot + 0x52) << 16) | uint32_t(g.tactics.at(slot + 0x53)) << 24;
uint32_t sum = 0;
for (int k = 0; k < 3; k++) {
uint32_t times = k == 0 ? kGoals[position] : kPerSeason[k];
if (fitness && k != 1) {
// the fitness correction: a player weaker than the team average (QuoteNationalFriendlyMatch
// flags 499) earns goal and appearance bonuses less often - PredictionRuntimeField4 per gap
static const uint8_t kPerGap[3] = {1, 0, 5}; // PredictionRuntimeField4
const uint32_t w = g.players.at(size_t(player)).w35c;
int gap = int16_t(team_average(g, team, 499).value -
int((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) >> 1));
if (gap < -1) gap = -1;
const int t = int(times) - kPerGap[k] * gap;
times = t < 0 ? 0 : uint32_t(t);
}
sum += g.tactics.at(slot + 0x12 + size_t(k)) * base / 100 * times / 12;
}
return season_bonus_impl(g, manager, team, board_slot, rank & 0xFF, false) / 12 + sum;
}
uint32_t expected_bonus(ModernState& g, int manager, int rank, int board_slot, int player, bool fitness) {
return expected_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),rank,board_slot,player,fitness);
}
uint32_t expected_bonus_parked_club_source(ModernState& g, int rank, int board_slot, int player, bool fitness) {
constexpr size_t team_at=4*kRecord+0x290;
if(g.manager_teams!=std::vector<int>{no_team()} || !g.memory.has(::bmh::layout::CoachActive) ||
g.memory.u8(::bmh::layout::CoachActive)==0 || !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 ||
!g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 ||
g.manager_records.size()<5*kRecord ||
(int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=no_team() ||
board_slot<0 || board_slot>=24 || g.tactics.size()<5*kBoard)
throw std::invalid_argument("expected_bonus: invalid FindManagerForClub parked club context");
const int team=int(g.manager_records[team_at]) | int(g.manager_records[team_at+1])<<8;
if(team<0 || team>=league_clubs())
throw std::invalid_argument("expected_bonus: parked record4 has no ordinary club");
return expected_bonus_impl(g,4,team,rank,board_slot,player,fitness);
}
} // namespace bmh::modern
+55
View File
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/prediction.hpp"
// Table prediction and bonus expectations of human managers (BMH.exe V2.24).
//
// table_prediction Void5 which final ranks a club can still reach / has secured
// expected_bonus ContractOffer bonus a player on the tactics board can expect
// season_bonus SeasonBonus the board's season bonus (title, Europe, staying up)
//
// team_rating (rating.cpp) uses them for the players of human managers: a player who can
// expect a large bonus relative to his base pay tries harder (+5 with some probability).
// As a side effect the prediction posts the "still possible" / "no longer possible"
// messages about the season goals (champion, Europe, relegation) to the manager, once per
// goal and season (bits 0-5 of manager record +0x28b).
#include <array>
#include <cstdint>
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// Void5(team, mode, buf). Fills buf[0..23], one entry per final rank:
// 0 the rank can no longer be reached (at least that many clubs stay ahead)
// 1 the predicted rank (modes other than 1)
// 0xFF a rank the club cannot fall to any more
// and returns the first rank (1-based) that is not 0, i.e. the best reachable rank.
// mode 1: maximum points = points + 3 per remaining game for every club (and messages);
// mode 2: the club's own points per game projected, the others stay where they are;
// mode 3: every club projected with its own points per game;
// mode >= 4: as 3, but the points per game over the last 5 * (mode / 4) matchdays.
// `size_word` receives the league size, which the original stores as a word in its frame
// (local_2c) unless it returns early (before the second matchday etc.; then it stays
// untouched). The side ratings read that stack word as a stale value, see team_rating.
// Returns 0 before the second matchday and after the last one (and for leagues >= 9),
// 9 for clubs outside the league system (ids from 138 on).
int table_prediction(ModernState& g, int team, int mode, std::array<uint8_t, 24>& buf, int* size_word = nullptr);
// ContractOffer(manager, predicted rank, board slot, player, 0): goal, point and appearance
// bonus of the board slot, each weighted by how often it is earned (goals by position:
// PredictionRuntimeField3, points 34, appearances 25 per season), plus the season bonus for the
// predicted rank, all divided by 12. `rank` 0xFF means: predict it (table_prediction mode 4).
// Only the variant without the fitness correction (last argument 0) is ported.
uint32_t expected_bonus(ModernState& g, int manager, int rank, int board_slot, int player, bool fitness = false);
// Checked FindManagerForClub record4 variant for a club parked during national takeover.
// Read the actual club from record4 without adding it to the active manager list.
uint32_t expected_bonus_parked_club_source(ModernState& g, int rank, int board_slot, int player, bool fitness = false);
// SeasonBonus(manager, board slot, rank, 0): season bonus of the slot for a final rank:
// title (league 0 only, rank 0), top 5, top 10, staying up (bonus indices 3-6 of the slot,
// the first one that is set and applies). Not paid.
uint32_t season_bonus(ModernState& g, int manager, int board_slot, int rank, bool pay = false);
} // namespace bmh::modern
+244
View File
@@ -0,0 +1,244 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/reschedule.hpp"
#include <algorithm>
#include "modern/game/matchday_setup.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh::modern {
namespace {
constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day
constexpr int kCalendarDays = 0x16e; // CalendarCell copies 0x16e words
constexpr uint32_t kPostponed = ::bmh::layout::Postponed; // 40 entries: u16 day, round, league, match
constexpr int kPostponedEntries = 0x28;
constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; // friendly plan: team pairs
constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; // friendly plan: days, 30 entries
constexpr int kFriendlyEntries = 30;
// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break.
constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8;
// RescheduleLeagueMatch accepts replay days up to 0x11e; the draw loop wants the day after the
// target inside 0x15 .. 0x11e.
constexpr int kLastReplayDay = 0x11e, kFirstDayAfter = 0x15;
constexpr uint8_t kRescheduledMark = 0xce; // param_5 = -0x32
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kFloodlights = 0x0e; // manager record byte (RescheduleRuntimeField)
// LeagueCalendarBits: calendar bit of a league (the two leagues 2 and 3 share bit 2, the four
// leagues of 12 clubs bit 4; compare kGroupLeague in matchday_setup.cpp).
// (kLeagueBit: schedule.hpp, set from the groups of the loaded game; 0xff = not played)
size_t result_at(int league, int round, int match) { return size_t(match) + size_t(round) * 10 + size_t(league) * 0x17c; }
bool memory_ok(const ModernState& g) {
return g.memory.has(kCalendar + kCalendarDays * 2 - 1) &&
g.memory.has(kPostponed + kPostponedEntries * 6 - 1) && g.memory.has(kFriendlyDays + kFriendlyEntries * 2 - 1) &&
g.memory.has(kFriendlyTeams + kFriendlyEntries * 4 - 1);
}
// The club of a human manager in league play, or -1.
int manager_team(const ModernState& g, int manager) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return -1;
const int team = g.manager_teams[size_t(manager)];
if (team < 0 || team_league(team) >= kLeagueCount) return -1;
return team;
}
std::vector<Fixture> round_fixtures(int league, int round) {
return generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league));
}
// DayConflict(team, other, word, day): 1 when `day` (calendar word `word` of the screen's
// copy) cannot take a match of `team`/`other`: the word is taken (anything but 0, 0x4001 or
// a word marked eligible with bit 15) or the friendly plan already has a match of one of the
// teams - or of the national team - on that day.
bool day_conflict(const ModernState& g, int team, int other, uint16_t word, int day) {
if (word != 0 && word != 0x4001 && (word & 0x8000) == 0) return true;
for (int i = 0; i < kFriendlyEntries; i++) {
if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(day)) continue;
for (int side = 0; side < 2; side++) {
const int t = int16_t(g.memory.u16(kFriendlyTeams + uint32_t(i) * 4 + uint32_t(side) * 2));
if (t == no_team() || t == team || t == other) return true;
}
}
return false;
}
// RescheduleTargetDays(day, team, league): entry + 1 of a replay of `team` in `league` on `day`, or 0
// (the last such entry, as the original keeps looking).
int team_replay_on(const ModernState& g, int day, int team, int league) {
int found = 0;
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day) || g.memory.u8(at + 3) != league) continue;
const Fixture f = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4));
if (f.home == team || f.away == team) found = e + 1;
}
return found;
}
// The draw loop of CalendarCell in mode 2 on a copy of the calendar: a future day is marked
// (bit 15) when it is free (0, 0x4001 or a calendar event 0x1c0), neither it nor its two
// neighbours conflict for the club (the neighbours before it may already be marked), the
// day after it lies in 0x15 .. 0x11e and it is not in the winter break. The national team
// (manager 0 coaching team 0x165) also checks the club of the Bundestrainer, CupDraw_FormatError_RuntimeField3.
std::vector<uint16_t> marked_calendar(const ModernState& g, int team) {
std::vector<uint16_t> cal(kCalendarDays);
for (int d = 0; d < kCalendarDays; d++) cal[size_t(d)] = g.memory.u16(kCalendar + uint32_t(d) * 2);
// DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day
const int today = g.season_day();
const bool national = !g.manager_teams.empty() && g.manager_teams[0] == no_team() && g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField);
for (int d = today + 1; d < kCalendarDays; d++) {
const uint16_t word = cal[size_t(d)];
if (word != 0 && word != 0x4001 && (word & 0x1c0) == 0) continue;
bool ok = true;
for (int i = std::max(0, d - 1); i <= std::min(kCalendarDays - 1, d + 1); i++) {
if (day_conflict(g, team, -1, cal[size_t(i)], i)) ok = false;
if (national && day_conflict(g, int16_t(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)), -1, cal[size_t(i)], i)) ok = false;
}
if (d + 1 > kLastReplayDay || d + 1 < kFirstDayAfter) ok = false;
if (d >= kWinterBreakFirst && d <= kWinterBreakLast) ok = false;
if (team == no_team() && (word & 0x1c0) != 0) ok = false;
if (ok) cal[size_t(d)] |= 0x8000;
}
return cal;
}
} // namespace
std::vector<LeagueMatchRef> reschedulable_matches(const ModernState& g, int manager) {
std::vector<LeagueMatchRef> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const int league = team_league(team);
// The screen only reacts to the calendar bit of the club's league for bits 0-3
// (local_34 == bit); CalendarCell derives local_34 as league - (league > 2).
const int screen_bit = league > 2 ? league - 1 : league;
if (screen_bit > 3 || kLeagueBit[league] != screen_bit) return out;
// DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day
const int today = g.season_day();
const int matchdays = league_matchdays(league);
int round = -1;
for (int day = 0; day < kCalendarDays; day++) {
const uint32_t comps = modern::day_competitions(g, g.memory.u16(kCalendar + uint32_t(day) * 2));
if (kLeagueBit[league] > 7 || !((comps >> kLeagueBit[league]) & 1)) continue;
++round; // local_58 - 1: the league days up to this one
if (day <= today || round == 0 || round + 2 >= matchdays) continue;
const std::vector<Fixture> fixtures = round_fixtures(league, round);
for (size_t m = 0; m < fixtures.size(); m++) {
const Fixture& f = fixtures[m];
if (f.home != team && f.away != team) continue;
// the screen picks the club's match of the day; only a home match can be moved
if (f.home == team && g.results.at(result_at(league, round, int(m))) == kNotPlayed)
out.push_back({day, round, league, int(m), f.home, f.away});
break;
}
}
return out;
}
std::vector<int> reschedule_target_days(const ModernState& g, int manager, const LeagueMatchRef& match) {
std::vector<int> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const std::vector<LeagueMatchRef> movable = modern::reschedulable_matches(g, manager);
if (std::none_of(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) {
return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match;
}))
return out;
std::vector<uint16_t> cal = marked_calendar(g, team);
// floodlights: the day before the matchday (the Friday) is offered as well
if ((size_t(manager) + 1) * kRecordSize <= g.manager_records.size() &&
g.manager_records[size_t(manager) * kRecordSize + kFloodlights] != 0 && match.day > 0)
cal[size_t(match.day - 1)] |= 0x8000;
for (int d = 0; d < kCalendarDays; d++)
if ((cal[size_t(d)] & 0x8000) && d != match.day && d <= kLastReplayDay && team_replay_on(g, d, team, match.league) == 0)
out.push_back(d);
return out;
}
RescheduleStatus reschedule_league_match(ModernState& g, int manager, const LeagueMatchRef& match, int day) {
if (manager_team(g, manager) < 0 || !memory_ok(g)) return RescheduleStatus::invalid_manager;
const std::vector<LeagueMatchRef> movable = modern::reschedulable_matches(g, manager);
const auto it = std::find_if(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) {
return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match;
});
if (it == movable.end()) return RescheduleStatus::invalid_match;
const std::vector<int> days = modern::reschedule_target_days(g, manager, *it);
if (std::find(days.begin(), days.end(), day) == days.end()) return RescheduleStatus::invalid_day;
// the first free entry of the postponed list
int slot = -1;
for (int e = 0; e < kPostponedEntries && slot < 0; e++)
if (g.memory.u16(kPostponed + uint32_t(e) * 6) == 0) slot = e;
if (slot < 0) return RescheduleStatus::no_free_slot;
// RescheduleLeagueMatch(day, league, match, slot, -0x32, round): eight replays on the day or a
// team clash with one of them refuse the move. Like the winter mode the original builds
// the other replay's fixtures with the parameters of this league and compares the low
// bytes of the team ids only.
const int league = it->league;
const Fixture own = round_fixtures(league, it->round).at(size_t(it->match));
int same_day = 0;
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day)) continue;
if (++same_day == 8) return RescheduleStatus::day_full;
const Fixture other = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4));
const uint8_t oh = uint8_t(other.home), oa = uint8_t(other.away), fh = uint8_t(own.home), fa = uint8_t(own.away);
if (fh == oh || fa == oa || fa == oh || fh == oa) return RescheduleStatus::team_clash;
}
const uint32_t at = kPostponed + uint32_t(slot) * 6;
g.memory.set16(at, uint16_t(day));
g.memory.set8(at + 2, uint8_t(it->round));
g.memory.set8(at + 3, uint8_t(league));
g.memory.set8(at + 4, uint8_t(it->match));
g.results.at(result_at(league, it->round, it->match)) = kRescheduledMark;
const uint32_t high = kCalendar + uint32_t(day) * 2 + 1;
g.memory.set8(high, g.memory.u8(high) | 0x40);
return RescheduleStatus::moved;
}
std::vector<LeagueMatchRef> moved_matches(const ModernState& g, int manager) {
std::vector<LeagueMatchRef> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const int league = team_league(team);
const int today = g.season_day();
// CalendarCell: a click on a replay day (calendar bit 0xe) finds the club's replay with
// RescheduleTargetDays(day, team, league) and calls UndoReschedule when its result byte is 0xCE
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
const int day = g.memory.u16(at);
if (day == 0 || day <= today || g.memory.u8(at + 3) != league) continue;
if (team_replay_on(g, day, team, league) != e + 1) continue;
const int round = g.memory.u8(at + 2), m = g.memory.u8(at + 4);
if (round == 0 || round + 2 >= league_matchdays(league)) continue;
if ((g.results.at(result_at(league, round, m)) & 0xcf) != kRescheduledMark) continue;
const Fixture f = round_fixtures(league, round).at(size_t(m));
out.push_back({day, round, league, m, f.home, f.away});
}
std::sort(out.begin(), out.end(), [](const LeagueMatchRef& a, const LeagueMatchRef& b) { return a.day < b.day; });
return out;
}
bool undo_reschedule(ModernState& g, int manager, int day) {
const std::vector<LeagueMatchRef> moved = modern::moved_matches(g, manager);
if (std::none_of(moved.begin(), moved.end(), [&](const LeagueMatchRef& m) { return m.day == day; })) return false;
const int team = manager_team(g, manager);
// UndoReschedule(day, 1, team): every replay of the club on that day, whatever its league
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day)) continue;
const int league = g.memory.u8(at + 3), round = g.memory.u8(at + 2), m = g.memory.u8(at + 4);
const Fixture f = round_fixtures(league, round).at(size_t(m));
if (f.home != team && f.away != team) continue;
g.results.at(result_at(league, round, m)) = kNotPlayed;
g.memory.set16(at, 0);
}
return true;
}
} // namespace bmh::modern
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/reschedule.hpp"
// Rescheduling a home league match (desk menu 7, "Verlegen", H2 p. 49; BMH.exe V2.24 +
// supported rule profile patch). The original does it on the calendar screen CalendarCell with mode 2:
//
// 1. The manager clicks a matchday of his own league. The match of his club on that day
// is selected when it is a home match, still in the future, not on the first matchday
// and not on one of the last two matchdays.
// 2. The calendar then marks the days the match can move to (draw loop of CalendarCell,
// see reschedule_target_days). With floodlights (manager record +0x0e) the day before
// the matchday (the Friday) is offered as well.
// 3. A click on a marked day moves the match with RescheduleLeagueMatch(day, league, match, slot,
// -0x32, round): the match becomes a "replay" on that day (postponed list Postponed),
// its result byte becomes 0xCE and the calendar day gets bit 0x4000. On the original
// matchday the 0xCE turns into 0xCD (matchday_setup) and the match is played on the
// new day like a winter postponement.
// 4. A click on the new day of a moved match takes the move back (UndoReschedule(day, 1,
// team)): the entry is freed and the result byte is 0xCC again. The calendar keeps bit
// 0x4000, as in the original.
//
// Everything here works on the saved ModernState only: no random numbers are drawn, so a
// rescheduled career stays deterministic.
#include <cstdint>
#include <vector>
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// A league match: day of the season (index into the calendar CompetitionCalendar), the 0-based
// league round, the league and the index of the match in the fixture list of that round.
// The own home league matches that can be moved: future days, rounds 1 .. matchdays - 3
// (0-based), result byte still 0xCC (not played, not postponed). Only clubs of leagues
// 0-4 (calendar bits 0-3) take part: the lower leagues have no own calendar bit.
std::vector<LeagueMatchRef> reschedulable_matches(const ModernState& g, int manager);
// The days `match` can be moved to (the days CalendarCell marks in mode 2), ascending.
// Days that already hold a replay of one of the teams in the same league are left out, as
// the second click refuses them (RescheduleTargetDays).
std::vector<int> reschedule_target_days(const ModernState& g, int manager, const LeagueMatchRef& match);
// Moves `match` to `day` (RescheduleLeagueMatch with param_5 = -0x32). Returns moved on success; on
// failure nothing is changed.
RescheduleStatus reschedule_league_match(ModernState& g, int manager, const LeagueMatchRef& match, int day);
// The own matches moved with reschedule_league_match that can still be taken back: their new
// day (`day`) is in the future, the result byte is 0xCE and the round is one the screen
// accepts (1 .. matchdays - 3). Winter postponements (0xCD) are not listed. Like the
// original the club need not be the home side: in a hot seat game the opponent's manager can
// take back a move as well.
std::vector<LeagueMatchRef> moved_matches(const ModernState& g, int manager);
// Takes back the move of the club's match on `day` (one of moved_matches) - UndoReschedule with
// param_2 = 1: every replay on that day with the club gets result byte 0xCC and its entry is
// freed. Returns false if there is no such match.
bool undo_reschedule(ModernState& g, int manager, int day);
} // namespace bmh::modern
+200
View File
@@ -0,0 +1,200 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/save.hpp"
#include <cstdio>
#include <cstring>
#include <fstream>
#include "formats/savestate.hpp"
#include "modern/game/career.hpp"
#include "modern/game/national.hpp"
namespace bmh::modern {
namespace {
void put(Bytes& d, const uint8_t* src, size_t n) {
for (size_t i = 0; i < n && i < d.size(); i++) d[i] = src[i];
}
void put(Bytes& d, const std::vector<uint8_t>& v) { put(d, v.data(), v.size()); }
void put16(Bytes& d, const std::vector<uint16_t>& v) {
for (size_t i = 0; i < v.size() && 2 * i + 1 < d.size(); i++) d[2 * i] = uint8_t(v[i]), d[2 * i + 1] = uint8_t(v[i] >> 8);
}
void put32(Bytes& d, size_t at, uint32_t x) {
for (int i = 0; i < 4 && at + size_t(i) < d.size(); i++) d[at + size_t(i)] = uint8_t(x >> (8 * i));
}
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
// four-year leap cycle that starts with the third year).
std::string date_text(uint32_t counter, int start_year) {
static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int cycle = 3, years = 0, month = 7;
while (counter > uint32_t(364 + (cycle == 4))) {
if (cycle == 4) cycle = 0, --counter;
++years, counter -= 365, ++cycle;
}
auto days = [&] { return month == 2 ? 28 + (cycle == 4) : kDays[month]; };
while (counter > uint32_t(days())) {
counter -= uint32_t(days());
if (++month == 13) month = 1, ++years;
}
int day = int(counter) + 1;
if (day > days()) {
day -= days();
if (++month == 13) month = 1, ++years;
}
char buf[16];
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, start_year + years);
return buf;
}
} // namespace
Bytes save_stream(const ModernState& live) {
// NationalCoachAfterLoad writes a Bundestrainer's game with the slots swapped back (national.hpp)
const bool coach = live.memory.has(::bmh::layout::CoachActive) && live.memory.u8(::bmh::layout::CoachActive) != 0;
const ModernState swapped = coach ? modern::national_coach_save_form(live) : ModernState{};
const ModernState& g = coach ? swapped : live;
const bool records = g.memory.has(::bmh::layout::ClubSeasonRecords) && g.memory.u32(::bmh::layout::ClubSeasonRecords) != 0;
Bytes stream;
for (const SaveBlock& b : save_layout(DbCounts{}, records)) {
Bytes d(b.size, 0);
if (b.heap) {
switch (b.address) {
case ::bmh::layout::PlayerBonuses: put(d, g.player_bonus); break;
case ::bmh::layout::TeamMorale: put(d, g.team_morale); break;
case ::bmh::layout::ClubBadgeSelectors: put(d, g.club_heap_78); break;
case ::bmh::layout::TeamFlags: put16(d, g.team_flags); break;
case ::bmh::layout::ClubIdentities: put16(d, g.club_ids); break;
case ::bmh::layout::PlayerNameOffsets: put16(d, g.player_name_offsets); break;
case ::bmh::layout::MasterDatabaseMetadata: put(d, g.master_database_metadata); break;
case ::bmh::layout::ClubAuxiliaryWords: put(d, g.club_heap_bc); break;
case ::bmh::layout::LeagueRankHistory: put(d, g.position_history); break;
case ::bmh::layout::ClubAuxiliaryBytes: put(d, g.club_heap_b8); break;
case ::bmh::layout::SquadSlots: put16(d, g.squad_slots); break;
case ::bmh::layout::PlayerCards: put16(d, g.player_cards); break;
case ::bmh::layout::ManagerMailbox: put(d, g.mailbox); break;
case ::bmh::layout::TournamentName: put(d, g.tournament_name); break;
case ::bmh::layout::ClubSeasonRecords: put(d, g.club_table); break;
case ::bmh::layout::PlayerConditionTechniqueForm:
case ::bmh::layout::PlayerSkillWords:
case ::bmh::layout::PlayerIdentityWords:
for (size_t i = 0; i < g.players.size(); i++) {
const Player& p = g.players[i];
put32(d, i * 4, b.address == ::bmh::layout::PlayerConditionTechniqueForm ? p.w35c : b.address == ::bmh::layout::PlayerSkillWords ? p.w368 : p.w364);
}
break;
default: break;
}
} else {
for (size_t i = 0; i < b.size; i++)
if (g.memory.has(b.address + uint32_t(i))) d[i] = g.memory.u8(b.address + uint32_t(i));
// the blocks ModernState keeps in typed fields
switch (b.address) {
case ::bmh::layout::ManagerRecords: put(d, g.manager_records); break;
case ::bmh::layout::ManagerMatchHistory: put(d, g.manager_results); break;
case ::bmh::layout::ManagerRatings: put(d, g.manager_ratings); break;
case ::bmh::layout::LeagueResults: put(d, g.results); break;
case ::bmh::layout::LeagueRoundCounters: put(d, g.league_rounds); break;
case ::bmh::layout::TacticsBoards: put(d, g.tactics); break;
case ::bmh::layout::StockExchange: put(d, g.stocks); break;
case ::bmh::layout::ManagerAutomation: put(d, g.manager_options); break;
case ::bmh::layout::Formations: put(d, g.formations); break;
case ::bmh::layout::ForeignClubStrength: put(d, g.foreign_strength); break;
case ::bmh::layout::Difficulty: d[0] = uint8_t(g.level); break;
case ::bmh::layout::CalendarDay: put32(d, 0, g.date); break;
case ::bmh::layout::DaysIntoSeason: d[0] = uint8_t(g.date - g.season_start), d[1] = uint8_t((g.date - g.season_start) >> 8); break;
case ::bmh::layout::PlayerDevelopmentBalance: put32(d, 0, uint32_t(g.development_balance)); break;
case ::bmh::layout::SeasonIndex: d[0] = uint8_t(g.season), d[1] = uint8_t(uint16_t(g.season) >> 8); break;
default: break;
}
}
stream.insert(stream.end(), d.begin(), d.end());
}
for (const std::vector<uint8_t>* pool : {&g.club_names, &g.player_names, &g.referee_names, &g.stadium_names}) {
stream.push_back(uint8_t(pool->size()));
stream.push_back(uint8_t(pool->size() >> 8));
stream.insert(stream.end(), pool->begin(), pool->end());
}
// the English cup memory has no place in the original layout: OpenBMH extension
std::vector<SaveState::ExtensionBlock> extension;
for (const auto& [at, size] : kEnglishCompetitionBlocks)
if (g.memory.has(at) && g.memory.has(at + size - 1)) {
Bytes bytes(size);
for (uint32_t i = 0; i < size; ++i) bytes[i] = g.memory.u8(at + i);
extension.push_back({at, std::move(bytes)});
}
append_save_extension(stream, extension);
return stream;
}
Bytes save_header(const ModernState& g) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
Bytes h;
h.push_back(uint8_t(managers));
const std::string date = date_text(g.date, g.display_start_year);
for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0);
Bytes list(0xa0, 0);
for (int m = 0; m < managers && m < 4; m++) {
const size_t rec = size_t(m) * 0xb0c;
const int team = int16_t(g.manager_records.at(rec + 0x290) | g.manager_records.at(rec + 0x291) << 8);
const bool national = team == no_team();
const size_t at = size_t(m) * 0x28;
list[at] = national ? 0x1e : g.manager_records.at(rec + 0x210); // (0x1e: high byte of the loop word)
list[at + 1] = national ? 1 : 0;
for (size_t i = 0; i < 0x13; i++) list[at + 2 + i] = g.manager_records.at(rec + 0xa8 + i);
const size_t name = g.club_ids.at(size_t(team));
for (size_t i = 0; i < 0x13 && name + i < g.club_names.size(); i++) list[at + 0x15 + i] = g.club_names[name + i];
}
h.insert(h.end(), list.begin(), list.end());
return h;
}
Savegame make_savegame(const ModernState& g, WatcomRandom& rand) {
Savegame s;
s.plain_header = modern::save_header(g);
s.id1 = 0;
s.version = "V2.24";
const uint32_t hi = uint32_t(rand.range(0, 0x8fff)), lo = uint32_t(rand.range(0, 0x8fff));
s.id2 = lo + hi * 0x10000 + 1;
s.key = uint8_t(rand.range(0, 0xff) + 'n');
s.random = uint8_t(rand.range(0, 0xff));
s.stream = modern::save_stream(g);
uint8_t sum = s.key;
for (uint8_t b : s.stream) sum = uint8_t(sum + b);
s.checksum = sum;
s.checksum_ok = true;
return s;
}
Bytes savegame_bytes(const Savegame& s) {
Bytes out = s.plain_header;
static const char magic[10] = {'K', 'R', 'O', 'N', '_', 'F', 'B', 'M', 0, 'k'};
out.insert(out.end(), magic, magic + 10);
for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id1 >> (8 * i)));
for (size_t i = 0; i < 6; i++) out.push_back(i < s.version.size() ? uint8_t(s.version[i]) : 0);
for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id2 >> (8 * i)));
out.push_back(s.random);
out.push_back(s.key);
Bytes enc = s.stream;
fbm_encrypt(enc.data(), enc.size(), s.key);
out.insert(out.end(), enc.begin(), enc.end());
out.push_back(s.checksum);
return out;
}
void write_savegame(const std::filesystem::path& path, const Savegame& s) {
const Bytes b = modern::savegame_bytes(s);
std::ofstream f(path, std::ios::binary | std::ios::trunc);
if (!f) throw FormatError("cannot write " + path.string());
f.write(reinterpret_cast<const char*>(b.data()), std::streamsize(b.size()));
const bool written = bool(f);
f.close();
// Buffered final bytes can fail only at close, after write reported the
// complete size. The autosave caller must not publish that temporary file.
if (!written || !f) throw FormatError("short write " + path.string());
}
} // namespace bmh::modern
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/save.hpp"
// Writing savegames (MakeSavegame with FbmDecrypt2 and NationalCoachAfterLoad).
//
// A ModernState keeps part of the savegame in typed fields (players, squads, records, ...)
// and the rest in StaticMemory; save_stream puts both back into the block order of the
// original, so that loading a savegame and saving it again gives the same stream.
#include <cstdint>
#include <filesystem>
#include "formats/binary.hpp"
#include "formats/fbm.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// The decrypted stream of a savegame: the 125 state blocks (NationalCoachAfterLoad, with the club
// records when their pointer ClubSeasonRecords is set) and the four name pools.
Bytes save_stream(const ModernState& g);
// FbmDecrypt2: the plain header read by the load list - the number of managers, the date
// ("TT.MM.JJJJ") and per manager (0x28 bytes): start league, national team flag, his name
// and his club's name (0x13 bytes each). The original leaves stack bytes in the unused
// parts; they are zero here.
Bytes save_header(const ModernState& g);
// MakeSavegame from the header on: "KRON_FBM", the previous id (here 0), "V2.24", the new
// id W(0, 0x8fff) << 16 + W(0, 0x8fff) + 1, the key byte W(0, 0xff) + 'n' and a random byte
// W(0, 0xff) (the four Watcom draws of saving), the encrypted stream and its checksum.
Savegame make_savegame(const ModernState& g, WatcomRandom& rand);
// The file bytes of a savegame (inverse of load_savegame).
Bytes savegame_bytes(const Savegame& s);
void write_savegame(const std::filesystem::path& path, const Savegame& s);
} // namespace bmh::modern
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
#include "game/season.hpp"
// OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets.
// From one season to the next (BMH.exe V2.24 + supported rule profile patch).
//
// On 1 July the "Weiter" loop (DailyInterest) ends the season: CareerSession_RuntimeError_RuntimeField4 = 1, the season
// bonuses (SeasonAwards) and the manager's desk "Saisonende". When he leaves it with
// "Anstoss" the offers still open for his players are answered (DispatchClubPlayerPendingOffers, from
// AdvanceTurn) and the new season is set up (the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest):
// season + 1 (SeasonIndex), the clubs' moods and flags (ClubBalance), the European
// cups and their foreign clubs (CareerSeasonSetup(1)), contracts (GameEndTaxAnimationScreen, Void),
// the league tables to the cups (CareerSeasonSetup(2)), the German clubs in Europe shown
// (SeasonOperation), the national cup draw (Getenv), promotion and relegation
// (CareerSeasonSetup3, SeasonEndSteps), the managers' season records (ManagerOf), the day steps
// up to the first Wednesday and the new transfer list (CareerFirstSteps); the season day
// DaysIntoSeason restarts at 0.
// Annual accounts expose the Original acknowledgement/decision boundary before
// booking tax. Headless callers without a selector use the Original NO branch.
#include <functional>
#include <array>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
#include "game/transfer_allocator.hpp"
namespace bmh::modern {
// SeasonProfitTax continues GameEndTaxAnimationScreen's loop without reinitialising its local fine.
// This state lives for one annual-accounts pass across all human managers.
// CupDrawFromGame: the generated order, then Getenv/CupGroupOverviewEffects.
// Participants are owned copies of the current round at each boundary.
// DispatchClubPlayerPendingOffers (the loop at the end of AdvanceTurn): the offers for players of human
// manager `manager` (OfferSlots) are answered. A salary demand (a club tries to lure the
// player away) is accepted with `accept`: the board salary becomes the offered one and
// its percentage of the market salary is noted (+0xd). Declining it needs the transfer
// (IncomingTransferScreen) and is reported. A fee offer opens the negotiation screen (IncomingTransferScreen /
// OpenTransferEditor), which restarts the game generator from CareerSession_Invalid_RuntimeField2 and draws the
// negotiator's picture; with `game` the manager refuses the release (right click, the
// message box "Sie verweigern dem Spieler die Freigabe!"). A transfer_decision callback
// may accept a fee offer. Interactive Main uses process_natural_pending_offers_after_desk
// with its typed presenters and shared human-buyer settlement instead of this legacy API.
// (The offer slots are freed by free_offer_slots after all desks.)
void answer_offers(ModernState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report,
GameRandom* game = nullptr);
// The end of the desk loop of AdvanceTurn, after every manager's desk and answers: the four
// offer slots (transfer list entries 0x28..0x2b, OfferSlots) are freed.
void free_offer_slots(ModernState& g);
// OpenBMH deviates from the original: retains the enhanced academy player-generation strength bands with monthly youth budgets.
// Annual recruitment with an active middle youth budget (or a paid legacy
// academy contract), provided the squad has room. Shared player strength bands
// remain in effect; see season.cpp.
bool youth_academy_player(ModernState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ClubBalance(0): every club's mood (TeamMorale, W(20, 30)) and flags (*TeamFlags): a random
// base, two levels from the final table position (title holders get the top one) with
// random exceptions, and two from the balance of its squad (CareerSeasonSetup4).
// CareerSeasonSetup4(team): bits 8-11 of the club flags from the balance of its squad (W draws).
void club_balance(ModernState& g, int team, WatcomRandom& rand);
// The end of InitializeCareer (a new career, after the managers): the national team flag, every
// league club's balance (CareerSeasonSetup4) and automatic line-up (humans with the bit 0x80),
// the title holders of the cups, CareerSeasonSetup(3) (international tournament, European
// entrants, national cup field), the season tickets (CareerSeasonSetup2), Getenv(0x40, 0) and
// the players' season (CareerSeasonSetup3).
// `pause` is called at the screens the original waits at (as in season_transition).
bool career_season_setup(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const char*)>& pause = nullptr,
const SeasonCupDrawHook& cup_draw = {});
// CareerFirstSteps2 after InitializeCareer and the start of DailyInterest(0): the game generator's seed is
// saved (CareerSession_Invalid_RuntimeField2), the clubs of each league change places at random (Getenv2) and the
// transfer list gets its first players (CareerFirstSteps). The "Weiter" loop then prepares the
// first event (AdvanceTurn) up to the first desk.
bool career_first_steps(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ClubsChangePlaces(a, b): two clubs (ids below 168) change places in every table per club id.
void clubs_change_places(ModernState& g, int a, int b);
// With `new_career` (ClubBalance(1), start of a career) both levels are 1 for every club and
// the position draws are skipped.
void reset_club_moods(ModernState& g, GameRandom& game, WatcomRandom& rand, bool new_career = false);
// The CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest (see above). Missing runtime context or
// invalid state is reported through MinuteReport; presenters are supplied by the caller.
// `pause` is called where the original waits for the manager (a screen): week_check compares
// the recorded pauses there.
// Void -> SeasonPromotionScreen: already computed local lists, before swaps.
// The arrays are owned; only their first `count` entries are displayed/swapped.
// In group 1 without play-offs, count may be smaller than relegated.size().
SeasonTransitionOutcome season_transition(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const char*)>& pause = {},
const SeasonHighscoreHook& highscore = {},
const SeasonTaxHooks& tax_hooks = {},
const SeasonPromotionHook& promotion_hook = {},
const SeasonCupDrawHook& cup_draw = {},
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// GameEndTaxAnimationScreen/SeasonProfitTax profit branch: show ACK, ask JA/NEIN, perform its exact RNG
// and sanctions, then store the carry values and debit tax plus any fine once.
// The caller supplies the already rounded seasonal profit, before ticket income.
void season_apply_profit_tax(ModernState& g, int manager, int32_t profit,
GameRandom& game, WatcomRandom& rand,
const SeasonTaxHooks& hooks = {},
SeasonTaxState* continuation = nullptr);
// GameEndTaxAnimationScreen / SeasonProfitTax: progressive tax on a rounded seasonal profit.
// Exposed so the threshold and integer-rounding rules can be tested directly.
int32_t season_profit_tax(int32_t profit);
// GameEndTaxAnimationScreen: next-season tax refund after a lower profit; returns zero when
// the original conditions do not grant a refund.
int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit,
int32_t previous_tax_paid);
// SeasonAwards, on 1 July before the "Saisonende" desk: per league (< 5) the club of the
// top scorer (goals), of the best scorer (goals + assists, list Season_List_RuntimeField) and the fair
// play winner (fewest card points); a human manager's club gets the prize (SeasonRuntimeField26)
// with a message.
void season_awards(ModernState& g);
// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): the
// running competitions' slot 4 (this year's international tournament), the manager's screen
// state and the friendlies 0xc while their entry 30 has teams.
void cup_overview_effects(ModernState& g);
// CupGroupOverviewEffects's group cursor is owned by this stage entry; the national cup's
// existing overview path intentionally keeps its original effects unchanged.
void cup_group_overview_effects(ModernState& g, int group_index);
// LeagueName: the name of a league below 5 (with its letter, e.g. for the third divisions).
std::string league_name(const ModernState& g, int league);
// MonthChange(absolute squad slot): the player leaves his club for the free agents with new
// values (W and game draws) and an age W(4, 15); his club closes the gap (ReleasePlayer,
// with a human club its tactics board as well). False if the source ownership/state
// cannot be validated; the player movement and human board compaction are implemented.
bool release_player(ModernState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh::modern
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/game/source_tip.hpp"
#include <bit>
#include <cstdint>
namespace bmh::modern {
uint8_t source_tip_result(GameRandom& game, const std::array<uint8_t, 10>& gap,
int home_rating, int away_rating,
int home_secondary, int away_secondary) {
uint8_t home = uint8_t((away_secondary + 0x14 < home_secondary) + game.range(0, 1));
uint8_t away = uint8_t((away_secondary < home_secondary) + game.range(0, 1));
const uint32_t wrapped = uint32_t(home_rating) - uint32_t(away_rating);
const int32_t signed_difference = std::bit_cast<int32_t>(wrapped);
int32_t scaled = signed_difference / 10;
if (scaled < 0) scaled = -scaled;
uint8_t local_c = uint8_t(scaled);
if (home_rating > away_rating) {
if (local_c > 9) local_c = 9;
home = uint8_t(home + game.range(0, int(gap[local_c]) + 1));
}
if (home_rating < away_rating) {
// ComputeLeagueTableForecast negates the byte before clamping it to the gap table.
local_c = uint8_t(-int(local_c));
if (local_c > 9) local_c = 9;
away = uint8_t(away + game.range(0, int(gap[local_c])));
if (local_c < 5) home = uint8_t(home + 1);
}
for (;;) {
const int cap = game.range(2, 6);
if (int(home) + int(away) <= cap) break;
if (home) --home;
if (away) --away;
}
return uint8_t((home << 4) | away);
}
} // namespace bmh::modern
+20
View File
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/game/modern_state.hpp"
#include "game/source_tip.hpp"
#include <array>
#include <cstdint>
#include "game/random.hpp"
namespace bmh::modern {
// ComputeLeagueTableForecast's pure score arithmetic after the caller has obtained the four
// QuoteNationalFriendlyMatch ratings. Each invocation consumes the same G draws, including
// the final goal-cap draw that terminates the loop.
uint8_t source_tip_result(GameRandom& game, const std::array<uint8_t, 10>& gap,
int home_rating, int away_rating,
int home_secondary, int away_secondary);
} // namespace bmh::modern
+168
View File
@@ -0,0 +1,168 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/game/stadium_blocks.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/matchday.hpp"
#include <algorithm>
#include <limits>
namespace bmh::modern {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kManagerClub = 0x290;
constexpr size_t kBuild = 0x34;
constexpr size_t kFlags = 0x44;
constexpr size_t kCapacity = 0x4c;
constexpr size_t kFutureCapacity = 0x54;
constexpr uint8_t kSeat = 1;
constexpr uint8_t kRoof = 2;
constexpr uint8_t kKnownFeatures = kSeat | kRoof;
bool slot_index(StadiumBlockSlot slot, size_t& out) {
const auto raw = static_cast<uint8_t>(slot);
if (raw >= 8) return false;
out = raw;
return true;
}
uint16_t record_u16(const std::vector<uint8_t>& records, size_t at) {
return uint16_t(records.at(at)) | uint16_t(records.at(at + 1)) << 8;
}
std::optional<uint32_t> checked_component(uint32_t price_per_1000, uint32_t places,
uint32_t multiplier, uint32_t divisor) {
const uint64_t units = places / 1000;
const uint64_t multiplied = uint64_t(price_per_1000) * units * multiplier;
if (multiplied > uint64_t(std::numeric_limits<int32_t>::max())) return std::nullopt;
return uint32_t(multiplied / divisor);
}
bool valid_resolved_offer(const StandBlockOffer& offer, const StadiumBlockExpansionQuote& quote) {
if (offer.percent < 6 || offer.percent > 14 || offer.base_price != quote.base_price ||
offer.base_days != quote.base_weeks || offer.base_days < 0 || offer.base_days > 255 ||
offer.offered_price != uint32_t(uint64_t(quote.base_price) * uint32_t(100 + offer.percent) / 100) ||
offer.price > uint32_t(std::numeric_limits<int32_t>::max()))
return false;
switch (offer.decision) {
case StandBlockOfferDecision::Declined:
return offer.price == offer.base_price && offer.construction_days == offer.base_days;
case StandBlockOfferDecision::Accepted:
// PrepareStandBlockOffer forms base_price * (100 + percent) in a signed
// 32-bit intermediate before dividing by 100. Do not accept a
// mathematically representable final uint32 when that Source
// intermediate would overflow. Declined offers do not use it.
return uint64_t(quote.base_price) * uint32_t(100 + offer.percent) <=
uint64_t(std::numeric_limits<int32_t>::max()) &&
offer.price == offer.offered_price &&
offer.construction_days <= offer.base_days - (offer.base_days >> 3) &&
offer.construction_days >= offer.base_days - (offer.base_days >> 1);
case StandBlockOfferDecision::Pending:
default:
return false;
}
}
} // namespace
std::optional<StadiumBlockExpansionQuote> quote_stadium_block_expansion(
const ModernState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places,
uint8_t desired_features, int company_price_percent,
const StadiumBlockExpansionConstants& constants) {
size_t block = 0;
if (!slot_index(slot, block) || manager < 0 ||
size_t(manager) >= g.manager_teams.size() ||
(size_t(manager) + 1) * kRecordSize > g.manager_records.size())
return std::nullopt;
const int club = g.manager_teams[size_t(manager)];
const size_t rec = size_t(manager) * kRecordSize;
if (club < 0 || club == no_team() || record_u16(g.manager_records, rec + kManagerClub) != uint16_t(club))
return std::nullopt;
const uint8_t build_weeks = g.manager_records.at(rec + kBuild + block);
const uint8_t raw_flags = g.manager_records.at(rec + kFlags + block);
const uint8_t current_capacity = g.manager_records.at(rec + kCapacity + block);
const uint8_t future_capacity = g.manager_records.at(rec + kFutureCapacity + block);
const uint32_t maximum = constants.max_places[block];
const uint32_t unit_price = constants.price_per_1000[block];
const uint8_t duration = constants.weeks[block];
// Active construction and idle unknown bits are not editable A–H source states.
if (build_weeks != 0 || (raw_flags & uint8_t(~kKnownFeatures)) != 0 ||
(desired_features & uint8_t(~kKnownFeatures)) != 0 ||
(desired_features & uint8_t(raw_flags & kKnownFeatures)) != uint8_t(raw_flags & kKnownFeatures) ||
company_price_percent < 0 || company_price_percent > 427 || unit_price == 0 ||
maximum == 0 || maximum > 255000 || maximum % 1000 != 0 || duration == 0)
return std::nullopt;
const uint32_t current_places = uint32_t(current_capacity) * 1000;
if (total_target_places < current_places || total_target_places > maximum ||
total_target_places / 1000 > 255)
return std::nullopt;
const uint32_t new_places = total_target_places - current_places;
const auto new_cost = checked_component(unit_price, new_places, 1, 1);
if (!new_cost) return std::nullopt;
const uint32_t seats_places = (raw_flags & kSeat) != 0 ? new_places : total_target_places;
const uint32_t roof_places = (raw_flags & kRoof) != 0 ? new_places : total_target_places;
const auto seats_cost = (desired_features & kSeat) != 0
? checked_component(unit_price, seats_places, 45, 100) : std::optional<uint32_t>(0);
const auto roof_cost = (desired_features & kRoof) != 0
? checked_component(unit_price, roof_places, 30, 100) : std::optional<uint32_t>(0);
if (!seats_cost || !roof_cost) return std::nullopt;
const uint64_t sum = uint64_t(*new_cost) + *seats_cost + *roof_cost;
if (sum > uint64_t(std::numeric_limits<int32_t>::max()) ||
sum * uint32_t(company_price_percent) > uint64_t(std::numeric_limits<int32_t>::max()))
return std::nullopt;
const uint32_t price = uint32_t(sum * uint32_t(company_price_percent) / 100);
StadiumBlockExpansionQuote quote;
quote.manager = manager;
quote.manager_club = club;
quote.slot = slot;
quote.current_build_weeks = build_weeks;
quote.current_raw_flags = raw_flags;
quote.current_capacity_thousands = current_capacity;
quote.current_future_capacity_thousands = future_capacity;
quote.total_target_places = total_target_places;
quote.desired_features = desired_features;
quote.company_price_percent = company_price_percent;
quote.price_per_1000 = unit_price;
quote.max_places = maximum;
quote.new_places = new_places;
quote.new_places_cost = *new_cost;
quote.seats_cost = *seats_cost;
quote.roof_cost = *roof_cost;
quote.undiscounted_cost = uint32_t(sum);
quote.base_price = price;
quote.base_weeks = duration;
return quote;
}
bool build_stadium_block_expansion(
ModernState& g, int manager, StadiumBlockSlot slot,
const StadiumBlockExpansionConstants& constants,
const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer,
WatcomRandom& rand, const ConstructionNoticeHook& payment_notice,
const SeasonTicketCompensationNoticeHook& compensation_notice) {
if (manager != quote.manager || slot != quote.slot || quote.base_price == 0 ||
!valid_resolved_offer(resolved_offer, quote))
return false;
const auto fresh = modern::quote_stadium_block_expansion(g, manager, slot, quote.total_target_places,
quote.desired_features, quote.company_price_percent, constants);
if (!fresh || *fresh != quote) return false;
// Sponsor is always false for Original A–H construction. In particular this
// preserves +0x171 and prevents pay_construction's sponsor-only W draws.
if (!modern::pay_construction(g, manager, resolved_offer.price, false, rand, payment_notice)) return false;
const size_t rec = size_t(manager) * kRecordSize;
const size_t block = static_cast<uint8_t>(slot);
g.manager_records.at(rec + kBuild + block) = resolved_offer.construction_days;
g.manager_records.at(rec + kFlags + block) = uint8_t(
g.manager_records.at(rec + kFlags + block) | uint8_t(quote.desired_features << 4));
g.manager_records.at(rec + kFutureCapacity + block) = uint8_t(quote.total_target_places / 1000);
modern::season_ticket_compensation_source(g, manager, compensation_notice);
return true;
}
} // namespace bmh::modern
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/game/modern_state.hpp"
#include "game/stadium_blocks.hpp"
#include "modern/game/desk_actions.hpp"
#include "modern/game/weekly.hpp"
#include <array>
#include <cstdint>
#include <optional>
namespace bmh::modern {
// Source choices 8..15 map to eight independent A–H record slots. These must
// not be confused with StadiumInvestment's facilities 0..7.
// An immutable quote binds the Source owner and every record/table value that
// affects the quote. Commit recomputes this value before it touches money.
// Pure Source projection. Manual totals need not be multiples of 1000; only the
// eventual +54 byte is floored to thousands. The supported source boundary is
// 0..427 company percent, 0..255 thousand places, a positive duration, and
// trusted table maxima <=255000. Current/target placement must satisfy
// current<=target<=maximum; busy blocks, unknown idle feature bits, owner
// mismatches, disabled existing features, malformed constants and any
// intermediate that overflows Source's signed 32-bit arithmetic have no quote.
// A valid zero-price quote remains previewable; commit refuses to construct it.
std::optional<StadiumBlockExpansionQuote> quote_stadium_block_expansion(
const ModernState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places,
uint8_t desired_features, int company_price_percent,
const StadiumBlockExpansionConstants& constants);
// Commit an already resolved tip decision exactly once. `Declined` proceeds at
// the base quote; `Accepted` uses its precomputed price and weeks. A zero-price
// quote never constructs. Notice exceptions propagate so the caller can restore
// its full transaction checkpoint.
bool build_stadium_block_expansion(
ModernState& g, int manager, StadiumBlockSlot slot,
const StadiumBlockExpansionConstants& constants,
const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer,
WatcomRandom& rand, const ConstructionNoticeHook& payment_notice = {},
const SeasonTicketCompensationNoticeHook& compensation_notice = {});
} // namespace bmh::modern
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/table_forecast.hpp"
#include <bit>
#include <stdexcept>
#include "game/schedule.hpp"
#include "modern/game/source_tip.hpp"
namespace bmh::modern {
LeagueTableForecast compute_league_table_forecast(
const ModernState& game, int league, int source_param2, int matchdays,
int flags, int normal_mode, int sort_extra,
const std::array<uint8_t, 10>& gap, const GameRandom& game_random) {
if (league < 0 || league >= kLeagueCount)
throw std::invalid_argument("table forecast: invalid league");
if (source_param2 != 0)
throw std::invalid_argument("table forecast: only Source param2 zero is reviewed");
const int source_matchdays = league_matchdays(league);
if (matchdays != source_matchdays)
throw std::invalid_argument("table forecast: matchday count differs from Source league");
if (flags < 0 || flags > 7)
throw std::invalid_argument("table forecast: unsupported Source aggregation flags");
if (normal_mode < 0 || normal_mode > 1 || sort_extra < 0 || sort_extra > 14 || (sort_extra & 1))
throw std::invalid_argument("table forecast: unsupported Source points/sort parameters");
if (game.league_rounds.size() < size_t(kLeagueCount) || game.results.size() < kResultsSize)
throw std::invalid_argument("table forecast: Native round/results inputs unavailable");
const int points_mode = normal_mode + sort_extra;
LeagueTableForecast out;
out.table = compute_league_table(game, league, 0, matchdays, flags, points_mode);
out.game_after = game_random;
const int raw_round = int(game.league_rounds[size_t(league)]);
out.first_simulated_round = raw_round + (source_param2 != 0);
const int first_team = league_first_team(league);
const int teams = league_table_teams(league);
int32_t source_seed = 0;
if (out.first_simulated_round < matchdays) {
if (!game.memory.has(::bmh::layout::TableForecast_InvalidArgument_RuntimeField))
throw std::invalid_argument("table forecast: Native Source seed unavailable for future rounds");
source_seed = std::bit_cast<int32_t>(game.memory.u32(::bmh::layout::CurrentMatchday));
if (source_seed < 0 || source_seed > 10000)
throw std::invalid_argument("table forecast: Native Source seed outside 0..10000");
}
for (int round = out.first_simulated_round; round < matchdays; ++round) {
const auto fixtures = generate_fixtures(teams, round + 1, matchdays / 2, first_team);
// ComputeLeagueTableForecast is invoked once per round and reseeds once at entry,
// before iterating that round's fixture pairs.
out.game_after.set_seed(source_seed);
for (const auto& fixture : fixtures) {
const int home_primary = team_average(game, fixture.home, 0x3f3).value;
const int home_secondary = team_average(game, fixture.home, 0x3fc).value;
const int away_primary = team_average(game, fixture.away, 0x3f3).value;
const int away_secondary = team_average(game, fixture.away, 0x3fc).value;
// GameRandom::set_seed deliberately preserves the cumulative call count.
const uint8_t encoded = modern::source_tip_result(out.game_after, gap,
home_primary, away_primary, home_secondary, away_secondary);
const int clubs[2] = {fixture.home - first_team, fixture.away - first_team};
const uint8_t goals[2] = {uint8_t(encoded >> 4), uint8_t(encoded & 0x0f)};
add_result(out.table, clubs, goals, flags & 3, normal_mode);
}
if (matchdays < round + 3) sort_table(out.table, sort_extra >> 1);
++out.simulated_rounds;
}
return out;
}
} // namespace bmh::modern
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "modern/game/modern_state.hpp"
#include "game/table_forecast.hpp"
#include <array>
#include <cstdint>
#include "game/random.hpp"
#include "game/table.hpp"
namespace bmh::modern {
// Scratch result of the Table screen's one-shot KI projection. `game_after`
// contains Source G after all per-ComputeLeagueTableForecast reseeds/draws; callers commit it
// only with the accepted UI/session transition. Native results and CurrentMatchday are
// never changed here.
// Only the reviewed E37 normal family entry (Source param2 == 0) is supported.
// All work is local: invalid input or a projection exception cannot mutate the
// caller's GameRandom or ModernState.
LeagueTableForecast compute_league_table_forecast(
const ModernState& game, int league, int source_param2, int matchdays,
int flags, int normal_mode, int sort_extra,
const std::array<uint8_t, 10>& gap, const GameRandom& game_random);
} // namespace bmh::modern
+223
View File
@@ -0,0 +1,223 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/turn.hpp"
#include "game/trace.hpp"
#include "modern/game/month.hpp"
#include "modern/game/national.hpp"
#include "modern/game/week.hpp"
#include "modern/game/weekly.hpp"
namespace bmh::modern {
bool full_game(const ModernState& g) { return g.memory.has(::bmh::layout::CompetitionSelection) && (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) != 0; }
void event_end(ModernState& g) {
if (g.memory.has(::bmh::layout::Savestate_Layout_ExecutableField8)) g.memory.set8(::bmh::layout::Turn_EventEnd_RuntimeField, 1);
}
void day_stock_market(ModernState& g, GameRandom& game) {
if (modern::full_game(g)) modern::stock_market(g, game);
}
bool month_step(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
if (!modern::full_game(g) || g.date == 0 || modern::month_code(g.date - 1) == modern::month_code(g.date)) return true;
modern::month_change(g, rand, report, &game); // DayStepRest2
return !report.unsupported;
}
bool day_step_rest(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
uint16_t source_season_day, TransferAllocatorContext allocator) {
// DayStepRest tests CareerSession_PairingsRuntimeDraw_ExecutableField6 after DeskDate2(date - 1): the weekday of the
// previous day decides whether it is a training day
const int wd = modern::weekday_code(g.date - 1);
const bool training = wd == 2 || wd == 6;
const bool month = modern::full_game(g) && g.date > 0 && modern::month_code(g.date - 1) != modern::month_code(g.date);
// the Bundestrainer leaves the national team for the day's processing: on a training day
// the national squad trains first (FamiliarityDecay), then the slots are swapped back
// (NationalCoachHandBack); at the end he takes it over again (SwapManagerSlots2, ActiveManager left at
// the number of managers by the loop below)
const bool coach = (training || month) && modern::national_coach_active(g);
if (coach) {
if (training) modern::familiarity_decay(g, game, rand);
modern::national_coach_hand_back(g);
}
if (training) {
if (modern::full_game(g) && modern::weekday_code(g.date) == 3) {
turn_step = "weekly_processing";
modern::weekly_processing(g, game, rand, report, allocator); // DayStepRest3
if (report.unsupported) return false;
}
turn_step = "training";
modern::familiarity_decay(g, game, rand);
for (size_t m = 0; m < g.manager_teams.size(); m++) modern::train_squad(g, int(m), game, rand);
}
turn_step = "month_step";
const bool ok = modern::month_step(g, game, rand, report);
if (coach) modern::national_coach_take_over(g, int(g.manager_teams.size()), source_season_day);
return ok;
}
} // namespace bmh::modern
#include "modern/game/matchday_setup.hpp"
#include "modern/game/season.hpp"
namespace bmh::modern {
void plain_day(ModernState& g, GameRandom& game, WatcomRandom& rand) {
modern::day_stock_market(g, game);
g.date++;
modern::daily_interest(g, rand);
}
bool empty_event_day(ModernState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
modern::setup_matchday(g, 0, ctx, game, rand, report);
turn_step = "prepare_event: matchday number";
modern::draw_matchday_number(g, rand); // CurrentMatchday
modern::shuffle_manager_order(g, game);
modern::event_end(g);
g.date++;
modern::daily_interest(g, rand);
return !report.unsupported;
}
bool is_season_end(const ModernState& g) { return g.date > 0 && modern::month_code(g.date) == 7 && modern::month_code(g.date - 1) != 7; }
void season_end_day(ModernState& g) {
if (modern::national_coach_active(g)) modern::national_coach_hand_back(g); // DailyInterest: NationalCoachHandBack first
if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 1);
modern::season_awards(g);
if (g.memory.has(::bmh::layout::EventPasses)) g.memory.set8(::bmh::layout::EventPasses, 0);
}
} // namespace bmh::modern
#include "modern/game/desk.hpp"
namespace bmh::modern {
std::vector<MatchGroup> prepare_event(ModernState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game,
WatcomRandom& rand, MinuteReport& report) {
std::vector<MatchGroup> groups = modern::setup_matchday(g, modern::day_competitions(g, calendar_entry), ctx, game, rand, report);
modern::draw_matchday_number(g, rand); // CurrentMatchday
turn_step = "prepare_event: manager order";
const std::vector<int> order = modern::shuffle_manager_order(g, game);
for (size_t k = 0; k < order.size() && g.memory.has(::bmh::layout::NextDeskManager + uint32_t(k) * 2); k++)
g.memory.set16(::bmh::layout::NextDeskManager + uint32_t(k) * 2, uint16_t(order[k]));
return groups;
}
bool enter_event_desk(ModernState& g, int position, const std::vector<MatchGroup>& groups, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer,
const DeskAutosaveHook& autosave) {
const int manager = g.manager_teams.size() > 1 ? g.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2) : position;
if (g.memory.has(::bmh::layout::DeskPosition)) g.memory.set8(::bmh::layout::DeskPosition, uint8_t(position));
if (g.memory.has(::bmh::layout::ActiveManager)) g.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager));
// AdvanceTurn(param1 != 0) suppresses only PreMatchOffer on the remaining
// desks of a loaded manager loop. Coupon preparation and desk entry still run.
// (an out-of-range access below names its step: the error reaches the player as text)
const char* step = "pre_match_offer";
try {
const bool offer = prepare_pre_match_offer
? modern::pre_match_offer(g, manager, game, rand, report) : false;
step = "build_pools_coupon";
modern::build_pools_coupon(g, groups, &rand); // BuildPoolsCoupon
step = "enter_desk";
modern::enter_desk(g, manager, game, rand, autosave); // DeskDate
return offer;
} catch (const std::out_of_range& e) {
throw std::out_of_range(std::string(e.what()) + " (" + step + ", manager " + std::to_string(manager) + ")");
}
}
} // namespace bmh::modern
#include "formats/binary.hpp"
#include "modern/game/cup.hpp"
#include "modern/game/matchday.hpp"
namespace bmh::modern {
void finish_event(ModernState& g, std::vector<MatchGroup>& groups, uint16_t calendar_entry, const std::vector<uint8_t>& buttons,
const std::vector<uint8_t>& saved_records, const std::vector<uint8_t>& saved_options, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw,
const SportschauPresentationHooks* sportschau, const std::vector<ShowEvent>* show_events,
bool source_sportschau_replay, const SportschauRatingTables* ratings) {
if (report.unsupported) return;
for (size_t m = 0; m < g.manager_teams.size(); m++)
for (int s = 0; s < 24; s++)
for (int k = 0; k < 2; k++) {
const size_t at = m * 0x840 + size_t(s) * 0x58 + 0x44 + size_t(k) * 2;
g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F;
}
auto show_intro = [&](int group_index) {
if (!sportschau || !sportschau->intro) return;
SportschauIntroView view;
view.group_index = group_index;
for (size_t i = 0; i < groups.size() && i <= 0xff; ++i) {
const MatchGroup& group = groups[i];
view.groups.push_back({uint8_t(i), group.desc.at(0), le32(group.desc, 0xcc),
int16_t(modern::sportschau_source_setting_index(g, group))});
}
sportschau->intro(g, view);
};
show_intro(-1);
for (size_t group_index = 0; group_index < groups.size(); ++group_index) {
MatchGroup& grp = groups[group_index];
// FinishEvent sets DeskPosition to the current match-group index. Its final nonempty
// iteration leaves the last index visible to the following cup presentation.
if (g.memory.has(::bmh::layout::DeskPosition) && group_index <= 0xff)
g.memory.set8(::bmh::layout::DeskPosition, uint8_t(group_index));
if (group_index <= 0xff) show_intro(int(group_index));
if (ratings && !source_sportschau_replay) {
// FinishEvent/BuildSideRecords clear eleven scores outside the CareerSession_SportschauSourceOptions_ExecutableField gate.
// The loaded EXE owner still performs that reset when it skips
// MatchdayIntro entirely; old slot words remain untouched.
for (size_t i = 0; i < 11; ++i) {
grp.desc.at(0x70 + i) = 0;
const uint32_t address = ::bmh::layout::Turn_FinishEvent_ExecutableField + uint32_t(group_index) * 0xd0 + uint32_t(i);
if (group_index < 6 && g.memory.has(address)) g.memory.set8(address, 0);
}
}
modern::process_group(g, grp, game, rand, report, int(group_index),
sportschau ? sportschau->fixture : SportschauFixtureHook{}, show_events,
source_sportschau_replay && sportschau ? &sportschau->replay : nullptr,
source_sportschau_replay ? ratings : nullptr);
if (report.unsupported) return;
if (source_sportschau_replay && ratings) {
const auto awards = finish_sportschau_awards(g, grp, int(group_index));
if (awards && sportschau && sportschau->awards) sportschau->awards(g, *awards);
if (sportschau && sportschau->team_info) {
const auto info = sportschau_team_info_view(g, grp, int(group_index));
if (info) sportschau->team_info(g, *info);
}
}
const uint32_t id = le32(grp.desc, 0xcc);
if (id < 0x15) {
if (modern::league_screen_shown(buttons, 1, 90, int(id))) modern::stir_random(game, rand);
const int round = g.league_rounds.at(id);
for (int m = 0; m < grp.matches(); m++) g.results.at(size_t(id) * 0x17C + size_t(round) * 10 + size_t(m)) = grp.results.at(size_t(m));
} else {
modern::store_cup_results(g, grp);
}
}
// FinishEvent/BuildSideRecords call EvaluatePoolsCoupon(1) after every group's processing,
// before returning to AdvanceTurn's calendar/round advancement. Result evaluation
// at the second half is separate; pools_open does not gate this settlement.
modern::settle_pools_coupon(g, groups);
for (size_t m = 0; m < g.manager_teams.size() && !saved_records.empty(); m++) {
for (size_t k = 0; k < 8; k++) g.manager_records.at(m * 0xB0C + 0xd2 + k) = saved_records.at(m * 0xB0C + 0xd2 + k);
g.manager_options.at(m * 5 + 2) = saved_options.at(m * 5 + 2);
}
const uint32_t competitions = modern::day_competitions(g, calendar_entry);
modern::advance_league_rounds(g, competitions & 0x1F, rand, report,
sportschau ? sportschau->winner : CompetitionWinnerHook{});
for (int bit = 5; bit < 0x13; bit++)
if ((competitions >> bit) & 1) modern::advance_cup(g, bit - 5, rand, report, &game, cup_draw,
sportschau ? sportschau->winner : CompetitionWinnerHook{});
modern::event_end(g);
}
} // namespace bmh::modern
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/turn.hpp"
// The "Weiter" loop of the original (DailyInterest) - everything between two desks of the
// human managers: the day steps, the weekly and monthly processing, the matchdays with
// their preparation, the cups, the season end and the season change.
//
// Built up step by step from the parts verified with tests/week_check (which uses these
// functions, so every regression run checks them against the recordings).
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/season.hpp"
#include "game/sportschau_presentation.hpp"
#include "modern/game/modern_state.hpp"
#include "game/transfer_allocator.hpp"
namespace bmh::modern {
// Whether the career plays the leagues (CompetitionSelection bit 0, "full game"); without them
// there is no weekly or monthly processing.
bool full_game(const ModernState& g);
// DailyInterest: the daily share price run (DailyInterest3) only with the leagues on
// (CompetitionSelection bit 0) - the world game without leagues keeps its prices.
void day_stock_market(ModernState& g, GameRandom& game);
// The end of AdvanceTurn: EventEnd(TurnRuntimeField), with the value layout field the program
// start leaves there, sets Turn_EventEnd_RuntimeField = 1.
void event_end(ModernState& g);
// The rest of the day step DayStepRest after the date moved on: on a training day (the
// previous day's weekday code 2 or 6) the weekly processing (DayStepRest3, full game,
// when the new day has weekday code 3), the decay of the familiarity and every human
// manager's training; then the month change (DayStepRest2) when the month moved on.
// Returns false on a reported state/context failure; see MinuteReport::reason.
bool day_step_rest(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
uint16_t source_season_day,
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// The month change part alone (full game only, when the new day is in another month).
bool month_step(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh::modern
namespace bmh::modern {
// A day without an event (the "Weiter" loop): the shares move (DailyInterest3), then the
// date counts on and the daily interest is booked (the start of DayStepRest). The rest
// of the day step (day_step_rest) follows.
void plain_day(ModernState& g, GameRandom& game, WatcomRandom& rand);
// A calendar entry whose competitions are all switched off (e.g. 0x4006 without the
// option CompetitionSelection bit 1) is still an event for DailyInterest: AdvanceTurn prepares an
// empty matchday (DayCompetitions2, the matchday number, the manager order) without a desk;
// then the date counts on (with the daily interest) as after any event.
bool empty_event_day(ModernState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// 1 July (DailyInterest: CareerSession_PairingsRuntimeDraw_ExecutableField4 == 1, CareerSession_PairingsRuntimeDraw_ExecutableField5 == 7): the season is over -
// CareerSession_RuntimeError_RuntimeField4 = 1, the prizes for top scorers and fair play (SeasonAwards); no event is
// due any more (EventPasses = 0). The managers' "Saisonende" desk follows.
bool is_season_end(const ModernState& g);
void season_end_day(ModernState& g);
} // namespace bmh::modern
#include <vector>
#include "modern/game/desk.hpp"
namespace bmh::modern {
// AdvanceTurn up to its desk loop for the day's calendar entry: the match groups
// (DayCompetitions2), the matchday number (CurrentMatchday) and the shuffled order of the
// managers' desks (PrepareEvent, kept in NextDeskManager).
std::vector<MatchGroup> prepare_event(ModernState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game,
WatcomRandom& rand, MinuteReport& report);
// One pass of that desk loop for the manager at `position` of the order: ActiveManager /
// DeskPosition, a pre-match offer (PreMatchOffer; true = its message box comes first), the
// pools coupon (BuildPoolsCoupon) and entering the desk (DeskDate).
bool enter_event_desk(ModernState& g, int position, const std::vector<MatchGroup>& groups, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer = true,
const DeskAutosaveHook& autosave = {});
} // namespace bmh::modern
namespace bmh::modern {
// The end of a matchday after its last phase (the part of FinishEvent / AdvanceTurn after
// the matches): the human boards' substitution marks are cleared, every group is processed
// (process_group; a league's result screen - when shown - stirs the numbers, its results go
// into the season table, a cup's into its rounds), the managers' match settings changed
// during the matches (record +0xd2..+0xd9, option byte 2) return to `saved_records` /
// `saved_options` (taken at the kick-off), the leagues count their round and the cups of the
// day move on.
void finish_event(ModernState& g, std::vector<MatchGroup>& groups, uint16_t calendar_entry, const std::vector<uint8_t>& buttons,
const std::vector<uint8_t>& saved_records, const std::vector<uint8_t>& saved_options, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw = {},
const SportschauPresentationHooks* sportschau = nullptr,
const std::vector<ShowEvent>* show_events = nullptr,
bool source_sportschau_replay = false,
const SportschauRatingTables* ratings = nullptr);
} // namespace bmh::modern
+594
View File
@@ -0,0 +1,594 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/turn_driver.hpp"
#include <algorithm>
#include <array>
#include <exception>
#include "modern/game/desk.hpp"
#include "modern/game/driver.hpp"
#include "modern/game/matchday.hpp"
#include "modern/game/matchday_setup.hpp"
#include "game/trace.hpp"
#include "modern/game/national.hpp"
#include "modern/game/season.hpp"
#include "modern/game/turn.hpp"
#include "modern/game/week.hpp"
namespace bmh::modern {
namespace {
constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar;
// The calendar entry of a season day. The table has 366 days (0-365); a season that starts
// on 1 July and spans 29 February ends on day 366, where the original reads the next bytes
// of its data (the fixture pointer table at CareerSession_RuntimeError_ExecutableField) - no competition. OpenBMH deviates from
// the original here: such a day has no calendar entry (0) instead of whatever lies behind.
uint16_t calendar_day(const ModernState& g, int day) {
const uint32_t at = kCalendar + uint32_t(day) * 2;
return day >= 0 && g.memory.has(at + 1) && at + 1 < ::bmh::layout::CareerSession_RuntimeError_ExecutableField ? g.memory.u16(at) : uint16_t(0);
}
constexpr uint32_t kDeskButtons = ::bmh::layout::LeaguePresentationOptions;
constexpr uint32_t kSavedCompetition = ::bmh::layout::SavedCompetition;
constexpr uint32_t kCoachActive = ::bmh::layout::CoachActive;
constexpr uint32_t kOriginalManagerCount = ::bmh::layout::OriginalManagerCount;
constexpr uint32_t kManagerCount = ::bmh::layout::ManagerCount;
constexpr uint32_t kManagerOrder = ::bmh::layout::NextDeskManager;
constexpr uint32_t kDeskPosition = ::bmh::layout::DeskPosition;
constexpr uint32_t kActiveManager = ::bmh::layout::ActiveManager;
constexpr uint32_t kEventPasses = ::bmh::layout::EventPasses;
// DailyInterest sets the saved loop count once per calendar date: three Hall
// rounds on the first of two consecutive Hall days, two on the last day.
// Completing a round does not run another date/training/interest step.
void start_event_passes(ModernState& g, uint16_t entry) {
if (!g.memory.has(kEventPasses)) return;
uint8_t passes = 1;
if (entry == 0x4002) {
const uint32_t next = kCalendar + uint32_t(g.season_day() + 1) * 2;
passes = g.memory.has(next + 1) && g.memory.u16(next) == 0x4002 ? 3 : 2;
}
g.memory.set8(kEventPasses, passes);
}
bool consume_event_pass(TurnDriver& driver, ModernState& g) {
if (!g.memory.has(kEventPasses)) return false;
// Only the Hall calendar cell has multiple passes. Old OpenBMH saves
// carried a stale Hall count into ordinary dates; do not repeat leagues.
const bool hall = driver.calendar_entry == 0x4002 && g.indoor;
const uint8_t count = hall ? g.memory.u8(kEventPasses) : 1;
const uint8_t remaining = count == 0 ? 0 : uint8_t(count - 1);
g.memory.set8(kEventPasses, remaining);
return hall && remaining != 0;
}
std::vector<uint8_t> read_buttons(const ModernState& g) {
std::vector<uint8_t> result;
if (!g.memory.has(kDeskButtons + 0xb3)) return result;
result.reserve(0xb4);
for (uint32_t i = 0; i < 0xb4; ++i) result.push_back(g.memory.u8(kDeskButtons + i));
return result;
}
MatchdayContext matchday_context(const ModernState& g, std::vector<uint8_t>& referees) {
MatchdayContext context;
context.month = modern::month_code(g.date);
context.season_day = g.season_day();
context.weekday = modern::weekday_code(g.date);
context.referees = &referees;
return context;
}
bool saved_national_nomination_desk(const ModernState& g, const std::vector<MatchGroup>& groups,
uint16_t calendar_entry) {
const auto& mem = g.memory;
if (!groups.empty() || g.manager_teams.size() != 1 || g.manager_teams[0] != no_team() ||
!mem.has(kCalendar + uint32_t(g.season_day()) * 2 + 1) ||
!mem.has(kSavedCompetition + 3) || !mem.has(kCoachActive) ||
!mem.has(kOriginalManagerCount) || !mem.has(kManagerCount) ||
!mem.has(kManagerOrder + 1) || !mem.has(kDeskPosition) || !mem.has(kActiveManager))
return false;
const uint16_t saved_entry = mem.u16(kCalendar + uint32_t(g.season_day()) * 2);
if (saved_entry != calendar_entry || modern::day_competitions(g, saved_entry) != 0x800000 ||
mem.u32(kSavedCompetition) != 0 || mem.u8(kCoachActive) == 0 ||
mem.u8(kManagerCount) != 1 || mem.u8(kOriginalManagerCount) < 1 ||
mem.u8(kOriginalManagerCount) > 4 || mem.u16(kManagerOrder) >= mem.u8(kOriginalManagerCount) ||
mem.u8(kDeskPosition) != 0 || mem.u8(kActiveManager) != 0)
return false;
return true;
}
TurnAdvanceResult fail(TurnDriver& driver, const ModernState& g, const MinuteReport& report,
const char* fallback) {
driver.stage = TurnDriver::Stage::Failed;
TurnAdvanceResult out;
out.kind = TurnDeskKind::Failed;
out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1;
out.date = g.date;
out.revision = driver.revision;
out.reason = report.reason.empty() ? fallback : report.reason;
return out;
}
TurnAudioEvent audio_event(TurnDriver& driver, TurnAudioKind kind) {
// Cue mapping is deliberately absent until a concrete original call site is proven.
return {driver.session_id, driver.next_event_id++, kind, std::nullopt};
}
TurnAdvanceResult desk_result(TurnDriver& driver, const ModernState& g, TurnDeskKind kind,
bool offer_pending = false) {
TurnAdvanceResult out;
out.kind = kind;
out.manager_slot = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1;
out.date = g.date;
out.revision = driver.revision;
out.offer_pending = offer_pending;
return out;
}
bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game,
WatcomRandom& rand, MinuteReport& report,
std::vector<TurnAudioEvent>& events) {
const std::vector<uint8_t> saved_records = g.manager_records;
const std::vector<uint8_t> saved_options = g.manager_options;
MatchdayContext context = matchday_context(g, driver.referees);
turn_step = "kick_off";
modern::kick_off(g, driver.groups, context, rand, game, report,
driver.sportschau_source.intro_after_matchday != 0,
driver.sportschau_source.rated_club_threshold);
if (report.unsupported) return false;
if (driver.sportschau_source.intro_after_matchday != 0 && driver.sportschau.kickoff) {
const auto intro = matchday_intro_view(g, driver.groups);
if (intro) driver.sportschau.kickoff(g, *intro);
}
bool manager_match_played = false;
for (const MatchGroup& group : driver.groups)
for (int m = 0; m < group.matches(); ++m) {
if (group.void_mask() >> m & 1) continue;
const size_t fixture = size_t(m * 2);
if (fixture + 1 < group.fixtures.size() &&
(g.manager_of(group.fixtures[fixture]) >= 0 ||
g.manager_of(group.fixtures[fixture + 1]) >= 0))
manager_match_played = true;
}
// Matchday resolution is synchronous. Emit cues only for fixtures involving a
// human-managed club so background AI schedules do not flood the audio queue.
if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::kickoff_whistle));
MatchEngine engine{g, driver.groups, game, rand, driver.referees};
if (driver.original_sound) {
engine.original_sound = [&driver, &g](uint8_t id) { driver.original_sound(id, g); };
if (manager_match_played) engine.original_sound(3); // EndPhase / ReadButtons, crowd.
}
std::vector<ShowEvent> sportschau_show_events;
if (driver.sportschau.fixture) engine.show = &sportschau_show_events;
engine.month = context.month;
engine.buttons = read_buttons(g);
engine.reality_rules = driver.reality_rules;
engine.live_scene_visible = g.live_scene && driver.reality_rules;
engine.phase_results = driver.phase_results;
if (driver.live_reality) {
engine.live_reality = [&driver, &g](const LiveRealityEvent& event) {
return driver.live_reality(event, driver.groups, g);
};
}
// LiveDeskDisabled is a saved settings byte. It also changes attitude, assistant
// substitutions and RNG consumption, so a background driver must preserve it.
engine.live_desk_disabled = g.memory.has(::bmh::layout::LiveDeskDisabled) && g.memory.u8(::bmh::layout::LiveDeskDisabled) != 0;
engine.alternate_event_roll = driver.alternate_match_event_roll;
engine.match_events_disabled = driver.disable_match_events;
engine.leave_screens = true;
if (driver.live_shootout) {
engine.live_shootout = [&driver, &g](const LiveShootoutEvent& event) {
driver.live_shootout(event, driver.groups, g);
};
}
if (driver.live_booking) {
engine.live_booking = [&driver, &g](const LiveBookingEvent& event) {
driver.live_booking(event, driver.groups, g);
};
}
if (driver.live_set_piece) {
engine.live_set_piece = [&driver, &g](const LiveSetPieceEvent& event) {
driver.live_set_piece(event, driver.groups, g);
};
}
if (driver.live_shot) {
engine.live_shot = [&driver, &g](const LiveShotEvent& event) {
driver.live_shot(event, driver.groups, g);
};
}
if (driver.live_chance) {
engine.live_chance = [&driver, &g](const LiveChanceEvent& event) {
driver.live_chance(event, driver.groups, g);
};
}
if (driver.live_ball) {
engine.live_ball = [&driver, &g](const LiveBallEvent& event) {
driver.live_ball(event, driver.groups, g);
};
}
if (driver.live_event) {
engine.live_event = [&driver, &engine](const LiveMatchEvent& event) {
driver.live_event(event, engine, driver.groups, static_cast<ModernState&>(engine.state));
};
}
std::vector<std::vector<std::array<int, 2>>> previous(driver.groups.size());
for (size_t gi = 0; gi < driver.groups.size(); ++gi) {
const MatchGroup& group = driver.groups[gi];
previous[gi].resize(size_t(group.matches()));
for (int m = 0; m < group.matches(); ++m) {
int home = 0, away = 0;
modern::match_score(group, m, home, away);
previous[gi][size_t(m)] = {home, away};
}
}
bool manager_match_scored = false;
auto collect_goals = [&](int) {
for (size_t gi = 0; gi < driver.groups.size(); ++gi) {
const MatchGroup& group = driver.groups[gi];
for (int m = 0; m < group.matches(); ++m) {
const size_t fixture = size_t(m * 2);
if ((group.void_mask() >> m & 1) || fixture + 1 >= group.fixtures.size() ||
(g.manager_of(group.fixtures[fixture]) < 0 &&
g.manager_of(group.fixtures[fixture + 1]) < 0))
continue;
int home = 0, away = 0;
if (!modern::match_score(group, m, home, away)) continue;
auto& old = previous[gi][size_t(m)];
const int goals = std::max(0, home - old[0]) + std::max(0, away - old[1]);
manager_match_scored = manager_match_scored || goals > 0;
old = {home, away};
}
}
};
auto after_minute = [&](int minute) {
collect_goals(minute);
if (driver.live_minute) driver.live_minute(minute, engine, driver.groups, g);
};
turn_step = "play_matchday";
modern::play_matchday(engine, g, driver.groups, engine.buttons, game, rand, report, after_minute);
if (report.unsupported) return false;
// The app receives the whole synchronous turn at once. One summary goal cue
// per manager matchday is bounded and avoids replaying a stream of missed goals.
if (manager_match_scored) events.push_back(audio_event(driver, TurnAudioKind::goal));
if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::full_time_whistle));
turn_step = "finish_event";
modern::store_group_descriptors(g, driver.groups, true);
modern::finish_event(g, driver.groups, driver.calendar_entry, engine.buttons,
saved_records, saved_options, game, rand, report, driver.season_cup_draw,
&driver.sportschau, &sportschau_show_events,
driver.sportschau_source.intro_after_matchday != 0,
driver.sportschau_source.ratings ? &*driver.sportschau_source.ratings : nullptr);
return !report.unsupported;
}
bool next_event(TurnDriver& driver, ModernState& g, GameRandom& game, WatcomRandom& rand,
MinuteReport& report, bool& offer_pending, bool after_event,
bool first_day_preprocessed = false, bool repeat_event = false) {
for (int day = 0; day < 366 * 5; ++day) {
// DailyInterest enters AdvanceTurn on season day zero even when its
// calendar cell is empty. The prepared first Wednesday is a manager
// desk, not a day to skip while seeking the first scheduled fixture.
const bool opening_desk = first_day_preprocessed && g.season_day() == 0;
// DailyInterest advances DaysIntoSeason before DayStepRest on a quiet day,
// but after DayStepRest when completing an event. Preserve that Source-visible
// context for a nested Bundestrainer re-takeover; the typed date is already one
// day ahead in the latter case.
const uint16_t source_rest_day = uint16_t(
g.date - g.season_start - uint32_t(after_event ? 1 : 0));
turn_step = "day_step_rest";
if (!first_day_preprocessed &&
!modern::day_step_rest(g, game, rand, report, source_rest_day,
driver.transfer_allocator_context)) return false;
// DailyInterest tests for 1 July only after DayStepRest has advanced a day. The
// prepared first day of a new season is not such a step: when 1 July is itself the
// first Wednesday (2037), the season change leaves the date there, and testing it
// again started the season change over and over (endless loop after ten seasons).
const bool day_stepped = !first_day_preprocessed;
first_day_preprocessed = false;
if (day_stepped && modern::is_season_end(g)) {
turn_step = "season_end_day";
modern::season_end_day(g);
// DailyInterest calls AdvanceTurn after the annual awards. DayCompetitions2's
// closing branch supplies FF opponents / competition32 without
// preparing teams, fixtures or cycling manager options. Its old
// descriptors remain available to BuildPoolsCoupon's coupon scan.
if (modern::full_game(g)) { // DailyInterest calls this desk loop only with leagues.
driver.calendar_entry = calendar_day(g, g.season_day());
const uint32_t closing_competitions = modern::day_competitions(g, driver.calendar_entry);
g.memory.set32(kSavedCompetition, closing_competitions == 0x800000 ? 0 : closing_competitions);
modern::draw_matchday_number(g, rand);
modern::shuffle_manager_order(g, game);
driver.manager_position = 0;
driver.national_nomination_desk = false;
turn_step = "enter_closing_desk";
offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave);
if (report.unsupported) return false;
}
driver.stage = TurnDriver::Stage::SeasonEndDesk;
++driver.revision;
return true;
}
turn_step = "stock market";
if (after_event) modern::day_stock_market(g, game);
after_event = false;
const uint16_t entry = calendar_day(g, g.season_day());
if (!(entry & 0x7fff) && !opening_desk) {
turn_step = "plain_day";
modern::plain_day(g, game, rand);
continue;
}
turn_step = "calendar day";
const uint32_t competitions = modern::day_competitions(g, entry);
driver.referees = driver.referee_source; // clear the per-day chosen flags
MatchdayContext context = matchday_context(g, driver.referees);
if (competitions == 0 && !opening_desk) {
turn_step = "empty_event_day";
if (!modern::empty_event_day(g, context, game, rand, report)) return false;
after_event = true;
continue;
}
if (competitions == 0x800000 && !opening_desk) {
// The return means that a human national-coach desk follows, not
// that the calendar step succeeded. The ordinary no-coach case
// still performs the Source national-team preparation and continues.
const bool has_national_coach = modern::national_team_day(g, rand, report);
if (report.unsupported) return false;
const bool enter_national_desk = has_national_coach && driver.enable_national_nomination_desks;
// AdvanceTurn clears the transient competition result before its empty
// setup. Keep the legacy/no-coach behavior byte-identical; the opted-in
// coach path clears it before preparing the real national desk.
if (enter_national_desk) {
if (g.manager_teams.size() != 1 || g.manager_teams[0] != no_team()) {
report.fail("national nomination returned a coach without the one-manager national context");
return false;
}
if (g.memory.has(kSavedCompetition + 3)) g.memory.set32(kSavedCompetition, 0);
context.national_team_day = true;
}
turn_step = "modern::setup_matchday (national)";
const std::vector<MatchGroup> none = modern::setup_matchday(g, 0, context, game, rand, report);
if (report.unsupported) return false;
if (!none.empty()) {
report.fail("national team day unexpectedly prepared match groups");
return false;
}
modern::draw_matchday_number(g, rand);
modern::shuffle_manager_order(g, game);
if (enter_national_desk) {
driver.calendar_entry = entry;
driver.groups = none;
driver.manager_position = 0;
turn_step = "enter_event_desk";
offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave);
if (report.unsupported) return false;
driver.national_nomination_desk = true;
driver.stage = TurnDriver::Stage::MatchdayDesks;
++driver.revision;
return true;
}
modern::event_end(g);
++g.date;
modern::daily_interest(g, rand);
after_event = true;
continue;
}
driver.calendar_entry = entry;
if (!repeat_event) start_event_passes(g, entry);
repeat_event = false;
turn_step = "prepare_event";
driver.groups = modern::prepare_event(g, entry, context, game, rand, report);
if (report.unsupported) return false;
if (!modern::matchday_needs_manager_desks(g, entry, driver.groups)) {
std::vector<TurnAudioEvent> background_events;
if (!run_current_matchday(driver, g, game, rand, report, background_events)) return false;
if (consume_event_pass(driver, g)) {
first_day_preprocessed = true;
repeat_event = true;
continue;
}
++g.date;
modern::daily_interest(g, rand);
after_event = true;
continue;
}
driver.manager_position = 0;
turn_step = "enter_event_desk";
offer_pending = modern::enter_event_desk(g, 0, driver.groups, game, rand, report, true, driver.desk_autosave);
if (report.unsupported) return false;
driver.stage = TurnDriver::Stage::MatchdayDesks;
++driver.revision;
return true;
}
report.fail("turn driver exceeded five seasons without a manager desk");
return false;
}
} // namespace
bool begin_turn_driver(TurnDriver& driver, const ModernState& g, std::vector<MatchGroup> groups,
uint16_t calendar_entry, std::vector<uint8_t> referees,
uint64_t session_id, uint64_t revision, std::string& error) {
if (driver.stage != TurnDriver::Stage::Empty || revision == 0 || session_id == 0) {
error = "turn driver is already active or has invalid identity";
return false;
}
if (g.manager_teams.empty()) {
error = "turn driver needs at least one human manager";
return false;
}
driver.stage = TurnDriver::Stage::MatchdayDesks;
driver.calendar_entry = calendar_entry;
driver.manager_position = g.memory.has(::bmh::layout::DeskPosition) ? int(g.memory.u8(::bmh::layout::DeskPosition)) : 0;
driver.revision = revision;
driver.session_id = session_id;
driver.groups = std::move(groups);
driver.referee_source = std::move(referees);
driver.referees = driver.referee_source;
driver.national_nomination_desk = saved_national_nomination_desk(
g, driver.groups, calendar_entry);
return true;
}
TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, ModernState& g,
const TurnAdvanceRequest& request,
GameRandom& game, WatcomRandom& rand,
MinuteReport& report) {
const int active_manager = g.memory.has(::bmh::layout::ActiveManager) ? int(g.memory.u8(::bmh::layout::ActiveManager)) : -1;
// AdvanceTurn restores the retained club-order owner after every temporary
// national desk, including desks with real fixtures. That owner can be1–3
// although the visible/runtime national manager is0. Qualify the completed
// pending batch below without turning an actual match into a nomination day.
const bool national_handoff = driver.enable_national_nomination_desks &&
(driver.national_nomination_desk ||
(g.manager_teams.size() == 1 && g.manager_teams[0] == no_team() &&
g.memory.has(kCoachActive) && g.memory.u8(kCoachActive) != 0));
if (national_handoff) {
const int original_count = g.memory.has(kOriginalManagerCount)
? int(g.memory.u8(kOriginalManagerCount)) : 0;
const int source_owner = g.memory.has(kManagerOrder + 1)
? int(g.memory.u16(kManagerOrder)) : -1;
const bool completed_pending = g.memory.has(kDeskPosition) &&
g.memory.u8(kDeskPosition) == 1 && active_manager == source_owner &&
original_count >= 1 && original_count <= 4 && source_owner >= 0 &&
source_owner < original_count;
if (!completed_pending) {
TurnAdvanceResult out;
out.kind = TurnDeskKind::Failed;
out.manager_slot = active_manager;
out.date = g.date;
out.revision = driver.revision;
out.reason = "national_nomination_pending_not_completed";
return out;
}
if (driver.stage != TurnDriver::Stage::MatchdayDesks ||
request.manager_slot != 0 || driver.manager_position != 0 ||
request.revision != driver.revision || g.manager_teams.size() != 1 ||
g.manager_teams[0] != no_team() || !g.memory.has(kCoachActive) ||
g.memory.u8(kCoachActive) == 0 || !g.memory.has(kManagerCount) ||
g.memory.u8(kManagerCount) != 1) {
TurnAdvanceResult out;
out.kind = TurnDeskKind::Failed;
out.manager_slot = active_manager;
out.date = g.date;
out.revision = driver.revision;
out.reason = "stale_national_coach_manager_or_revision";
return out;
}
} else if ((driver.stage != TurnDriver::Stage::MatchdayDesks && driver.stage != TurnDriver::Stage::SeasonEndDesk) ||
request.manager_slot != active_manager || request.revision != driver.revision) {
TurnAdvanceResult out;
out.kind = TurnDeskKind::Failed;
out.manager_slot = active_manager;
out.date = g.date;
out.revision = driver.revision;
out.reason = "stale_manager_or_revision";
return out;
}
// Claim the request before any RNG or state mutation. A failure is terminal for this
// cursor, so replaying the same request cannot repeat a partially completed turn.
const auto previous_stage = driver.stage;
driver.stage = TurnDriver::Stage::Failed;
std::vector<TurnAudioEvent> events;
bool offer_pending = false;
try {
if (driver.manager_position + 1 < int(g.manager_teams.size())) {
++driver.manager_position;
const bool prepare_pre_match_offer =
!(driver.loaded_matchday_resume && driver.suppress_remaining_pre_match_offers);
turn_step = "enter_event_desk";
offer_pending = modern::enter_event_desk(g, driver.manager_position, driver.groups,
game, rand, report, prepare_pre_match_offer, driver.desk_autosave);
if (report.unsupported) return fail(driver, g, report, "manager pre-match desk unsupported");
driver.stage = previous_stage;
++driver.revision;
return desk_result(driver, g, previous_stage == TurnDriver::Stage::SeasonEndDesk
? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending);
}
if (previous_stage == TurnDriver::Stage::SeasonEndDesk) {
// Every manager has now left the closing desk. Do not carry the
// loaded desk-resume policy into the annual transition or a new event.
driver.complete_loaded_manager_loop();
// AdvanceTurn's completed manager-desk loop leaves DeskPosition == ManagerCount
// before DailyInterest enters the annual transition. This native byte is
// serialized at modal checkpoints; the next real desk resets it.
if (g.memory.has(::bmh::layout::DeskPosition))
g.memory.set8(::bmh::layout::DeskPosition, g.memory.has(::bmh::layout::ManagerCount)
? g.memory.u8(::bmh::layout::ManagerCount) : uint8_t(g.manager_teams.size()));
const auto outcome = modern::season_transition(g, game, rand, report, driver.season_pause
? std::function<void(const char*)>([&](const char* screen) { driver.season_pause(screen, g); })
: std::function<void(const char*)>{}, driver.season_highscore, driver.season_tax,
driver.season_promotion, driver.season_cup_draw, driver.transfer_allocator_context);
if (report.unsupported || outcome == SeasonTransitionOutcome::Failed)
return fail(driver, g, report, "season transition unsupported");
if (outcome == SeasonTransitionOutcome::CareerComplete) {
driver.stage = TurnDriver::Stage::CareerComplete;
++driver.revision;
return desk_result(driver, g, TurnDeskKind::CareerComplete);
}
driver.stage = TurnDriver::Stage::MatchdayDesks;
// season_end_steps has already performed the calendar days up to the new
// season's first Wednesday; the next loop starts from that prepared date.
if (!next_event(driver, g, game, rand, report, offer_pending, false, true))
return fail(driver, g, report, "season transition could not reach a desk");
auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk
? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending);
out.audio_events = std::move(events);
return out;
}
// The current manager desk loop is complete, so these flags have no further
// desk to govern. Consume them before match simulation and future event setup.
driver.complete_loaded_manager_loop();
if (driver.enable_national_nomination_desks && driver.national_nomination_desk) {
// AdvanceTurn's national nomination event has an empty desk, not a
// matchday: Source skips kick_off/play/finish and advances the event
// calendar directly after the pending cleanup performed by App.
driver.national_nomination_desk = false;
modern::event_end(g);
++g.date;
modern::daily_interest(g, rand);
if (!next_event(driver, g, game, rand, report, offer_pending, true))
return fail(driver, g, report, "national nomination could not advance to next desk");
auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk
? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending);
out.audio_events = std::move(events);
return out;
}
// A legacy caller can bind a genuine saved national desk, but it keeps the
// historic matchday path unless the App explicitly opted into this lifecycle.
driver.national_nomination_desk = false;
const auto result_tournament_name = g.tournament_name;
if (!run_current_matchday(driver, g, game, rand, report, events))
return fail(driver, g, report, "matchday unsupported");
driver.last_results.valid = true;
driver.last_results.date = g.date;
driver.last_results.calendar_entry = driver.calendar_entry;
driver.last_results.matchday = g.memory.has(::bmh::layout::CurrentMatchday) ? g.memory.u16(::bmh::layout::CurrentMatchday) : 0;
driver.last_results.groups = driver.groups;
driver.last_results.tournament_name = result_tournament_name;
const bool repeat = consume_event_pass(driver, g);
if (!repeat) {
++g.date;
modern::daily_interest(g, rand);
}
if (!next_event(driver, g, game, rand, report, offer_pending, !repeat, repeat, repeat))
return fail(driver, g, report, "could not advance to next desk");
auto out = desk_result(driver, g, driver.stage == TurnDriver::Stage::SeasonEndDesk
? TurnDeskKind::SeasonEndDesk : TurnDeskKind::NextDesk, offer_pending);
out.audio_events = std::move(events);
return out;
} catch (const std::exception& ex) {
report.fail(std::string("turn driver exception: ") + ex.what() + " (in " + std::string(turn_step.load()) + ")");
return fail(driver, g, report, "turn driver exception");
}
}
} // namespace bmh::modern
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/turn_driver.hpp"
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "game/match_engine.hpp"
#include "modern/game/desk.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/season.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/transfer_allocator.hpp"
namespace bmh::modern {
// Controller-level sound events carry stable identities. An original cue is optional:
// only attach one when its concrete BMH call site is mapped to a cue by evidence.
// WaitingAtDesk has not claimed the driver: its original request may be retried.
// Read-only-ready copy of the most recently completed human matchday. Kept apart
// from `groups`, which is replaced while seeking the next calendar event.
// Runtime state between a desk's kickoff request and the next desk. The group objects,
// referee table, presentation settings and random generators remain owned by the caller/
// controller for each synchronous advance; only this cursor survives the desk handoff.
// Bind an event already prepared by prepare_event and with its first human desk open.
// No generators are drawn here; the object becomes the only accepted continuation for it.
bool begin_turn_driver(TurnDriver& driver, const ModernState& g, std::vector<MatchGroup> groups,
uint16_t calendar_entry, std::vector<uint8_t> referees,
uint64_t session_id, uint64_t revision, std::string& error);
// Accept the current desk's advance request, show the next manager desk when applicable,
// then play the event in the background and advance through calendar days to the next desk.
// Rejected/stale requests leave state and both random generators untouched.
TurnAdvanceResult advance_to_next_desk(TurnDriver& driver, ModernState& g,
const TurnAdvanceRequest& request,
GameRandom& game, WatcomRandom& rand,
MinuteReport& report);
} // namespace bmh::modern
+395
View File
@@ -0,0 +1,395 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/week.hpp"
#include "modern/game/matchday.hpp"
#include "game/lineup.hpp"
#include "game/schedule.hpp"
#include <algorithm>
namespace bmh::modern {
namespace {
constexpr size_t kManagerRecord = 0xB0C;
int32_t rd32(const std::vector<uint8_t>& v, size_t o) {
return int32_t(uint32_t(v.at(o)) | uint32_t(v.at(o + 1)) << 8 | uint32_t(v.at(o + 2)) << 16 | uint32_t(v.at(o + 3)) << 24);
}
void wr32(std::vector<uint8_t>& v, size_t o, int32_t x) {
for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(uint32_t(x) >> (8 * i));
}
} // namespace
void daily_interest(ModernState& g, WatcomRandom& rand) {
// (DailyInterest before the day step: the training camp visits of today are over)
for (size_t m = 0; m < g.manager_teams.size(); m++) g.manager_records.at(m * kManagerRecord + 0x21f) &= 0x7f;
for (int k = 0; k < 4; k++) {
const size_t rec = size_t(k) * kManagerRecord;
const int32_t balance = rd32(g.manager_records, rec + 0x314);
const int32_t deposit = rd32(g.manager_records, rec + 0x318);
const int32_t credit = rd32(g.manager_records, rec + 0x31c);
int32_t amount = 0; // positive = cost
if (balance < 0) {
if (balance + credit < 0) amount = ((balance + credit) * 18) / -36500;
int32_t used = -credit < balance ? balance : -credit;
amount += (used * 12) / -36500;
wr32(g.manager_records, rec + 0x89c, rd32(g.manager_records, rec + 0x89c) + amount);
modern::book_money(g, k, amount, true);
amount = 0;
} else {
amount = balance / -36500;
}
amount += ((deposit / 10000) * 20000) / -36500;
wr32(g.manager_records, rec + 0x870, rd32(g.manager_records, rec + 0x870) - amount);
modern::book_money(g, k, amount, true);
if (rd32(g.manager_records, rec + 0x314) > 100000000) { // read again after the bookings
int32_t extra = int32_t(rand.range(10000, 20000)) * 1000;
// BookMoney2 with the statistics flag set: counts as an expense (+0x8a0)
wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + extra);
modern::book_money(g, k, extra, true);
}
}
}
} // namespace bmh::modern
namespace bmh::modern {
namespace {
uint16_t rd16w(const std::vector<uint8_t>& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); }
void wr16w(std::vector<uint8_t>& v, size_t o, uint16_t x) {
v.at(o) = uint8_t(x);
v.at(o + 1) = uint8_t(x >> 8);
}
int8_t clamp8(int v, int lo, int hi) { // Int8T on a signed char
int8_t c = int8_t(v);
int s = c < lo ? lo : c;
if (s > hi) s = hi;
return int8_t(s);
}
// Training areas (WeekRuntimeField shift, WeekRuntimeField2 mask): 0 condition, 1 technique (w35c),
// 2-8 the seven skills (w368, 2 bits each).
constexpr uint8_t kAreaShift[9] = {14, 7, 12, 10, 8, 6, 4, 2, 0};
constexpr uint8_t kAreaMask[9] = {127, 127, 3, 3, 3, 3, 3, 3, 3};
constexpr uint8_t kIntensityValue[4] = {0, 80, 100, 120}; // WeekRuntimeField3
constexpr int8_t kFamiliarityStep[4] = {0, -4, 0, 4}; // WeekRuntimeField4
// Attribute: read (write = false) or change an attribute by `delta` within 0..max.
int attribute(Player& p, int area, bool write, int delta, int max) {
uint32_t& word = area < 2 ? p.w35c : p.w368;
const int shift = kAreaShift[area], mask = kAreaMask[area];
int v = int(int32_t(word) >> shift) & mask;
if (!write) return v;
int8_t n = clamp8(int8_t(delta + v), 0, max);
word = (word & ~(uint32_t(mask) << shift)) | uint32_t(int32_t(n)) << shift;
return 0;
}
} // namespace
int weekday_code(uint32_t date) {
int c = int(date % 7) + 2;
if (c > 6) c = int(date % 7) - 5;
return c;
}
void familiarity_decay(ModernState& g, GameRandom& game, WatcomRandom& rand) {
for (size_t k = 0; k < g.manager_teams.size(); k++) {
const int team = g.manager_teams[k];
const SquadRange range = squad_range(team);
for (size_t s = range.first; s < range.first + range.count; s++) {
const int player = g.squad_slots.at(s) & 0x0FFF;
if (player == 0xFFF) continue;
const Player& p = g.players.at(player);
uint8_t& used = g.tactics.at(k * 0x840 + (s - range.first) * 0x58 + 0xf);
int r = rand.range(0, 2);
uint8_t rate = uint8_t(r + 4);
if (p.condition() < p.technique()) rate = uint8_t(r + 6);
if (unsigned(rand.range(12, 16)) < ((p.w364 >> 21) & 0x1F)) rate = uint8_t(rate + 2);
int16_t cap = int16_t(8 - int16_t(rd16w(g.manager_records, k * 0xB0C + 0x8b0)) / 0x113);
if (team == no_team()) cap = 8;
if (cap < int16_t(rate)) rate = uint8_t(cap);
// the player pool of a manager without a club: a low value is drawn afresh
// (game generator)
if (team == no_team() && used < 0x1e) used = uint8_t(game.range(0x18, 0x30));
used = uint8_t(used - used / rate);
}
}
}
void train_squad(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand) {
const size_t rec = size_t(manager) * 0xB0C;
uint8_t table[4][9];
for (int pos = 0; pos < 4; pos++)
for (int a = 0; a < 9; a++)
table[pos][a] = uint8_t(kIntensityValue[int8_t(g.manager_records.at(rec + 0xc5 + pos))] +
kIntensityValue[int8_t(g.manager_records.at(rec + 0xc9 + a))]);
const int team = int16_t(rd16w(g.manager_records, rec + 0x290));
const SquadRange range = squad_range(team);
const int league = team_league(team);
const int16_t quality = int16_t(rd16w(g.manager_records, rec + 0x8ac));
uint8_t max_value[9] = {99, 99, 3, 3, 3, 3, 3, 3, 3}; // WeekRuntimeField5
for (size_t s = range.first; s < range.first + range.count; s++) {
const uint16_t entry = g.squad_slots.at(s);
if (entry == 0x0FFF) continue;
const int player = entry & 0x0FFF;
Player& p = g.players.at(player);
const size_t board = size_t(manager) * 0x840 + (s - range.first) * 0x58;
const uint32_t w364 = p.w364;
const int games = int32_t(w364) >> 26;
const int pos = int(w364 & 3);
int8_t used_delta = 0; // local_48
int8_t trend = 0; // local_54
const uint8_t used = g.tactics.at(board + 0xf);
const int intensity = g.tactics.at(board + 0xa) & 3;
int second = 10; // local_4c
int focus = (g.tactics.at(board + 0xa) >> 2) + 1; // local_58
if (attribute(p, focus < 9 ? focus : 8, false, 0, 0) < 3) {
do {
second = game.range(2, 8);
} while (second == focus);
} else {
focus = 10;
}
for (int a = 0; a < 9; a++) {
// register EDI of the original: a value from an earlier branch may survive
uint32_t edi = uint32_t(pos * 9 + a);
int ebx = table[pos][a] + quality / 110 - 5;
if (rand.range(0, 4) == 0) used_delta = int8_t(used_delta + int8_t(g.manager_records.at(rec + 0xc5 + a)) * 2 - 4);
ebx = (int(uint16_t(ebx)) + kIntensityValue[intensity]) / 3;
uint8_t rest = uint8_t(0xa0 - used);
if (rest > 100) rest = 100;
ebx = (int(uint16_t(ebx)) + rest) / 2 - 0x50;
if (focus == a) ebx += 8;
if (second == a) ebx -= 8;
int sign;
if (uint16_t(ebx) < 20) {
sign = -1;
ebx = 20 - ebx;
} else {
sign = 1;
ebx -= 20;
}
// OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus.
// FocusAreaGetsAtLeastStrengthBelow (supported rule profile): the focus area gets at least strength 5 below
uint32_t reg = uint16_t(ebx);
if (focus == a) reg |= 0x10000;
if (sign == 1) {
edi = 3;
if (g.league_rounds.at(league) / 3 > games) {
reg = 0; // no match practice yet: no progress
} else {
edi = (w364 >> 21) & 0x1F; // age - 16
if (rand.range(13, 40) < int(edi)) reg = 0; // older players progress less
}
}
if (a > 1) {
edi = uint32_t(a);
if (table[pos][a] < 0x6e && game.range(0, 50) == 0) max_value[a] = 2;
}
if (game.range(0, 8) == 0) {
// OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus.
// Int9 (supported rule profile)
uint32_t dx = reg & 0xFFFF;
if ((reg & 0x10000) && dx < 5) dx = 5;
edi = dx * 15;
reg &= 0xFFFF;
if (int(edi) > game.range(0, 0x96)) attribute(p, a, true, sign, int8_t(max_value[a]));
}
(void)edi;
if (a > 1) max_value[a] = 3;
if (reg & 0xFFFF) trend = int8_t(trend + sign);
}
used_delta = clamp8(used_delta, -15, 15);
g.tactics.at(board + 0xf) = uint8_t(g.tactics.at(board + 0xf) + kFamiliarityStep[intensity] + used_delta);
trend = int8_t(trend / int8_t(game.range(1, 4)));
trend = clamp8(trend, -1, 1);
g.tactics.at(board + 0xe) = uint8_t((g.tactics.at(board + 0xe) & 0x3F) + uint8_t((trend + 1) << 6));
g.tactics.at(board + 0xf) = uint8_t(clamp8(int8_t(g.tactics.at(board + 0xf)), 0x18, 99));
}
// the assistant's training plan (training automatic on)
if (g.manager_options.at(size_t(manager) * 5 + 4) & 1) modern::auto_training(g, manager);
}
void auto_training(ModernState& g, int manager) {
uint8_t& option = g.manager_options.at(size_t(manager) * 5 + 4); // CareerSessionRuntimeField3
if (!(option & 0x80)) option = 0x9f;
const uint8_t flags = (option & 1) ? option : 0; // local_14
const size_t rec = size_t(manager) * 0xB0C;
const int team = int16_t(rd16w(g.manager_records, rec + 0x290));
uint8_t plan[13];
for (int i = 0; i < 13; i++) plan[i] = g.manager_records.at(rec + 0xc5 + size_t(i));
// QuoteNationalFriendlyMatch for keepers, defence, midfield, attack and the whole team (WeekRuntimeField6)
static constexpr uint16_t kPositions[5] = {0x1f, 0x2f, 0x4f, 0x8f, 0xff};
int value[5];
for (int i = 0; i < 5; i++) value[i] = team_average(g, team, kPositions[i]).value;
int16_t order[7];
uint32_t key[7];
if (flags & 2) {
for (int i = 0; i < 4; i++) {
plan[i] = 2;
order[i] = int16_t(i);
key[i] = uint32_t((value[i] * 100) / value[4]);
}
quicksort_by_key(order, key, 4, true); // Games ascending
for (int i = 0; i < 2; i++)
if (key[i] < 0x62) plan[order[i]] = 3, plan[order[3 - i]] = 1;
}
const int condition = team_average(g, team, 0xf1).value, technique = team_average(g, team, 0xf2).value;
if (flags & 4) {
plan[4] = 2, plan[5] = 2;
if (condition - 1 > technique) plan[4] = 1, plan[5] = 3;
if (technique - 1 > condition) plan[4] = 3, plan[5] = 1;
}
for (int i = 0; i < 7; i++) {
if (flags & 4) plan[6 + i] = 2;
order[i] = int16_t(i);
key[i] = 0x32;
}
const SquadRange range = squad_range(team);
for (size_t s = range.first; s < range.first + range.count; s++) {
const uint16_t v = g.squad_slots.at(s);
if (v == kEmptySlot) continue;
const Player& p = g.players.at(v & 0x0FFF);
uint8_t* board = &g.tactics.at(size_t(manager) * 0x840 + (s - range.first) * 0x58);
if (flags & 8) {
uint8_t intensity = 2;
if (board[0xf] < 0x1f) intensity = 3;
if (board[0xf] > 0x3c) intensity = 1;
board[10] = uint8_t((board[10] & 0xfc) | intensity);
}
// the skills 6..0 (w368 bits 12..0, Attribute with WeekRuntimeField/WeekRuntimeField2, index 2..8):
// + 1 for a player at 0 (WeekRuntimeField7), - 1 at 3 (WeekRuntimeField8)
bool at_top[8] = {}; // OpenBMH deviates from the original: uses the enhanced training rules: focus strength is at least five below its target, and completed skills rotate to another focus.
// by index k = 7 - skill (the supported rule profile patch's bit pairs)
for (int i = 0; i < 7; i++) {
const int skill = 6 - i;
const int level = int(p.w368 >> (2 * skill) & 3);
at_top[i + 1] = level == 3;
if (level == 0) key[i]++;
if (level == 3) key[i]--;
}
if (flags & 0x10) {
// Position: the skill to train (+0x0a bits 2-4) is kept unless it is at 3;
// else the first of the position's order (nibbles of Week_AutoTraining_ExecutableField3, Week_AutoTraining_ExecutableField4, Week_AutoTraining_ExecutableField2,
// Week_AutoTraining_ExecutableField, low first, each 2 * k) that is not at 3 yet
static constexpr uint32_t kOrder[4] = {::bmh::layout::Week_AutoTraining_ExecutableField3, ::bmh::layout::Week_AutoTraining_ExecutableField4, ::bmh::layout::Week_AutoTraining_ExecutableField2, ::bmh::layout::Week_AutoTraining_ExecutableField};
const int current = (board[10] >> 2) & 7;
if (current == 0 || at_top[current]) {
for (uint32_t list = kOrder[p.position()]; (list & 0xf) != 0; list >>= 4) {
const int k = int(list & 0xf) / 2;
if (!at_top[k]) {
board[10] = uint8_t((board[10] & 3) | (k << 2));
break;
}
}
}
}
}
quicksort_by_key(order, key, 7); // Games descending
if (flags & 4)
for (int i = 0; i < 3; i++)
if (key[i] > 0x34) plan[6 + order[i]] = 3, plan[6 + order[6 - i]] = 1;
for (int i = 0; i < 13; i++) g.manager_records.at(rec + 0xc5 + size_t(i)) = plan[i];
}
void stock_market(ModernState& g, GameRandom& game) {
auto u32 = [&](size_t o) {
return uint32_t(g.stocks.at(o) | g.stocks.at(o + 1) << 8 | g.stocks.at(o + 2) << 16 | uint32_t(g.stocks.at(o + 3)) << 24);
};
auto w32 = [&](size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) g.stocks.at(o + i) = uint8_t(x >> (8 * i));
};
for (int k = 0; k < 12; k++) w32(size_t(k) * 0x5c, u32(size_t(k) * 0x5c) + u32(size_t(k) * 0x5c) * 3 / 10000);
for (int k = 0; k < 12; k++) {
const size_t s = size_t(k) * 0x5c;
const uint32_t base = u32(s) / 300;
int v = rd16w(g.stocks, s + 0x4e) / 3 + (g.stocks.at(s + 0x58) - 1);
if (v < 10) v = 10;
uint8_t& trend = g.stocks.at(s + 0x58);
uint8_t& left = g.stocks.at(s + 0x59);
if (left != 0) left--;
if (left == 0) {
trend = uint8_t(game.range(0, 1) * 2);
left = uint8_t(game.range(2, (trend != 0) + 8));
}
if (game.range(0, 400 - k * 25) == 0) {
int dir = game.range(0, 1);
v += game.range(v / 5, v / 2) * (dir * 2 - 1);
if (game.range(0, 3) != 0) {
int d2 = game.range(0, 1);
w32(s, uint32_t(v * 300 + (d2 * 2 - 1) * 3000));
}
}
if (game.range(0, 0x16 - k) == 0) {
int dir = game.range(0, 1);
v += game.range(2, 10) * (dir * 2 - 1);
if (game.range(0, 3) == 0) {
int d2 = game.range(0, 1);
int m = game.range(2, 10);
w32(s, uint32_t(int32_t(u32(s)) + (d2 * 2 - 1) * m * 300));
}
}
if (game.range(0, 0x5a) == 0 && (v + 0x14 < int(base) || int(base) < v - 0x14)) {
int dir = game.range(0, 1);
int m = game.range(2, 10);
v = (dir * 2 - 1) * m + int(base);
}
if (game.range(0, 1) != 0) v += game.range(0, 2) - 1;
if (int(base) < v) {
if (trend == 2) v--;
} else if (game.range(0, 1) != 0) {
if (trend == 2) v--;
}
if (v < int(base)) {
if (trend == 0) v++;
} else if (game.range(0, 1) != 0) {
if (trend == 0) v++;
}
std::copy(g.stocks.begin() + s + 0x16, g.stocks.begin() + s + 0x16 + 0x3a, g.stocks.begin() + s + 0x14);
if (v < 10) {
v = 10;
w32(s, 3000);
}
if (v > 2000) {
v = 1000;
w32(s, 300000);
for (int i = 0; i < 4; i++) wr16w(g.stocks, s + 0x50 + i * 2, uint16_t(rd16w(g.stocks, s + 0x50 + i * 2) << 1));
}
wr16w(g.stocks, s + 0x4e, uint16_t(v * 3));
}
}
} // namespace bmh::modern
namespace bmh::modern {
int month_code(uint32_t date) {
// DeskState_DeskDate_RuntimeField: days per month (index 1-12; February 29 in leap years)
uint8_t days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int leap = 3; // sVar4: 4 = the current year is a leap year
while (date > uint32_t((leap == 4 ? 1 : 0) + 0x16c)) {
if (leap == 4) {
leap = 0;
date--;
}
date -= 0x16d;
leap++;
}
days[2] = uint8_t((leap == 4 ? 1 : 0) + 0x1c);
int month = 7;
while (date > days[month]) {
date -= days[month];
month = month == 12 ? 1 : month + 1;
}
if (date + 1 > days[month]) month = month == 12 ? 1 : month + 1;
return month;
}
} // namespace bmh::modern
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/week.hpp"
// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum.
// Between the matchdays: the day processing (BMH.exe V2.24 + supported rule profile patch).
//
// "Weiter" (DailyInterest) handles the event of the current day (AdvanceTurn, e.g. a
// matchday) and then advances day by day (DaysIntoSeason = day of the season, CalendarDay =
// day counter) until the calendar (block CompetitionCalendar) has the next event. Every day runs
// DayStepRest:
// - date + 1, DailyInterest2(1): interest on every human manager's account
// - training and weekly processing on the Source weekday boundary
// - month_change and the national coach's temporary club handback
// day_step_rest in turn.cpp owns those steps; DailyInterest3 advances shares.
#include <cstdint>
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// DailyInterest2(1): daily interest for the four manager slots. Balance (record +0x314)
// earns 1 % a year, the fixed deposit (+0x318) 2 %; an overdraft costs 12 % a year, beyond
// the credit line (+0x31c) 18 % (booked to +0x89c). Income goes to +0x870. A balance over
// 100 million triggers a random extra booking (WatcomRandom 10000-20000 thousand).
// Every day step starts with it, so it also does what DailyInterest does right before the day
// step: bit 7 of record +0x21f (a training camp visit booked today, BookTrainingCamp) is
// cleared for every manager.
void daily_interest(ModernState& g, WatcomRandom& rand);
} // namespace bmh::modern
namespace bmh::modern {
// DeskDate2 (weekday part): CareerSession_PairingsRuntimeDraw_ExecutableField6 of a day counter.
int weekday_code(uint32_t date);
// FamiliarityDecay (training days): the players of human managers slowly forget their places
// on the tactics board (slot byte 0x0f), faster when condition < technique and when older.
void familiarity_decay(ModernState& g, GameRandom& game, WatcomRandom& rand);
// TrainSquad: training of one human manager's squad (on training days). At the end, with
// the training automatic on (option byte 4 bit 0, CareerSessionRuntimeField3), auto_training.
void train_squad(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand);
// OpenBMH deviates from the original: uses the enhanced assistant-training rules, retaining the selected skill until it reaches its maximum.
// Initialize (+ the supported rule profile patch Position / WeekOperation): the assistant's training
// plan. Option byte 4 (CareerSessionRuntimeField3) holds what he decides - without bit 7 it becomes 0x9f
// (everything), without bit 0 nothing. The plan (record +0xc5, 13 bytes, 1 light 2 normal
// 3 hard) starts from the manager's own:
// bit 1, bytes 0-3: the team value (QuoteNationalFriendlyMatch 0x1f/0x2f/0x4f/0x8f) of keepers,
// defence, midfield, attack in percent of the whole team (0xff); the two weakest
// below 98 % train hard, the two strongest then light - sorted ascending,
// bit 2, bytes 4-5: condition (0xf1) against technique (0xf2): the weaker one hard when
// they differ by more than one,
// bit 2, bytes 6-12: the skills 6..0 of w368: 50 + players at 0 - players at 3, sorted
// descending; the three most needed (over 52) hard, their opposite numbers light.
// Per player of the squad on the tactics board:
// bit 3, +0x0a bits 0-1: the intensity after the familiarity +0x0f (below 31 hard, above
// 60 light),
// bit 4, +0x0a bits 2-4: the skill to train (supported rule profile): kept unless it is at 3 already,
// else the first not yet at 3 in the order of the position (keeper 7,6,3,4,5;
// defence 3,6,4,7,5; midfield 4,6,5,7,3; attack 5,6,4,7,3 - index k = skill 7 - k).
void auto_training(ModernState& g, int manager);
// DailyInterest3: the daily moves of the 12 shares (block StockExchange).
void stock_market(ModernState& g, GameRandom& game);
} // namespace bmh::modern
namespace bmh::modern {
// DeskDate2 (month part): CareerSession_PairingsRuntimeDraw_ExecutableField5 (1-12) of a day counter. Day 0 is in July; the
// year has 365 days, every fourth one 366 (February 29).
int month_code(uint32_t date);
} // namespace bmh::modern
File diff suppressed because it is too large. Load diff
+118
View File
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/weekly.hpp"
// OpenBMH deviates from the original: uses the supported weekly processing and transfer rule profile.
// The weekly processing (DayStepRest3, BMH.exe V2.24 + supported rule profile patch).
//
// DayStepRest runs it on the day after a training day when that day has weekday code 3
// (in games with the full economy, CompetitionSelection bit 0). In order:
// 1. per human manager: offers and incidents (Bool), the ageing of the club's
// facilities (FacilityDamage) and random damage to them (SeasonTicketCompensation), each followed
// by the season ticket compensation (Void3); every third week new advertising
// offers (TransferListCountdown2)
// 2. the transfer list (TransferListCountdown(0)): the days left of every listed player count
// down; at 0 the highest-rated eligible bid wins unless a human-seller selector is set
// 3. new bids for listed players (TransferBid)
// 4. every player in a squad: injuries in training, players out (w35c bits 27-31) come
// back or retire
// 5. per human manager: debts, the training camp bill, player bonuses, the weekly
// statistics (FacilityRating)
// Messages to the managers (PostMessage / SystemIdentity) are not produced; dialogs that
// wait for a decision of the player are reported as unsupported.
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "modern/game/modern_state.hpp"
#include "game/transfer_allocator.hpp"
#include "game/human_buyer_sale.hpp"
#include "game/pending_offer.hpp"
#include "game/transfer_bid.hpp"
#include "game/transfer_offer_view.hpp"
#include <array>
#include <cstdint>
#include <functional>
namespace bmh::modern {
// Projects the current live rows without mutation or RNG. The selector caller
// performs the Source-ranked selection and ProjectTransferOfferList post-selection check.
TransferOfferListView project_transfer_offer_list(const ModernState& g, int list_entry);
void weekly_processing(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// The single steps, public for tests.
void manager_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report); // Bool
void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report); // FacilityDamage
void facility_damage(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand); // SeasonTicketCompensation
void season_ticket_compensation(ModernState& g, int manager); // Void3
// Source-visible compensation path: the notice receives the state after the
// usable-capacity calculation, but before the forced/statistical money booking.
void season_ticket_compensation_source(ModernState& g, int manager,
const SeasonTicketCompensationNoticeHook& notice = {});
void advertising_offers(ModernState& g, int manager, WatcomRandom& rand, MinuteReport& report); // TransferListCountdown2
// TransferListCountdown(all): the days left of every listed player count down; at 0 the best bid wins
// (with `all`, at the season end, every list is settled at once)
void transfer_list_countdown(ModernState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report, bool all = false,
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// TransferBid(slot, list entry, 0, -1): a new bid of some club for the player in the
// absolute squad slot (a listed player), or with list_entry 0 a move of the player to a
// club that wants him.
void transfer_bid(ModernState& g, int slot, uint32_t list_entry, bool high, int months, GameRandom& game,
WatcomRandom& rand, MinuteReport& report);
void weekly_statistics(ModernState& g, int manager); // FacilityRating
// FacilityRating2(manager, with_rand, &second): rating of a human club's stadium facilities
// (about 24-100). *second receives the covered share of the stands in percent. With `rand`
// (the attendance calculation) every stand under construction costs 10-12 % of the
// facility sum, drawn per stand.
int facility_rating(ModernState& g, int manager, int* second, WatcomRandom* rand = nullptr);
// Squad helpers shared with the month change (month.cpp):
// Nationality: nationality of a player (w368 bits 27-31, +32 with the flag in *PlayerBonuses).
int nationality(const ModernState& g, int player);
// SquadCount(team, flags): players of a club (bit 1: the injured too; bit 0: plus the
// players bought for later, table Career_RemoveJoinLoans_RuntimeField).
int squad_count(const ModernState& g, int team, int flags);
// SlotTeam: club of an absolute squad slot, -1 for the transfer pool.
int slot_team(int slot);
// Int2(team, 100) after a transfer (only clubs with a squad).
void lineup_after_transfer(ModernState& g, int team);
// ReleasePlayer(seller, player): the player leaves the club (0xFFF: the pool).
bool remove_from_seller(ModernState& g, int seller, int player, MinuteReport& report);
// Finalize a high-confidence manager offer immediately after the seller/player accepts it.
bool accept_transfer_bid_immediately(ModernState& g, int list_entry, int bid, WatcomRandom& rand,
MinuteReport& report,
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
} // namespace bmh::modern
namespace bmh::modern {
// PreMatchOffer, before a human manager's matchday: now and then a club makes an offer for
// one of his players (1 in 71 - manager rating / 50).
// Returns whether an offer was shown (its message box waits for a click before the desk).
bool pre_match_offer(ModernState& g, int manager, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ClubAttraction(team, 0): how attractive a club is for advertisers (0-100): its European
// campaign, its league and table position (weekly.cpp).
int club_attraction(const ModernState& g, int team);
// Modern versions of functions that transfer_bid.hpp, human_buyer_sale.hpp and
// pending_offer.hpp declare for Classic; all are implemented in weekly.cpp.
TransferBidRating rate_transfer_bid_source(ModernState&, const TransferBidRatingRequest&,
WatcomRandom&, MinuteReport&);
HumanBuyerSaleResult settle_human_buyer_sale(ModernState&, const HumanBuyerSaleRequest&,
const HumanBuyerSaleHooks&, WatcomRandom&, MinuteReport&);
PendingOfferResult process_player_card_pending_offers(ModernState& g,
const ClubPlayerDetailSelection& selection, GameRandom& game, WatcomRandom& rand,
const PendingOfferHooks& hooks, MinuteReport& report);
PendingOfferResult process_natural_pending_offers_after_desk(ModernState& g,
const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand,
const PendingOfferHooks& hooks, MinuteReport& report);
PendingOfferResult process_national_nomination_pending_after_desk(ModernState& g,
const PendingOfferDeskRequest& request, GameRandom& game, WatcomRandom& rand,
const PendingOfferHooks& hooks, MinuteReport& report);
} // namespace bmh::modern