Files
WT-Offline/packages/local-service/src/local-service.ts
T
N0VAN0M4LY 7c27d09f78 fix(battle): calculate LocalMP rewards in the local service
The LocalMP host has no battle server, and the previous bridge filled the
gap by computing money in the client: the native ledger wrote invented
amounts into SessionStatsNet, the spawn patch derived reward rates from
warpoints.blk, and the settlement patch summed and rescaled the result.
Rewards came out as zero or several orders of magnitude too high.

Now the client reports facts and the local service prices them.

Native (wto_ws.dll):
- local_mp_ledger.c is removed together with its SessionStatsNet
  offsets and four signatures (43 -> 39).
- local_mp_awards.c raises the HUD script event wtoLocalMpExpEvent for
  every combat event of the local player (event code, victim expClass
  and name, player or AI victim, friendly, naval damage). The DataBlock
  helpers and the HUD event queue are resolved from call sites inside
  GameSaveData::addScoreMessage, which already has a signature.

GUI patches:
- record-local-battle-awards records events and lives in nestdb and
  raises the stock InBattleReward banner from launch-time parameters.
- report-local-battle-settlement sends only facts and rebuilds the
  debriefing from the settled table; failures show the stock error box.
- use-settled-debriefing-stats makes gatherDebriefingResult read that
  table instead of the empty stat_get_exp().
- pass-spawn-modifications-blk no longer computes economy factors.

Local service:
- battle-economy dataset reads every reward factor from wpcost.blk,
  warpoints.blk and rank.blk; tuning/battle-economy.jsonc holds the
  mission score per event with its source (official values where
  published, otherwise marked).
- battle-economy.ts is the single pricing function, shared by the
  banner parameters and the settlement; battle-rewards.ts adds battle
  time, timed award, win/defeat bonus, activity, premium account,
  talisman, skill bonus and free research points; the debriefing table
  has the stat_get_exp() layout and travels in EULT_SESSION_RESULT.
- Crews earn skill points from the battle's research points.
- A battle left before it ends counts as a defeat.

Verified: npm run typecheck, check-gui (35 patches), check-patches,
check-offsets, native build. Not yet run in game.
2026-11-28 04:42:27 +08:00

182 lines
8.7 KiB
TypeScript

/**
* Assemble the local service: data layer, save layer, rules, protocol-layer services,
* and the single loopback listening port.
*/
import type { Server } from 'node:net';
import { AccountStore } from './accounts/account-store.ts';
import { BattleEconomy } from './battle/battle-economy.ts';
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
import { BattleSessionStore } from './battle/battle-session-store.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { ClanStore } from './clans/clan-store.ts';
import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { clanEconomy } from './game-data/datasets/clan-economy.ts';
import { crewSkillData } from './game-data/datasets/crew-skills.ts';
import { DatasetCache } from './game-data/datasets/dataset-cache.ts';
import { decalTextures } from './game-data/datasets/decal-textures.ts';
import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts';
import { externalItemSources } from './game-data/datasets/external-item-sources.ts';
import { itemCatalogue } from './game-data/datasets/item-catalogue.ts';
import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { storeBundles } from './game-data/datasets/store-bundles.ts';
import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts';
import { unitNames } from './game-data/datasets/unit-names.ts';
import { unlockPrices } from './game-data/datasets/unlock-prices.ts';
import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts';
import { webIcons } from './game-data/datasets/web-icons.ts';
import { GameFiles } from './game-data/game-files.ts';
import { GameModes } from './game-modes/game-modes.ts';
import { InventoryService } from './inventory/inventory-service.ts';
import { InventoryCatalogue } from './inventory/itemdef-catalogue.ts';
import { MarketplaceService } from './inventory/marketplace-service.ts';
import { TrophyCatalogue } from './inventory/trophy-catalogue.ts';
import { ItemCatalogue } from './items/item-catalogue.ts';
import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts';
import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './server/port-listener.ts';
import { Router } from './server/router.ts';
import { loadOrCreateCredentials } from './server/tls/tls-certificate.ts';
import { StoreCatalogue } from './store/store-catalogue.ts';
import { StoreService } from './store/store-service.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
import { loadTuning, type Tuning } from './tuning/tuning.ts';
import { UnlockShop } from './unlocks/unlock-purchase.ts';
import { GameArtwork } from './web-ui/game-artwork.ts';
import { WebUiService } from './web-ui/web-ui-service.ts';
export interface LocalServiceOptions {
/** The player's game folder; its data packs are read, never written. */
readonly gameFolder: string;
/** Accounts, saves and logs. */
readonly dataFolder: string;
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
readonly report?: (line: string) => void;
}
export const LOOPBACK = '127.0.0.1';
export interface RunningLocalService {
readonly logFolder: string;
close(): Promise<void>;
}
export async function startLocalService(options: LocalServiceOptions): Promise<RunningLocalService> {
const report = options.report ?? (() => {});
const gameFiles = new GameFiles(options.gameFolder);
// Static data and stores first, before the port opens.
const datasets = new DatasetCache(options.dataFolder, gameFiles, report);
const gameModes = new GameModes(datasets.load(multiplayerMissions), datasets.load(shopCountries), report);
const accounts = new AccountStore(options.dataFolder);
const tuning = loadTuning(options.dataFolder, report);
const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const decals = datasets.load(decalTextures);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
const storeProducts = catalogues.store.allProducts();
const artwork = new GameArtwork(options.gameFolder, {
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
groups: storeProducts.flatMap((product) => product.artworkGroup ? [product.artworkGroup] : []),
listings: catalogues.inventory.marketplaceListings(),
}, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
gameFiles.releasePacks();
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
{ silverLions: tuning.battle.rewardMultiplierSilverLions, researchPoints: tuning.battle.rewardMultiplierResearchPoints },
new Set(vehicles.filter((vehicle) => vehicle.goldenEagles > 0 || vehicle.premiumPack).map((vehicle) => vehicle.name)),
);
const router = new Router([
webUi,
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
new InventoryService(accounts, profiles, catalogues.inventory),
new LoginService(accounts),
new CharService(actionTable({
profiles,
accounts,
research,
equipment,
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, economy },
notifyInventoryChanged,
})),
new DownloadableContentService(decals, options.gameFolder),
]);
const log = new TrafficLog(options.dataFolder);
const listener = createPortListener(
router,
matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
}),
log,
loadOrCreateCredentials(options.dataFolder),
);
matching = listener.matching;
await listen(listener.server, options.port);
return {
logFolder: log.folder,
close: () => new Promise((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
}),
};
}
function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) {
const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)),
unlocks: new UnlockShop(datasets.load(unlockPrices)),
items: new ItemCatalogue(classicItemDefs, tuning.limits.itemPiecesPerPurchase),
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
clanEconomy: datasets.load(clanEconomy),
};
}
function listen(server: Server, port: number): Promise<void> {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, LOOPBACK, () => {
server.off('error', reject);
resolve();
});
});
}