'use strict'; /* * POST /movements with type 'transport': carry resources from one of your POPs to any POP. Capacity and the number * of concurrent transports come from the Internet exchange (D.TRANSPORT): `links` = its level, each link carries * `capacityPerLink`. The cargo leaves the POP now and is added to the target on arrival (anything above the target's * Rack hall cap is lost). The trade stage calls `launchTransport` directly for the two legs of an accepted offer. */ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const { settle, loadWorld } = require('../state'); const { ownedTown } = require('./build'); const ctxOf = require('../military/ctx'); const U = require('../military/units'); const M = require('../military/movements'); // Validate + dispatch from an already settled, owned POP `from`. `toRow` is the target POP row. `extra` is stored on // the movement (and its return leg) for later stages, e.g. { tradeId }. Returns the movement. function launchTransport(ctx, from, toRow, cargo, extra) { const { db, now } = ctx; const plan = R.transportPlan(from, cargo, M.activeLinks(db, from.id), now); if (!plan.ok) throw new GameError(plan.code, plan); const world = loadWorld(db, from.worldId); const dist = R.distance(from.x, from.y, toRow.x, toRow.y); const clean = {}; for (const r of D.RESOURCES) if (cargo[r] > 0) clean[r] = cargo[r]; for (const r of D.RESOURCES) from.res[r] -= clean[r] || 0; db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', from.res.fiber, from.res.hardware, from.res.capital, from.id); return M.insertMovement(ctx, { worldId: from.worldId, ownerId: from.ownerId, type: 'transport', fromTownId: from.id, toTownId: toRow.id, from: { x: from.x, y: from.y }, to: { x: toRow.x, y: toRow.y }, units: {}, cargo: clean, departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: Object.assign({}, extra || {}), }); } module.exports = function sendTransport(ctx0, { userId, fromTownId, toTownId, cargo }) { const ctx = ctxOf(ctx0); const { db, now } = ctx; const from = ownedTown(db, userId, fromTownId); const to = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', toTownId, from.worldId); if (!to) throw new GameError('not_found', { what: 'town' }); if (to.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' }); settle(db, from, now); const mv = launchTransport(ctx, from, to, cargo || {}); const toOp = U.getOperator(db, to.owner_id); if (toOp.id !== from.ownerId) { const uid = U.userOfOperator(db, toOp.id); if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: to.id, fromTownId: from.id, arriveAt: mv.arriveAt }); } return { movementId: mv.id, type: 'transport', fromTownId: from.id, toTownId: to.id, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt }; }; module.exports.launchTransport = launchTransport;