diff --git a/apps/server/src/battle/battle-settlement.ts b/apps/server/src/battle/battle-settlement.ts index dd99412..258d490 100644 --- a/apps/server/src/battle/battle-settlement.ts +++ b/apps/server/src/battle/battle-settlement.ts @@ -53,6 +53,8 @@ export interface BattleSettlementDeps { readonly streaks: BattleStreaks; readonly items: ItemCatalogue; readonly repair: RepairRules; + /** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */ + readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined; } const REPAIR_MODE: Readonly> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' }; @@ -87,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul); } const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); - const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), { + const vehicleRps = rewards.vehicles.map(vehicleRpOf); + const research = investBattleRp(profile, vehicleRps, { country: session.country, requiredClass: session.requiredClass, difficulty, nowUnixSec: log.timeSec, }, deps); + const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0); + if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec); recordBoosterUses(profile, boosters.uses, log); const wager = activeWager(profile, deps.items); const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, { diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index c99ab72..0be7ecb 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -13,6 +13,7 @@ import type { BattleEconomy } from '../../battle/battle-economy.ts'; import type { BattleStreaks } from '../../battle/battle-streaks.ts'; import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts'; import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; import type { ItemCatalogue } from '../../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; @@ -41,6 +42,7 @@ export interface FinishBattleContext { readonly crew: CrewSkillCatalogue; readonly items: ItemCatalogue; readonly repair: RepairRules; + readonly clans?: { readonly store: ClanStore } | undefined; } export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { @@ -67,7 +69,15 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio // The result log and expenses are written together. A retry can arrive after the profile // was saved but before the session was marked settled. if (hasBattleResultLog(profile, session.roomId)) return false; - settleBattle(profile, report, session, settlementDeps); + settleBattle(profile, report, session, { + ...settlementDeps, + onBattleRpEarned: ctx.clans + ? (baseVehicleRp, nowSec) => { + ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec); + ctx.clans!.store.syncProfile(profile, account, nowSec); + } + : undefined, + }); battle.onAfterSettle?.({ userId: account.userId, roomId: session.sessionId, diff --git a/apps/server/src/clans/clan-blk.ts b/apps/server/src/clans/clan-blk.ts index aa78a01..c79e100 100644 --- a/apps/server/src/clans/clan-blk.ts +++ b/apps/server/src/clans/clan-blk.ts @@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray todayDay ? candidateNextDay : todayDay + rewardPeriodDays; + const nextRewardSec = nextRewardDay * 86400; return { name: '', params: [ @@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat int('rewardPeriodDays', rewardPeriodDays), bool('expRewardEnabled', true), int('historyDepth', historyDepthDays), - int('nextRewardDayId', todayDay + rewardPeriodDays), + int64('nextRewardDayId', BigInt(nextRewardSec)), ], blocks: [ buildAstatBlock(clan, tuning), @@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] { function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock { const periods = member.periods.length > 0 ? member.periods - : [{ day: todayDay, activity: member.curActivity, exp: 20000 }]; + : (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []); return { name: member.uid, @@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam { return { name, value: { type: 'int', value: Math.trunc(value) } }; } +function int64(name: string, value: bigint): BlkParam { + return { name, value: { type: 'int64', value } }; +} + function bool(name: string, value: boolean): BlkParam { return { name, value: { type: 'bool', value } }; } diff --git a/apps/server/src/clans/clan-membership.ts b/apps/server/src/clans/clan-membership.ts index 0abd231..287cdc6 100644 --- a/apps/server/src/clans/clan-membership.ts +++ b/apps/server/src/clans/clan-membership.ts @@ -54,13 +54,15 @@ export function addMemberToClan( ): void { if (clan.members.some((m) => m.uid === uid)) return; const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning); + const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity); + const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0); clan.members.push({ uid, nick, role, joinDateSec: nowSec, - curActivity: tuning.activity.maxPerPeriod, - totalActivity: periods.reduce((s, p) => s + p.activity, 0), + curActivity, + totalActivity: periods.length > 0 ? periodActivitySum : curActivity, earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), ratingArc: tuning.playerRating.joiner.arc, ratingHist: tuning.playerRating.joiner.hist, diff --git a/apps/server/src/clans/clan-season.ts b/apps/server/src/clans/clan-season.ts new file mode 100644 index 0000000..113079b --- /dev/null +++ b/apps/server/src/clans/clan-season.ts @@ -0,0 +1,75 @@ +/** + * Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk` + * (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May, + * Jul, Sep, and Nov at 00:00:00 UTC. + * + * Wire contract verified in stock `aces.exe` (2.61.0.58): + * - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level + * profile parameters on every profile-returning char transaction: + * - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay` + * - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay` + * - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber` + * - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear` + * - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim. + * - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using + * `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1` + * (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the + * end time with `time.buildDateTimeStr(info.rewardDay, false, false)`. + */ + +export interface ClanSeasonInfo { + /** UTC 00:00:00 start of the active season as Unix seconds. */ + readonly startDaySec: number; + /** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */ + readonly rewardDaySec: number; + /** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */ + readonly numberInYear: number; + /** Monotonic positive ordinal season number across years. */ + readonly ordinalNumber: number; +} + +/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */ +export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [ + { month: 1, day: 1 }, + { month: 3, day: 1 }, + { month: 5, day: 1 }, + { month: 7, day: 1 }, + { month: 9, day: 1 }, + { month: 11, day: 1 }, +]; + +const SEASON_ORDINAL_BASE_YEAR = 2016; + +/** Compute the active squadron battle season for a given Unix timestamp in seconds. */ +export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo { + const now = new Date(Math.trunc(nowSec) * 1000); + const year = now.getUTCFullYear(); + const seasonCount = CLAN_SEASON_STARTS.length; + + let activeIndex = 0; + let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000; + + for (let i = seasonCount - 1; i >= 0; i--) { + const entry = CLAN_SEASON_STARTS[i]!; + const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000; + if (nowSec >= candidateSec) { + activeIndex = i; + startSec = candidateSec; + break; + } + } + + const nextIndex = (activeIndex + 1) % seasonCount; + const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year; + const nextEntry = CLAN_SEASON_STARTS[nextIndex]!; + const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000; + + const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1); + + return { + startDaySec: startSec, + rewardDaySec: rewardSec, + numberInYear: activeIndex, + ordinalNumber, + }; +} diff --git a/apps/server/src/clans/clan-seeds.ts b/apps/server/src/clans/clan-seeds.ts index f37e4ae..72f0f1b 100644 --- a/apps/server/src/clans/clan-seeds.ts +++ b/apps/server/src/clans/clan-seeds.ts @@ -3,25 +3,75 @@ * The directory is written when the server first creates `/clans.json`. */ import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts'; -import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; const SECONDS_PER_DAY = 86400; export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY; - return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); + return tuning.presetClans.clans.map((spec, specIndex) => + buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); } -/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */ -export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] { - const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity; +/** + * The activity periods a member starts with: `periodCount` periods (defaulting to + * `activity.startingPeriods`), each with the given activity and the squadron RP it earns. + */ +export function buildDefaultPeriods( + todayDay: number, + tuning: ClanTuning, + periodActivity = tuning.activity.maxPerPeriod, + periodCount = tuning.activity.startingPeriods, +): ClanActivityPeriodEntry[] { + if (periodCount <= 0) return []; + const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity; const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod); - return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); + return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); } -function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord { - const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); +/** + * Idempotently appends deterministic filler NPCs to an existing preset clan whose + * persisted roster is smaller than its configured `targetMemberCount`, without altering + * any existing player or NPC members. + */ +export function backfillPresetClanMembers( + clan: ClanRecord, + spec: PresetClan, + specIndex: number, + todayDay: number, + tuning: ClanTuning, +): boolean { + const targetCount = Math.min(clan.mlimit, spec.targetMemberCount); + if (clan.members.length >= targetCount) return false; + + const existingUids = new Set(clan.members.map((m) => m.uid)); + const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning); + let added = false; + for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) { + const npc = fillerSpecs[i]!; + if (existingUids.has(npc.uid)) continue; + existingUids.add(npc.uid); + const memberIdx = spec.members.length + i; + clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning)); + added = true; + } + return added; +} + +function buildSeededClan( + spec: PresetClan, + specIndex: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanRecord { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const allSpecs: PresetMember[] = [ + ...spec.members, + ...buildPresetFillerSpecs(spec, specIndex, tuning), + ].slice(0, mlimit); + const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); const leader = spec.members[0]!; return { id: spec.id, @@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t region: spec.region, status: 'open', autoaccept: spec.autoAccept, - mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, + mlimit, mspent: 0, cdateSec, changedByUid: leader.uid, changedByNick: leader.nick, changedTimeSec: cdateSec, regionLastUpdatedSec: 0, + lastRewardDay: todayDay, stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats }, members, candidates: [], @@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t }; } -function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord { - const periods = buildDefaultPeriods(todayDay, tuning, npc.activity); +function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount)); + const needed = targetCount - spec.members.length; + if (needed <= 0) return []; + + const filler = tuning.presetClans.fillerMembers; + const clanSlot = presetClanSlot(spec.id, specIndex); + const usedUids = new Set(spec.members.map((m) => m.uid)); + const span = Math.max(0, filler.activityMax - filler.activityMin); + const result: PresetMember[] = []; + + let ordinal = spec.members.length + 1; + while (result.length < needed) { + const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal); + if (usedUids.has(uid)) { + ordinal++; + continue; + } + usedUids.add(uid); + const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!; + const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!; + const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!; + const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!; + const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0; + const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset); + result.push({ + uid, + nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`, + role: ClanRole.REGULAR, + title, + icon, + unit, + activity, + }); + ordinal++; + } + return result; +} + +function presetClanSlot(clanId: string, specIndex: number): number { + const parsed = Number(clanId); + if (Number.isSafeInteger(parsed) && parsed > 0) { + const remainder = parsed % 1000; + if (remainder > 0) return remainder; + } + return specIndex + 1; +} + +function buildSeededMember( + spec: PresetClan, + npc: PresetMember, + idx: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanMemberRecord { + const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods); const { step, floor } = tuning.presetClans.memberRating; return { uid: npc.uid, @@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda npcFrame: '', npcShowcaseUnit: npc.unit, curActivity: npc.activity, - totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), + totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity, earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc), ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist), diff --git a/apps/server/src/clans/clan-store.ts b/apps/server/src/clans/clan-store.ts index 032b26a..5104585 100644 --- a/apps/server/src/clans/clan-store.ts +++ b/apps/server/src/clans/clan-store.ts @@ -39,10 +39,12 @@ import { type MembershipRequestQuery, } from './clan-membership.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; -import { createDefaultClans } from './clan-seeds.ts'; +import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts'; import type { ClanTuning } from './clan-tuning.ts'; import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +const SECONDS_PER_DAY = 86400; + export type { LeaderboardQuery }; export class ClanStore { @@ -51,18 +53,36 @@ export class ClanStore { readonly tuning: ClanTuning; #state: StoredClansState; - constructor(dataFolder: string, tuning: ClanTuning) { + constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) { this.#filePath = join(dataFolder, 'clans.json'); this.tuning = tuning; - this.#state = this.#loadOrSeed(); + this.#state = this.#loadOrSeed(nowSec); } - #loadOrSeed(): StoredClansState { + #loadOrSeed(nowSec: number): StoredClansState { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); if (existsSync(this.#filePath)) { const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; - if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; + if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') { + let mutated = false; + for (let i = 0; i < this.tuning.presetClans.clans.length; i++) { + const spec = this.tuning.presetClans.clans[i]!; + const existing = parsed.clans.find((c) => c.id === spec.id); + if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) { + mutated = true; + } + } + for (const clan of parsed.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + } + } + if (mutated) this.#save(parsed); + return parsed; + } } - const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) }; + const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) }; this.#save(seeded); return seeded; } @@ -71,19 +91,7 @@ export class ClanStore { writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); } - #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { - return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan; - } - - byId(clanId: string): ClanRecord | undefined { - return this.#state.clans.find((c) => c.id === clanId); - } - - findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined { - return findClanInList(this.#state.clans, query); - } - - clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + #findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { for (const clan of this.#state.clans) { const member = clan.members.find((m) => m.uid === userId); if (member) return { clan, member }; @@ -91,12 +99,147 @@ export class ClanStore { return undefined; } + #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { + return clanId && clanId !== '-1' + ? this.#state.clans.find((c) => c.id === clanId) + : this.#findUserClan(userId)?.clan; + } + + /** + * Lazily settles expired activity reward periods for all squadrons using the stock + * client formula (`clanAverageActivityModal.nut:44-54`): + * `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)` + * Player members' current-period activity resets to 0 for the new period while NPC + * members keep their active roster contribution. + */ + settleExpiredPeriods(nowSec = nowSeconds()): boolean { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const { + maxPerPeriod, + squadronRpPerFullPeriod: maxClanActivity, + rewardPeriodDays, + historyDepthDays, + } = this.tuning.activity; + + let mutated = false; + for (const clan of this.#state.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + continue; + } + const elapsedDays = todayDay - clan.lastRewardDay; + if (elapsedDays < rewardPeriodDays) continue; + + const anchorDay = clan.lastRewardDay; + const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays); + const settlementDay = anchorDay + rewardPeriodDays; + const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays; + const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0); + const maxActivity = maxPerPeriod * clan.members.length; + const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0; + const minKeptDay = settlementDay - historyDepthDays; + + clan.members = clan.members.map((member) => { + const myActivity = Math.max(0, member.curActivity); + const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0; + const myExp = (myPercent > 0 && clanPercent > 0) + ? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity)) + : 0; + const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay)); + const settledEntry = (myActivity > 0 || myExp > 0) + ? [{ day: settlementDay, activity: myActivity, exp: myExp }] + : []; + const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay); + if (member.isNpc) { + return { + ...member, + totalActivity: member.totalActivity + myActivity, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + } + return { + ...member, + curActivity: 0, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + }); + + clan.lastRewardDay = nextAnchorDay; + mutated = true; + } + + if (mutated) this.#save(); + return mutated; + } + + /** + * Accumulates current-period squadron activity from battle base vehicle RP + * (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`). + * Returns the activity points actually added. + */ + recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number { + this.settleExpiredPeriods(nowSec); + if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0; + const found = this.#findUserClan(userId); + if (!found) return 0; + + const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity; + const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint); + if (rawGain <= 0) return 0; + + const { clan, member } = found; + const remaining = Math.max(0, maxPerPeriod - member.curActivity); + const added = Math.min(rawGain, remaining); + if (added <= 0) return 0; + + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const periodStartDay = clan.lastRewardDay ?? todayDay; + const nextCurActivity = member.curActivity + added; + const nextTotalActivity = member.totalActivity + added; + const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay); + const nextPeriods = existingInProgressIdx >= 0 + ? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p)) + : [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods]; + + const memberIdx = clan.members.findIndex((m) => m.uid === userId); + if (memberIdx < 0) return 0; + clan.members[memberIdx] = { + ...member, + curActivity: nextCurActivity, + totalActivity: nextTotalActivity, + periods: nextPeriods, + }; + this.#save(); + return added; + } + + byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return this.#state.clans.find((c) => c.id === clanId); + } + + findClan( + query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }, + nowSec = nowSeconds(), + ): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return findClanInList(this.#state.clans, query); + } + + clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + this.settleExpiredPeriods(nowSec); + return this.#findUserClan(userId); + } + pendingRequestOfUser(userId: string): ClanRecord | undefined { return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId)); } - earnedSquadronExpOf(userId: string): number { - return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0; + earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number { + return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0; } npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { @@ -107,8 +250,8 @@ export class ClanStore { return undefined; } - syncProfile(profile: BlkBlock, account: Account): void { - const found = this.clanOfUser(account.userId); + syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void { + const found = this.clanOfUser(account.userId, nowSec); if (found) { const { clan, member } = found; if (member.nick !== account.nick) { @@ -131,15 +274,31 @@ export class ClanStore { } } - queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + this.settleExpiredPeriods(nowSec); return queryClanLeaderboard(this.#state.clans, query, this.tuning); } createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { + this.settleExpiredPeriods(nowSec); const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec); if (outcome.ok) { + const created = this.#state.clans[0]; + if (created) { + created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY); + const founder = created.members[0]; + if (founder && founder.uid === account.userId) { + const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity); + const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0); + created.members[0] = { + ...founder, + curActivity, + totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity, + }; + } + } this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return outcome; } @@ -189,10 +348,11 @@ export class ClanStore { } requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome { - const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning); + this.settleExpiredPeriods(nowSec); + const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning); if (res.mutated) { this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return res.outcome; } diff --git a/apps/server/src/clans/clan-tuning.ts b/apps/server/src/clans/clan-tuning.ts index 8a2e063..cd7b521 100644 --- a/apps/server/src/clans/clan-tuning.ts +++ b/apps/server/src/clans/clan-tuning.ts @@ -26,6 +26,17 @@ export interface PresetMember { readonly activity: number; } +export interface PresetFillerMembers { + readonly activityMin: number; + readonly activityMax: number; + readonly uidBase: number; + readonly uidStride: number; + readonly callsigns: readonly string[]; + readonly titles: readonly string[]; + readonly icons: readonly string[]; + readonly units: readonly string[]; +} + export interface PresetClan { readonly id: string; readonly tag: string; @@ -37,6 +48,7 @@ export interface PresetClan { readonly region: string; readonly autoAccept: boolean; readonly createdAfterDays: number; + readonly targetMemberCount: number; readonly rating: ModeTriple; readonly members: readonly PresetMember[]; } @@ -47,6 +59,8 @@ export interface ClanTuning { readonly squadronRpPerFullPeriod: number; readonly rewardPeriodDays: number; readonly historyDepthDays: number; + readonly rpPerActivityPoint: number; + readonly startingActivity: number; readonly startingPeriods: number; }; readonly memberLimits: { readonly normal: number; readonly battalionInitial: number }; @@ -56,6 +70,8 @@ export interface ClanTuning { readonly presetClans: { readonly createdDaysAgo: number; readonly memberJoinSpacingMinutes: number; + readonly npcHistoryPeriods: number; + readonly fillerMembers: PresetFillerMembers; readonly stats: PresetClanStats; readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple }; readonly clans: readonly PresetClan[]; @@ -64,6 +80,7 @@ export interface ClanTuning { export function readClanTuning(file: TuningReader): ClanTuning { const activity = file.object('activity'); + const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 }); const limits = file.object('memberLimits'); const leaderboard = file.object('leaderboard'); const preset = file.object('presetClans'); @@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning { const rating = preset.object('memberRating'); return { activity: { - maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }), + maxPerPeriod, squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }), rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }), historyDepthDays: activity.int('historyDepthDays', { min: 1 }), + rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }), + startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }), startingPeriods: activity.int('startingPeriods', { min: 0 }), }, memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) }, @@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning { presetClans: { createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }), memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }), + npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }), + fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod), stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats, memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) }, clans: preset.list('clans', readPresetClan), @@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning { }; } +function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers { + const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod }); + const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod }); + const callsigns = entry.stringList('callsigns'); + const titles = entry.stringList('titles'); + const icons = entry.stringList('icons'); + const units = entry.stringList('units'); + if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) { + throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty'); + } + return { + activityMin, + activityMax, + uidBase: entry.int('uidBase', { min: 1 }), + uidStride: entry.int('uidStride', { min: 1 }), + callsigns, + titles, + icons, + units, + }; +} + function readPresetClan(entry: TuningReader): PresetClan { const type = entry.string('type'); if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`); const members = entry.list('members', readPresetMember); if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`); + const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length; return { id: entry.string('id'), tag: entry.string('tag'), @@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan { region: entry.string('region'), autoAccept: entry.bool('autoAccept'), createdAfterDays: entry.int('createdAfterDays', { min: 0 }), + targetMemberCount: Math.max(members.length, rawTarget), rating: triple(entry.object('rating')), members, }; diff --git a/apps/server/src/clans/clan-types.ts b/apps/server/src/clans/clan-types.ts index c07ad84..9024419 100644 --- a/apps/server/src/clans/clan-types.ts +++ b/apps/server/src/clans/clan-types.ts @@ -171,6 +171,8 @@ export interface ClanRecord { changedByNick: string; changedTimeSec: number; regionLastUpdatedSec: number; + /** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */ + lastRewardDay?: number; stats: ClanStats; members: ClanMemberRecord[]; candidates: ClanCandidateRecord[]; diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index da812bc..9a39f34 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.ts @@ -1,22 +1,30 @@ /** * The profile as the char service hands it to the client: the saved profile plus the - * account data and server clock the char server attaches on the wire. + * account data, server clock, and active squadron season metadata the char server attaches + * on the wire. * * charDrivenNick: the client reads the player's nick from this top-level string when it * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). * * serverTime:i64: the char server's clock; without it the client * takes the server time as 0 and every expiry and time limit is wrong. + * + * clanDuelNextReward:i64, clanSeasonStart:i64, clanSeasonOrdinal:i, clanSeasonInYear:i: + * parsed by GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.58 0xebc728..0xebc7b4) + * on every profile-returning char response and exposed by clan_get_current_season_info + * (0x178aff0..0x178b227). Without them all fields default to 0, causing the squadron + * leaderboard to display "1970-I" and "1970-01-01". */ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; +import { currentClanSeason } from '../clans/clan-season.ts'; import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts'; import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts'; import { clearStoreCart } from './profile-store-cart.ts'; import { clientHangarSpares } from './profile-vehicle-state.ts'; -import { serverTimeNow } from './server-time.ts'; +import { serverTimeFromUnixMs } from './server-time.ts'; -export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { +export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.now()): BlkBlock { // Clone the hangar entries whose spare count has a different wire representation. const profile: BlkBlock = { name: saved.name, @@ -26,8 +34,13 @@ export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { }; clearStoreCart(profile); const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON; + const season = currentClanSeason(Math.floor(nowMs / 1000)); setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon }); setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); - setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() }); + setParam(profile, 'serverTime', { type: 'int64', value: serverTimeFromUnixMs(nowMs) }); + setParam(profile, 'clanDuelNextReward', { type: 'int64', value: BigInt(season.rewardDaySec) }); + setParam(profile, 'clanSeasonStart', { type: 'int64', value: BigInt(season.startDaySec) }); + setParam(profile, 'clanSeasonOrdinal', { type: 'int', value: season.ordinalNumber }); + setParam(profile, 'clanSeasonInYear', { type: 'int', value: season.numberInYear }); return profile; } diff --git a/apps/server/tuning/clans.jsonc b/apps/server/tuning/clans.jsonc index d84dae5..a80b239 100644 --- a/apps/server/tuning/clans.jsonc +++ b/apps/server/tuning/clans.jsonc @@ -2,19 +2,25 @@ { // Set activity and squadron RP. The service reports maxActivityPerPeriod, maxClanActivity, rewardPeriodDays, and historyDepth in squadron replies. "activity": { - "maxPerPeriod": 360, // Activity cap per reward period. + "maxPerPeriod": 360, // Activity cap per reward period. "squadronRpPerFullPeriod": 20000, // Squadron RP awarded for a full activity period. "rewardPeriodDays": 3, // Reward period in days. "historyDepthDays": 14, // Activity history displayed by the client, in days. - // Seed full periods on creation or joining so squadron research can start immediately. - "startingPeriods": 3 + // Base vehicle RP from battles required for 1 squadron activity point (stock rule: 200 RP = 1 point). + "rpPerActivityPoint": 200, + // Starting current-period activity for a player creating or joining a squadron (0..maxPerPeriod). + // Set to 360 together with startingPeriods > 0 in /tuning/clans.jsonc to start at full activity immediately. + "startingActivity": 0, + // Full past activity periods granted on creation or joining (default 0: earn activity through battles). + // Increase (e.g. 1 or 3) in /tuning/clans.jsonc to grant immediate squadron RP on joining. + "startingPeriods": 0 }, // Set the full squadron cap and initial battalion cap. Expansion cost and step size are read from warpoints.blk. "memberLimits": { "normal": 128, "battalionInitial": 10 }, - // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier), so small NPC rosters can represent full squadrons. - "leaderboard": { "activityMultiplier": 10, "maxActivity": 100000 }, + // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier). + "leaderboard": { "activityMultiplier": 1, "maxActivity": 100000 }, // Starting ID for player-created squadrons. "firstNewClanId": 600001, @@ -29,6 +35,37 @@ "presetClans": { "createdDaysAgo": 180, // Age of the first seeded squadron before applying each squadron's createdAfterDays offset. "memberJoinSpacingMinutes": 60, + "npcHistoryPeriods": 3, // Past activity periods seeded for preset NPC members. + // Deterministic filler NPC pool used when a preset clan's targetMemberCount exceeds its named roster. + "fillerMembers": { + "activityMin": 340, + "activityMax": 360, + "uidBase": 900000000, + "uidStride": 1000, + "callsigns": [ + "Vanguard", "Falcon", "Striker", "Sentinel", "Raptor", "Valkyrie", + "Tempest", "Bastion", "Corsair", "Drago", "Harrier", "Kestrel", + "Lancer", "Mirage", "Nomad", "Osprey", "Paladin", "Reaper", + "Sabre", "Talon", "Vector", "Warden", "Zephyr", "Aegis", + "Cobra", "Hornet", "Jaguar", "Lynx", "Mantis", "Puma" + ], + "titles": [ + "title_pilot", "title_tankman", "title_ace", "title_sniper", + "title_scout", "title_eagle", "title_tank_destroyer", "title_jet_powered" + ], + "icons": [ + "cardicon_03", "cardicon_05", "cardicon_07", "cardicon_08", + "cardicon_09", "cardicon_11", "cardicon_12", "cardicon_14", + "cardicon_15", "cardicon_16", "cardicon_18", "cardicon_19", + "cardicon_20", "cardicon_22", "cardicon_25", "cardicon_28" + ], + "units": [ + "cn_ztz_99a", "su_27sm", "germ_leopard_2a7v", "f_14b", + "jp_destroyer_shimakaze", "sw_strv_122b_plus", "j_11a", "jh_7a", + "cn_vt_4a1", "f_15j_kai", "ussr_t_90m", "us_m1a2_sep2_abrams", + "uk_challenger_2_black_night", "us_hstvl", "it_centauro_rgo_120" + ] + }, // Lifetime stats displayed for each seeded squadron. "stats": { "akills_arc": 4280, "akills_hist": 6150, "akills_sim": 1420, @@ -45,7 +82,7 @@ "slogan": "离线天空与钢铁防线 · 自由研发全部联队载具", "desc": "War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。", "announcement": "欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。", - "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, + "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, "targetMemberCount": 60, "rating": { "arc": 1840, "hist": 2150, "sim": 1620 }, "members": [ { "uid": "900001001", "nick": "Lin_Wei", "role": "LEADER", "title": "title_marshall", "icon": "cardicon_28", "unit": "cn_ztz_99a", "activity": 360 }, @@ -61,7 +98,7 @@ "slogan": "鹰击长空 · 现代喷气空战与陆空协同联队", "desc": "专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。", "announcement": "本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。", - "region": "Asia", "autoAccept": true, "createdAfterDays": 12, + "region": "Asia", "autoAccept": true, "createdAfterDays": 12, "targetMemberCount": 60, "rating": { "arc": 1690, "hist": 2040, "sim": 1780 }, "members": [ { "uid": "900002001", "nick": "SkyDragon_J20", "role": "LEADER", "title": "title_ace", "icon": "cardicon_25", "unit": "j_11a", "activity": 360 }, @@ -75,7 +112,7 @@ "slogan": "Steel & Fire — Heavy Armor Historical Squadron", "desc": "Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.", "announcement": "Squadron vehicles ready for research at full 20,000 RP per period.", - "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, + "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, "targetMemberCount": 60, "rating": { "arc": 1920, "hist": 1980, "sim": 1510 }, "members": [ { "uid": "900003001", "nick": "Kommissar_KVs", "role": "LEADER", "title": "title_hero", "icon": "cardicon_22", "unit": "ussr_t_90m", "activity": 360 }, @@ -88,7 +125,7 @@ "slogan": "All The Way — Air, Ground & Naval Task Force", "desc": "需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。", "announcement": "Manual application review enabled for testing request/cancel workflow.", - "region": "NA", "autoAccept": false, "createdAfterDays": 35, + "region": "NA", "autoAccept": false, "createdAfterDays": 35, "targetMemberCount": 58, "rating": { "arc": 1550, "hist": 1760, "sim": 1490 }, "members": [ { "uid": "900004001", "nick": "Major_Winters", "role": "LEADER", "title": "title_brother_in_arms", "icon": "cardicon_03", "unit": "us_m1a2_sep2_abrams", "activity": 360 }, @@ -100,7 +137,7 @@ "slogan": "轻量级战术分队 · 侦察与快速反应", "desc": "战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。", "announcement": "轻装侦察分队常驻开放。", - "region": "Global", "autoAccept": true, "createdAfterDays": 48, + "region": "Global", "autoAccept": true, "createdAfterDays": 48, "targetMemberCount": 2, "rating": { "arc": 1410, "hist": 1610, "sim": 1320 }, "members": [ { "uid": "900005001", "nick": "Ghost_Scout", "role": "LEADER", "title": "title_scout", "icon": "cardicon_15", "unit": "us_hstvl", "activity": 360 },