'use strict'; /* * Read models for the military stage: the military part of GET /towns/:id, the movements list with incoming warnings, * reports, and tile info for the send dialog. Reads catch the event queue up first (via `fresh`) and never write. */ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const { loadWorld, hasTable } = require('../state'); const U = require('./units'); const P = require('./power'); const j = (s) => JSON.parse(s || '{}'); function townNames(db, ids) { const out = new Map(); for (const id of ids) { if (!id || out.has(id)) continue; const t = db.get('SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?', id); out.set(id, t ? { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, owner: { id: t.oid, name: t.oname, asNumber: t.asn } } : null); } return out; } // What the owner of a movement sees. function ownerView(m, names) { const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null; const extra = j(m.extra); return { id: m.id, type: m.type, status: m.status, ownerId: m.owner_id, from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null }, to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null }, units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at, recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs, target: extra.target || null, parentId: m.parent_id, siteId: extra.siteId || null, // siteId: a shipment to a backbone landing site }; } // What the target of somebody else's movement sees: origin and ETA, never the type, units or cargo. function incomingView(m, names) { const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null; return { id: m.id, type: 'unknown', status: m.status, incoming: true, from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null, owner: f ? f.owner : null }, to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null }, departAt: m.depart_at, arriveAt: m.arrive_at, }; } // Active movements: the operator's own (outgoing legs, returns, transports) and other operators' movements heading for // the operator's POPs. `townId` limits both to one POP. function movementLists(db, operatorId, townId) { const own = db.all(`SELECT * FROM movements WHERE owner_id = ? AND status = 'out' ${townId ? 'AND (from_town_id = ? OR to_town_id = ?)' : ''} ORDER BY arrive_at, id LIMIT ?`, ...(townId ? [operatorId, townId, townId, D.MILITARY.maxLists] : [operatorId, D.MILITARY.maxLists])); const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' ${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`, ...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists])); // Confederation members (own alliance included) see what is heading for each other's POPs: origin and ETA only, the type // stays hidden. Movements of operators who are themselves partners of the target are friendly traffic and left out. // Only in the whole-operator list, not in the per-POP lists. let allied = []; if (!townId) { const partners = require('../alliances').confederatedOperators(db, operatorId); if (partners.length) { allied = db.all(`SELECT m.*, t.owner_id AS target_owner FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id IN (${partners.map(() => '?').join(',')}) AND m.owner_id != t.owner_id AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' ORDER BY m.arrive_at, m.id LIMIT ?`, ...partners, operatorId, D.MILITARY.maxLists) .filter((m) => !U.pactBlocks(db, m.owner_id, m.target_owner)); } } const names = townNames(db, own.concat(inc, allied).flatMap((m) => [m.from_town_id, m.to_town_id])); const out = { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) }; if (!townId) { out.alliedIncoming = allied.map((m) => { const o = db.get('SELECT id, name FROM operators WHERE id = ?', m.target_owner); return Object.assign(incomingView(m, names), { ally: true, toOperator: { id: o.id, name: o.name } }); }); } return out; } // [{ siteId, x, y, units }] of one owner POP's units standing in landing sites (the `site_stationed` rows), ordered by site. function garrisonGroups(db, townId) { const by = new Map(); for (const r of db.all('SELECT s.site_id AS sid, l.x AS x, l.y AS y, s.unit AS unit, s.count AS count FROM site_stationed s JOIN landing_sites l ON l.id = s.site_id WHERE s.owner_town_id = ? ORDER BY s.site_id, s.unit', townId)) { if (!by.has(r.sid)) by.set(r.sid, { siteId: r.sid, x: r.x, y: r.y, units: {} }); by.get(r.sid).units[r.unit] = r.count; } return Array.from(by.values()); } // The military part of GET /towns/:id (the town object is already loaded and belongs to the caller). function townMilitary(db, t, now, world) { const home = U.homeUnits(db, t.id); const online = P.online(t, now); const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId))); const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units })); const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units })); // Units of this POP standing in backbone landing sites its alliance holds: they draw THIS POP's power (state.unitDraw), so they belong here. const garrisoned = hasTable(db, 'site_stationed') ? garrisonGroups(db, t.id) : []; const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id) .map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; }); const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id); const rp = rq ? JSON.parse(rq.payload) : null; const bonus = U.researchBonusOf(db, t.ownerId); const trainable = D.UNIT_ORDER.map((unit) => { const def = D.UNITS[unit]; const missing = R.unitMissing(t, unit); return { unit, building: def.building, role: def.role, cost: R.unitCost(unit, 1), timeMs: R.trainTimeMs(unit, 1, t.buildings[def.building] ? t.buildings[def.building].level : 0, world.speed), missing, locked: missing.length > 0 }; }); const offline = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', t.id); const op = U.getOperator(db, t.ownerId); const links = R.transportLinks(t); return { units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away, garrisoned }, training, trainable, research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel }, transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: R.transportCapacity(world.speed) }, movements: movementLists(db, t.ownerId, t.id), protectionUntil: op.protection_until, }; } function createMilitaryQueries({ db, clock, scheduler }) { const fresh = () => { scheduler.runDue(); return clock.now(); }; function operatorFor(userId, worldId) { const op = worldId ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId); if (!op) throw new GameError('not_found', { what: 'operator' }); return op; } function movements(userId, { worldId }) { const now = fresh(); const op = operatorFor(userId, worldId); return Object.assign({ serverTime: now }, movementLists(db, op.id, null)); } function reports(userId, { after, limit, unread }) { const now = fresh(); const n = limit || 25; const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? ${after ? 'AND r.id < ?' : ''} ${unread ? 'AND rr.read_at IS NULL' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [userId, after, n + 1] : [userId, n + 1])); const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, role: r.role, read: r.read_at !== null, summary: j(r.summary) })); const unreadCount = db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NULL', userId).n; return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null, unread: unreadCount }; } function report(userId, id) { const now = fresh(); const r = db.get(`SELECT r.*, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? AND r.id = ?`, userId, id); if (!r) throw new GameError('not_found', { what: 'report' }); return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, role: r.role, read: r.read_at !== null, summary: j(r.summary), data: j(r.data) } }; } // Public information about a tile, for the send dialog: what is there, who owns it, how far it is from each of my POPs, // whether I could found a POP there. function tileInfo(userId, { worldId, x, y }) { const now = fresh(); const op = operatorFor(userId, worldId); const world = loadWorld(db, op.world_id); const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed)); if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' }); const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y); const mine = U.operatorTowns(db, op.id); const out = { serverTime: now, x, y, type: row ? 'pop' : tile.type, bonus: tile.bonus || null, distances: mine.map((t) => ({ townId: t.id, distance: R.distance(t.x, t.y, x, y) })) }; if (row) { const o = U.getOperator(db, row.owner_id); out.town = { id: row.id, name: row.name, isCapital: !!row.is_capital, owner: { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protected: R.isProtected(o.protection_until, now), protectionUntil: o.protection_until }, mine: o.id === op.id }; } if (tile.type === 'incumbent') { const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id); out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus }; } if (tile.type === 'backbone') { // end game: who holds the site, its node level and stockpile, whether you could attack it const E = require('../endgame'); const st = E.siteStates(db, world, now).find((s) => s.site.index === tile.site); const v = E.siteView(db, world, st.site, st.row); const holds = !!(op.alliance_id && v.holder && v.holder.allianceId === op.alliance_id); out.backbone = { siteId: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel, pool: v.pool, build: v.build, mine: holds, canAttack: !!op.alliance_id && !holds }; } const fp = U.operatorFootprint(db, op.id, now); const gate = R.footprintGate(mine.length, fp); let nearest = Infinity; for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y)); const sc = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp }); out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance }; return out; } return { movements, reports, report, tileInfo }; } module.exports = { townMilitary, movementLists, createMilitaryQueries };