Files
c-evo-evo/game/GameServer.cpp
T

3940 lines
166 KiB
C++

// This file is part of cevo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "GameServer.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
std::array<Brain *, nPl> playersBrain{};
Brains brains;
QString notifyMessage;
Brain *brainNoTerm = nullptr;
Brain *brainSuperVirtual = nullptr;
Brain *brainTerm = nullptr;
Brain *brainRandom = nullptr;
Brain *brainNetworkClient = nullptr;
Brain *brainNetworkServer = nullptr;
bool networkEnabled = false;
namespace {
// Equivalent of Directories.pas's GetAiDir() - see Brain.cpp's own copy of
// this (not shared via a header since Directories.pas itself isn't ported).
QString getAiDir()
{
#ifdef CEVO_AI_DIR
return QStringLiteral(CEVO_AI_DIR);
#else
return QString();
#endif
}
NotifyFunction notify;
// Convenience wrapper matching Pascal's `Notify(Id)` (Index defaults to 0).
void notifyEvent(NotifyId id, int index = 0)
{
if (notify)
notify(id, index);
}
// Equivalent of Pascal's unit-level private `bix: TBrains` ("brain of the
// players") - renamed to avoid colliding with the pervasive `bix`
// parameter/loop-variable name used for brain *indices* elsewhere in the
// original (e.g. InitBrain(bix: TBrain), CallClient(bix, Command, ...)).
std::array<Brain *, nPl> playerBrain{};
bool previewElevation = false;
// Remaining unit-level private state needed by this slice (the rest of
// GameServer.pas's big private var block belongs to the not-yet-ported
// SaveGame/StartGame/LoadGame/BeforeTurn/AfterTurn/Server()).
int maxTurn = 0;
int pTurn = 0;
int gWinner = 0;
int gColdWarStart = 0;
int pDipActive = -1;
int pContacted = -1;
TOffer lastOffer{};
int uixSelectedTransport = -1;
int spyMission = 0;
bool winOnAlone = false;
bool autoSaveExists = false;
CmdListState autoSaveState{};
std::array<void *, nPl> savedData{};
std::array<void *, nPl> debugMap{};
std::array<int, nPl> originalDataVersion{};
std::array<int, nPl> devModelTurn{}; // turn of last sCreateDevModel call (comment name is stale in the original too)
std::array<QString, nPl> aiInfo{};
QString aiCredits;
// Persistent byte-buffer caches for sGetAIInfo/sGetAICredits, which hand
// out a raw const char* into AIInfo[]/AICredits (valid until the next such
// call - same "valid until next mutating call" convention already used
// for CmdList::get's data pointer).
QByteArray aiInfoUtf8Cache;
QByteArray aiCreditsUtf8Cache;
QString mapFileName; // name of map to use, empty for random (set by not-yet-ported StartNewGame/LoadGame)
QString logFileName;
QString savePath; // directory of the file for saving the current game
int lastEndClientCommand = -1;
int ccCommand = 0;
int ccPlayer = -1;
std::array<int, 15> ccData{};
double lastClientTime = 0.0;
int gStealFrom = -1;
int zocTile = -1;
// GameServer.pas's own local ProjectType() result constants (Server()'s
// sSetCityProject handling only - not a shared Protocol.h concept).
constexpr int ptSelect = 0;
constexpr int ptTrGoods = 1;
constexpr int ptUn = 2;
constexpr int ptCaravan = 3;
constexpr int ptImp = 4;
constexpr int ptWonder = 6;
constexpr int ptShip = 7;
constexpr int ptInvalid = 8;
int loadTurn = 0; // turn where to stop loading
int nLogOpened = 0; // nLog of opened book
bool movieStopped = false;
bool loadOK = false;
// SavedTiles[cix] - a single shared scratch array (not per-player): only
// RW[pTurn]'s cities are ever "in focus" at a time, matching the original.
std::array<std::uint32_t, nCmax> savedTiles{};
// Predefined map snapshot (only non-empty when Database::landMass == 0) -
// a disclosed std::vector-based simplification of the original's
// GetMem/FreeMem(MapField) raw pointer (not a wire format, pure in-memory
// bookkeeping, same rationale as CmdList's QByteArray backing buffer).
std::vector<std::uint32_t> mapField;
// Stat[st][p][turn] equivalent - std::vector instead of GetMem/FreeMem for
// the same reason as mapField above.
std::array<std::array<std::vector<std::int32_t>, nPl>, nStat> stat{};
// Server() is the ~1900-line client-to-server command dispatcher - the
// single biggest piece of GameServer.pas. Forward-declared here (needed by
// initBrain/forceClientDeactivation/changeClient, which are defined before
// it); the real definition sits at the end of this anonymous namespace,
// after every lifecycle function it dispatches to.
int CEVO_ABI_CALL server(int command, int player, int subject, void *data);
// Re-applies previously-recorded sIntExpandTerritory diffs for the current
// player's turn (used after loading/replaying a game - during live play
// CheckBorders computes and applies territory changes directly instead).
void insertTerritoryUpdateCommands()
{
while (Database::cl.progress() < 1000) {
const CmdListState formerState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (command == sIntExpandTerritory && p1 == pTurn) {
Database::intServer(command, p1, subject, data);
} else {
Database::cl.setState(formerState);
break;
}
}
Database::invalidTreatyMap = 0;
}
void callPlayer(int command, int p, void *data)
{
if (Database::mode != Database::moMovie || p == 0) {
try {
playerBrain[p]->module.call(command, p, data);
} catch (...) {
// Fixes an apparent typo in the original (`Notify(ntException +
// bix[P])` doesn't even type-check as written - enum + object -
// matching the correct 2-arg Notify(Id, Index) calls used
// everywhere else in this same file, e.g. InitBrain below).
if (notify)
notify(NotifyId::Exception, brains.indexOf(playerBrain[p]));
}
}
}
void callAllPlayers(int command, void *data)
{
for (int i = 0; i < nPl; ++i)
if (playerBrain[i])
callPlayer(command, i, data);
}
void callClient(int brainIndex, int command, void *data)
{
if (Database::mode != Database::moMovie || brainIndex == brains.indexOf(playerBrain[0])) {
try {
brains[brainIndex].module.call(command, -1, data);
} catch (...) {
if (notify)
notify(NotifyId::Exception, brainIndex);
}
}
}
void putMessage(int level, const QString &text)
{
const QByteArray bytes = text.toUtf8();
playerBrain[0]->module.call(cDebugMessage, level, const_cast<char *>(bytes.constData()));
}
void changeClientWhenDone(int command, int player, const void *data, int dataSize)
{
ccCommand = command;
ccPlayer = player;
if (dataSize > 0)
std::memcpy(ccData.data(), data, static_cast<std::size_t>(dataSize));
notifyEvent(NotifyId::ChangeClient);
}
void forceClientDeactivation()
{
if (pDipActive < 0) {
server(sTurn, pTurn, 0, nullptr); // no nego mode
} else {
switch (lastEndClientCommand) { // nego mode
case scContact:
server(scReject, pDipActive, 0, nullptr);
break;
case scDipCancelTreaty:
case scDipBreak:
server(scDipNotice, pDipActive, 0, nullptr);
break;
default: {
TOffer nullOffer{};
nullOffer.nDeliver = 0;
nullOffer.nCost = 0;
server(scDipOffer, pDipActive, 0, &nullOffer);
break;
}
}
}
}
void inform(int p)
{
TPlayerContext &player = Database::rw[p];
player.Turn = Database::gTurn;
if (Database::gTurn == maxTurn && p == pTurn && p == 0)
player.Happened |= phTimeUp;
if (gWinner > 0 && p == pTurn && p == 0)
player.Happened |= phShipComplete;
player.Alive = Database::gAlive;
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
std::memcpy(player.Ship, Database::gShip.data(), sizeof(player.Ship));
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != p && playerBrain[p1] && Database::difficulty[p1] > 0)
player.EnemyReport[p1]->Credibility = Database::rw[p1].Credibility;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != p && ((1 << p1) & Database::gAlive)) {
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 ||
player.Treaty[p1] >= trFriendlyContact)
Database::giveCivilReport(p, p1);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 || player.Treaty[p1] == trAlliance)
Database::giveMilReport(p, p1);
}
}
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
}
void logChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status) {
Database::cl.put(sIntSetUnitStatus, p, ix, &un[ix].Status);
un[ix].SavedStatus = un[ix].Status;
}
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status) {
Database::cl.put(sIntSetCityStatus, p, ix, &city[ix].Status);
city[ix].SavedStatus = city[ix].Status;
}
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status) {
Database::cl.put(sIntSetModelStatus, p, ix, &model[ix].Status);
model[ix].SavedStatus = model[ix].Status;
}
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status) {
Database::cl.put(sIntSetECityStatus, p, ix, &enemyCity[ix].Status);
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
}
if (playerBrain[p]->dataSize > 0) {
Database::cl.putDataChanges(sIntDataChange, p, static_cast<std::uint32_t *>(savedData[p]),
static_cast<std::uint32_t *>(player.Data), playerBrain[p]->dataSize);
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
}
void noLogChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
un[ix].SavedStatus = un[ix].Status;
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
city[ix].SavedStatus = city[ix].Status;
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
model[ix].SavedStatus = model[ix].Status;
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
if (playerBrain[p]->dataSize > 0)
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
bool hasChanges(int p)
{
TPlayerContext &player = Database::rw[p];
const TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status)
return true;
const TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status)
return true;
const TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status)
return true;
const TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status)
return true;
if (player.Data) {
const auto *savedWords = static_cast<const std::uint32_t *>(savedData[p]);
const auto *currentWords = static_cast<const std::uint32_t *>(player.Data);
for (int ix = 0; ix < playerBrain[p]->dataSize; ++ix)
if (savedWords[ix] != currentWords[ix])
return true;
}
return false;
}
void initBrain(Brain &brain)
{
assert(brain.kind != BrainType::SuperVirtual);
if (brain.initialized)
return;
if (brain.kind == BrainType::AI) { // get client function
if (notify)
notify(NotifyId::InitModule, brains.indexOf(&brain));
if (!brain.module.load(brain.dllName.toStdString()))
notify(NotifyId::DllError, brains.indexOf(&brain));
}
if (brain.module.isLoaded()) {
brain.initialized = true;
TInitModuleData initModuleData{};
initModuleData.Server = &server;
initModuleData.DataVersion = 0;
initModuleData.DataSize = 0;
initModuleData.Flags = 0;
callClient(brains.indexOf(&brain), cInitModule, &initModuleData);
brain.dataVersion = initModuleData.DataVersion;
brain.dataSize = (initModuleData.DataSize + 3) / 4;
if (brain.dataSize > MaxDataSize)
brain.dataSize = 0;
brain.flags |= initModuleData.Flags;
}
}
void saveGame(const QString &fileName, bool autoSave)
{
int nLocal = 0;
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::Term)
++nLocal;
if (Database::difficulty[0] == 0)
nLocal = 0;
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(lxmax) * lymax, 0);
if (nLocal <= 1) {
for (int y = 0; y < Database::ly; ++y) {
for (int x = 0; x < Database::lx; ++x) {
const std::uint32_t tile =
(*Database::rw[0].Map)[(x + Database::saveMapCenterLoc + (Database::lx >> 1)) % Database::lx +
Database::lx * y];
saveMap[static_cast<std::size_t>(x + Database::lx * y)] =
static_cast<std::uint8_t>((tile & fTerrain) + ((tile & (fCity | fUnit | fOwned)) >> 16));
}
}
}
QDir().mkpath(QFileInfo(fileName).path());
QFile file(fileName);
const bool append = autoSave && autoSaveExists;
if (!file.open(append ? QIODevice::ReadWrite : (QIODevice::WriteOnly | QIODevice::Truncate)))
throw std::runtime_error(("Cannot open " + fileName + " for writing").toStdString());
file.seek(0);
auto writeInt32 = [&file](std::int32_t value) { file.write(reinterpret_cast<const char *>(&value), 4); };
file.write("cEvoBook", 8);
writeInt32(CevoVersion);
const qint64 exeTime = QFileInfo(QCoreApplication::applicationFilePath()).lastModified().toSecsSinceEpoch();
writeInt32(static_cast<std::int32_t>(exeTime));
writeInt32(Database::lx);
writeInt32(Database::ly);
writeInt32(Database::landMass);
if (Database::landMass == 0)
file.write(reinterpret_cast<const char *>(Database::realMap.data()), Database::mapSize * 4);
writeInt32(maxTurn);
writeInt32(Database::rnd);
writeInt32(Database::gTurn);
if (nLocal > 1) { // multiplayer game -- no quick view
writeInt32(0x80);
} else {
file.write(reinterpret_cast<const char *>(saveMap.data()), ((Database::mapSize - 1) / 4 + 1) * 4);
}
for (int i = 0; i < nPl; ++i) {
if (!playerBrain[i]) {
writeInt32(0);
continue;
}
assert(playersBrain[i]); // bix[i] can only be set if playersBrain[i] was
const QByteArray name = ((playersBrain[i]->kind == BrainType::Random || playersBrain[i]->kind == BrainType::AI)
? playerBrain[i]->fileName
: playersBrain[i]->fileName)
.toLatin1();
// Pascal shortstring-style encoding: 1 length byte + chars, zero-
// padded up to a total of (length div 4 + 1) * 4 bytes.
const int len = name.size();
QByteArray buffer((len / 4 + 1) * 4, '\0');
buffer[0] = static_cast<char>(len);
std::memcpy(buffer.data() + 1, name.constData(), static_cast<std::size_t>(len));
file.write(buffer);
writeInt32(originalDataVersion[i]);
file.write(QByteArray(4, '\0')); // "behavior" string - always empty, kept for on-disk compatibility
writeInt32(Database::difficulty[i]);
}
if (append)
Database::cl.appendToFile(file, autoSaveState);
else
Database::cl.saveToFile(file);
file.close();
if (autoSave) {
autoSaveState = Database::cl.state();
autoSaveExists = true;
}
}
void startGame()
{
for (int p1 = 0; p1 < nPl; ++p1) {
if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::SuperVirtual) {
playerBrain[p1] = brainTerm; // supervisor and local human use same module
} else if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::Random) {
if (brains.kindCount(BrainType::AI) == 0) {
playerBrain[p1] = nullptr;
} else {
const std::vector<Brain *> aiBrains = brains.getByKind(BrainType::AI);
playerBrain[p1] = aiBrains[static_cast<std::size_t>(Database::delphiRandom(static_cast<int>(aiBrains.size())))];
}
} else {
playerBrain[p1] = playersBrain[p1];
}
if (!playersBrain[p1])
Database::difficulty[p1] = -1;
}
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
std::array<bool, maxBrain> brainUsed{};
for (int p = 0; p < nPl; ++p) {
if (playerBrain[p] && (Database::mode != Database::moMovie || p == 0)) {
aiInfo[p] = playerBrain[p]->name();
initBrain(*playerBrain[p]);
if (Database::mode == Database::moPlaying) {
originalDataVersion[p] = playerBrain[p]->dataVersion;
Database::processClientData[p] = true;
} else {
Database::processClientData[p] =
Database::processClientData[p] && (originalDataVersion[p] == playerBrain[p]->dataVersion);
}
// NOTE: Term/Random/NetworkXxx brain kinds have no backing
// AiModule (no dylib to load) - until this port grows a real
// UI-side terminal-client bridge (StdIntf.pas equivalent,
// outside GameServer.pas's own scope), isLoaded() is always
// false for them, same as a failed-to-resolve Client in the
// original.
if (!playerBrain[p]->module.isLoaded()) {
if (playerBrain[0]->kind == BrainType::NoTerm) {
playerBrain[p] = nullptr;
} else {
playerBrain[p] = brainTerm;
originalDataVersion[p] = -1;
Database::processClientData[p] = false;
}
}
if (playerBrain[p])
brainUsed[static_cast<std::size_t>(brains.indexOf(playerBrain[p]))] = true;
}
}
notifyEvent(NotifyId::CreateWorld);
int nAlive = 0;
Database::gAlive = 0;
Database::gWatching = (Database::mode == Database::moMovie) ? 1 : 0;
Database::gAI = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1]) {
if (Database::mode != Database::moMovie)
Database::gWatching |= (1 << p1);
if (playerBrain[p1]->kind == BrainType::AI)
Database::gAI |= (1 << p1);
if (Database::difficulty[p1] > 0) {
Database::gAlive |= (1 << p1);
++nAlive;
}
Database::serverVersion[p1] = playerBrain[p1]->serverVersion;
}
}
winOnAlone = playerBrain[0]->kind == BrainType::NoTerm && nAlive > 1;
gWinner = 0;
gColdWarStart = -ColdWarTurns - 1;
uixSelectedTransport = -1;
spyMission = smSabotageProd;
debugMap.fill(nullptr);
Database::gTurn = 0;
for (TWonderInfo &wonder : Database::gWonder) {
wonder.CityID = -1;
wonder.EffectiveOwner = -1;
}
Database::gShip.fill(TShipInfo{});
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & (Database::gAlive | Database::gWatching)) == 0)
continue;
TPlayerContext &player = Database::rw[p];
player.Government = gDespotism;
player.Money = StartMoney;
player.TaxRate = 30;
player.LuxRate = 0;
player.Research = 0;
player.ResearchTech = -2;
player.AnarchyStart = -AnarchyTurns - 1;
player.Happened = 0;
Database::lastValidStat[p] = -1;
UnitProcessing::worked[p] = 0;
Database::founded[p] = 0;
devModelTurn[p] = -1;
player.OracleIncome = 0;
if (playerBrain[p]->dataSize > 0) {
savedData[p] = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
player.Data = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
} else {
player.Data = nullptr;
savedData[p] = nullptr;
}
player.nBattleHistory = 0;
player.BattleHistory = nullptr;
player.BorderHelper = nullptr;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p].assign(static_cast<std::size_t>(maxTurn + 1), 0);
if (playerBrain[p]->flags & fDotNet) {
// fDotNet brains are filtered out in init() - unreachable, kept
// only for structural fidelity with the original.
player.DefaultDebugMap =
reinterpret_cast<TIntList *>(new std::int32_t[static_cast<std::size_t>(Database::mapSize)]());
debugMap[p] = player.DefaultDebugMap;
} else {
player.DefaultDebugMap = nullptr;
}
}
if (Database::landMass > 0) { // random map
Database::initRandomGame();
previewElevation = false;
mapField.clear();
} else { // predefined map
if (Database::mode == Database::moPlaying) {
Map map;
map.loadFromFile(mapFileName);
Database::mapSize = map.mapSize();
Database::lx = map.size().x();
Database::ly = map.size().y();
std::copy(map.tiles.begin(), map.tiles.begin() + Database::mapSize, Database::realMap.begin());
}
mapField.assign(Database::realMap.begin(), Database::realMap.begin() + Database::mapSize);
int human = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::Term)
human |= (1 << p1);
Database::initMapGame(human);
}
CityProcessing::initGame();
UnitProcessing::initGame();
for (int p = 0; p < nPl; ++p)
if ((1 << p) & (Database::gAlive | Database::gWatching))
inform(p);
pTurn = -1;
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
TNewGameData game{};
game.lx = Database::lx;
game.ly = Database::ly;
game.LandMass = Database::landMass;
game.MaxTurn = maxTurn;
std::memcpy(game.Difficulty, Database::difficulty.data(), sizeof(game.Difficulty));
aiCredits.clear();
for (int i = 0; i < brains.count(); ++i) {
Brain &brain = brains[i];
if (!brain.initialized)
continue;
if (brainUsed[static_cast<std::size_t>(i)]) {
if (brain.kind == BrainType::AI)
notifyEvent(NotifyId::InitPlayers);
for (int p = 0; p < nPl; ++p) {
game.RO[p] = (brains.indexOf(playerBrain[p]) == i) ? &Database::rw[p] : nullptr;
game.SuperVisorRO[p] = (brain.kind == BrainType::Term && Database::difficulty[0] == 0 && playerBrain[p])
? &Database::rw[p]
: nullptr;
}
// DotNet AssemblyPath is unsupported by this port - always empty.
game.AssemblyPath[0] = '\0';
switch (Database::mode) {
case Database::moLoading:
case Database::moLoading_Fast:
callClient(i, cLoadGame, &game);
break;
case Database::moMovie:
callClient(i, cMovie, &game);
break;
case Database::moPlaying:
callClient(i, cNewGame, &game);
break;
}
if (brain.kind == BrainType::AI && !brain.credits.isEmpty()) {
if (aiCredits.isEmpty())
aiCredits = brain.credits;
else
aiCredits += QLatin1Char('\\') + brain.credits;
}
} else { // module no longer used -- unload
callClient(i, cReleaseModule, nullptr);
if (brain.kind == BrainType::AI && (brain.flags & fDotNet) == 0)
brain.module.unload();
brain.initialized = false;
}
}
if (playerBrain[0]->kind != BrainType::NoTerm) {
int brainUni = -1;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
if (brainUni == -1)
brainUni = brains.indexOf(playerBrain[p1]);
else if (brainUni != brains.indexOf(playerBrain[p1]))
brainUni = -2;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
notifyMessage = (brainUni == -2) ? playerBrain[p1]->fileName : QString();
notifyEvent(NotifyId::SetAiName, p1);
}
}
}
Database::checkBorders(-1);
Database::invalidTreatyMap = 0;
autoSaveExists = false;
pDipActive = -1;
pTurn = 0;
if (Database::mode >= Database::moMovie)
notifyEvent(NotifyId::EndInfo);
}
void endGame()
{
mapField.clear(); // only populated for predefined maps in this port
for (int p1 = 0; p1 < nPl; ++p1) {
if (!playerBrain[p1])
continue;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p1].clear();
TPlayerContext &player = Database::rw[p1];
delete[] reinterpret_cast<TBattle *>(player.BattleHistory);
player.BattleHistory = nullptr;
delete[] static_cast<std::uint32_t *>(player.Data);
player.Data = nullptr;
delete[] static_cast<std::uint32_t *>(savedData[p1]);
savedData[p1] = nullptr;
delete[] reinterpret_cast<std::int32_t *>(player.DefaultDebugMap);
player.DefaultDebugMap = nullptr;
}
UnitProcessing::releaseGame();
CityProcessing::releaseGame();
Database::releaseGame();
Database::cl = CmdList();
}
void generateStat(int p)
{
if (Database::difficulty[p] <= 0)
return;
TPlayerContext &player = Database::rw[p];
const int turn = Database::gTurn;
int statPop = 0;
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
statPop += city[cix].Size;
int statScience = Database::researched[p] * 50;
if (player.ResearchTech >= 0 && player.ResearchTech != adMilitary)
statScience += player.Research * 100 / Database::techBaseCost(Database::nTech[p], Database::difficulty[p]);
int statMil = 0;
const TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
if (un[uix].Loc < 0)
continue;
const TModel &m = model[un[uix].mix];
if (m.Kind <= mkEnemyDeveloped && un[uix].mix != 1)
statMil += m.Weight * m.MStrength * un[uix].Health / 100;
else if (m.Domain == dGround)
statMil += (m.Attack + 2 * m.Defense) * un[uix].Health / 100;
else
statMil += (m.Attack + m.Defense) * un[uix].Health / 100;
if (m.Kind == mkSlaves)
++statPop;
else if (m.Kind == mkSettler)
statPop += 2;
}
statMil /= 16;
stat[stPop][p][static_cast<std::size_t>(turn)] = statPop;
stat[stScience][p][static_cast<std::size_t>(turn)] = statScience;
stat[stMil][p][static_cast<std::size_t>(turn)] = statMil;
stat[stExplore][p][static_cast<std::size_t>(turn)] = Database::discovered[p];
stat[stTerritory][p][static_cast<std::size_t>(turn)] = Database::territoryCount[p];
stat[stWork][p][static_cast<std::size_t>(turn)] = UnitProcessing::worked[p];
Database::lastValidStat[p] = turn;
}
void logCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc < 0)
continue;
if (savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles) {
Database::cl.put(sSetCityTiles, pTurn, cix, &city[cix].Tiles);
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
}
}
void noLogCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
bool hasCityTileChanges()
{
const TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles)
return true;
return false;
}
void beforeTurn0()
{
TPlayerContext &player = Database::rw[pTurn];
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) // init movement points for first turn
un[uix].Movement = model[un[uix].mix].Speed;
if (Database::difficulty[pTurn] > 0) {
Database::discoverViewAreas(pTurn);
} else { // supervisor
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
}
}
void destroySpacePortTellPlayers(int p, int pCapturer)
{
// stop ship part production
TCity *city = *Database::rw[p].City;
for (int cix = 0; cix < Database::rw[p].nCity; ++cix) {
TCity &c = city[cix];
if (c.Loc >= 0 && (c.Project & cpImp) &&
((c.Project & cpIndex) == woMir || Imp[c.Project & cpIndex].Kind == ikShipPart)) {
Database::rw[p].Money += c.Prod0;
c.Prod = 0;
c.Prod0 = 0;
c.Project = cpImp + imTrGoods;
c.Project0 = cpImp + imTrGoods;
}
}
// destroy ship
TShipInfo &ship = Database::gShip[p];
if (ship.Parts[0] + ship.Parts[1] + ship.Parts[2] > 0) {
TShowShipChange showShipChange{};
for (int i = 0; i < nShipPart; ++i) {
showShipChange.Ship1Change[i] = -ship.Parts[i];
if (pCapturer >= 0) {
showShipChange.Ship2Change[i] = ship.Parts[i];
Database::gShip[pCapturer].Parts[i] += ship.Parts[i];
}
ship.Parts[i] = 0;
}
if (Database::mode >= Database::moMovie) {
showShipChange.Reason = pCapturer >= 0 ? scrCapture : scrDestruction;
showShipChange.Ship1Owner = p;
showShipChange.Ship2Owner = pCapturer;
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
}
}
void destroyCityTellPlayers(int p, int cix, bool saveUnits)
{
if ((*Database::rw[p].City)[cix].Built[imSpacePort] > 0)
destroySpacePortTellPlayers(p, -1);
Database::destroyCity(p, cix, saveUnits);
}
void changeCityOwnerTellPlayers(int pOld, int cixOld, int pNew)
{
if ((*Database::rw[pOld].City)[cixOld].Built[imSpacePort] > 0) {
if (Database::rw[pNew].NatBuilt[imSpacePort] > 0)
destroySpacePortTellPlayers(pOld, pNew);
else
destroySpacePortTellPlayers(pOld, -1);
}
Database::changeCityOwner(pOld, cixOld, pNew);
}
void checkWin(int p)
{
bool shipComplete = true;
for (int i = 0; i < nShipPart; ++i)
if (Database::gShip[p].Parts[i] < ShipNeed[i]) {
shipComplete = false;
break;
}
if (shipComplete)
gWinner |= (1 << p); // game won!
}
void beforeTurn()
{
assert((1 << pTurn) & (Database::gAlive | Database::gWatching));
if (((1 << pTurn) & Database::gAlive) == 0 && Database::difficulty[pTurn] > 0)
return;
TPlayerContext &player = Database::rw[pTurn];
if (Database::gWonder[woGrLibrary].EffectiveOwner == pTurn && gWinner == 0) { // check great library effect
int nAlive = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
++nAlive;
for (int ad = 0; ad <= nAdv - 5; ++ad) {
if (player.Tech[ad] < tsSeen) {
int nAppliers = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && Database::rw[p1].Tech[ad] >= tsApplicable)
++nAppliers;
if (nAppliers * 2 > nAlive) {
Database::seeTech(pTurn, ad);
++Database::nTech[pTurn];
if (Database::mode >= Database::moMovie)
callPlayer(cShowGreatLibTech, pTurn, &ad);
// do not call CallPlayer(pTurn) while map is invalid
}
}
}
}
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
bool mirBuilt = false;
if (Database::difficulty[pTurn] > 0 && gWinner == 0) {
if (player.nCity > 0) {
TCity *city0 = *player.City;
TUn *un0 = *player.Un;
const TModel *model0 = *player.Model;
for (int p1 = 0; p1 < nPl; ++p1) {
if (Database::gTurn != player.EvaStart[p1] + PeaceEvaTurns)
continue;
// peace contract -- remove all units from p1's territory
int loc1 = city0[0].Loc; // search destination for homeless units
for (int cix = 1; cix < player.nCity; ++cix)
if (city0[cix].Loc >= 0 && (loc1 < 0 || city0[cix].Built[imPalace] > 0))
loc1 = city0[cix].Loc;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &un = un0[uix];
if (un.Loc >= 0 && model0[un.mix].Kind != mkDiplomat && (un.Home >= 0 || loc1 >= 0) &&
(Database::realMap[un.Loc] >> 27) == static_cast<std::uint32_t>(p1)) {
const int oldLoc = un.Loc;
if (un.Master >= 0) { // transport unload
if (model0[un.mix].Domain == dAir)
--un0[un.Master].AirLoad;
else
--un0[un.Master].TroopLoad;
un.Master = -1;
} else {
Database::freeUnit(pTurn, uix);
}
un.Loc = un.Home >= 0 ? city0[un.Home].Loc : loc1;
Database::placeUnit(pTurn, uix);
Database::updateUnitMap(oldLoc);
Database::updateUnitMap(un.Loc);
un.Flags |= unWithdrawn;
player.Happened |= phPeaceEvacuation;
}
}
}
}
TShowShipChange showShipChange{};
bool tribeExtinct = true;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) { // city loop 1
TCity &c = city[cix];
if (c.Loc < 0)
continue;
// check for siege
int siegedTiles = 0;
Database::Vicinity21Loc radius;
Database::v21ToLoc(c.Loc, radius);
for (int v21 = 1; v21 <= 26; ++v21) {
if ((c.Tiles & (1u << v21) & ~(1u << Database::CityOwnTile)) == 0)
continue;
const int loc1 = radius[static_cast<std::size_t>(v21)];
assert(loc1 >= 0 && loc1 < Database::mapSize && Database::usedByCity[loc1] == c.Loc);
const auto p1 = static_cast<int>(Database::realMap[loc1] >> 27);
if ((Database::realMap[loc1] & fCity) ||
(p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) ||
(Database::zocMap[loc1] > 0 && Database::occupant[loc1] != pTurn &&
player.Treaty[Database::occupant[loc1]] < trPeace)) {
c.Tiles &= ~(1u << v21);
Database::usedByCity[loc1] = -1;
c.Flags |= chSiege;
++siegedTiles;
}
}
while (siegedTiles > 0) { // replace sieged tiles
if (!CityProcessing::addBestCityTile(pTurn, cix))
break;
--siegedTiles;
}
if ((c.Flags & chFounded) == 0) {
if (CityProcessing::cityTurn(pTurn, cix)) {
tribeExtinct = false;
} else { // city is erased
Database::removeDomainUnits(dSea, pTurn, c.Loc);
Database::removeDomainUnits(dAir, pTurn, c.Loc);
(*player.Map)[c.Loc] &= ~static_cast<std::uint32_t>(fCity); // !!! do this in inner core
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = c.Loc;
++nUpdateLoc;
destroyCityTellPlayers(pTurn, cix, true);
}
if ((c.Flags & chProduction) && (c.Project0 & cpImp)) {
if ((c.Project0 & cpIndex) == woMir)
mirBuilt = true;
else if ((c.Project0 & cpIndex) == woManhattan)
gColdWarStart = Database::gTurn;
else if (Imp[c.Project0 & cpIndex].Kind == ikShipPart) // ship parts produced
++showShipChange.Ship1Change[(c.Project0 & cpIndex) - imShipComp];
}
}
} // city loop 1
if (nUpdateLoc > 0) {
Database::checkBorders(-1, pTurn);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)], true);
if (Database::mode >= Database::moMovie)
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn)
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowCityChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
{
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 2
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (u.Health < 100)
UnitProcessing::recover(pTurn, uix);
if (u.Flags & unMountainDelay) {
u.Movement = 0;
u.Flags &= ~static_cast<decltype(u.Flags)>(unMountainDelay);
} else {
u.Movement = Database::unitSpeed(pTurn, u.mix, u.Health); // refresh movement
}
assert(u.Loc >= 0);
if (model[u.mix].Kind != mkDiplomat) { // check treaty violation
const auto p1 = static_cast<int>(Database::realMap[u.Loc] >> 27);
if (p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) {
if ((u.Job == jCity || u.Job == jPillage || u.Job == jClear || u.Job == jAfforest ||
u.Job == jTrans) ||
((u.Job == jIrr || u.Job == jMine || u.Job == jFort || u.Job == jBase) &&
(Database::realMap[u.Loc] & fTerImp)))
u.Job = jNone;
if (Database::gTurn > player.EvaStart[p1] + PeaceEvaTurns && player.Treaty[p1] != trAlliance) {
player.EvaStart[p1] = Database::gTurn;
player.Happened |= phPeaceViolation;
if (Database::mode >= Database::moMovie)
callPlayer(cShowPeaceViolation, p1, &pTurn);
}
}
}
if (Database::serverVersion[pTurn] >= 0x000EF0) {
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
}
}
}
if (Database::serverVersion[pTurn] < 0x000EF0) {
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 3
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // pollution - city loop 3
TCity *cityList = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (cityList[cix].Loc >= 0 && cityList[cix].Pollution >= MaxPollution)
CityProcessing::pollute(pTurn, cix);
}
Database::compactLists(pTurn);
if (player.nUn == 0 && player.nCity == 0) { // nation made extinct
player.Happened |= phExtinct;
Database::gAlive &= ~(1 << pTurn);
stat[stPop][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stMil][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stScience][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stExplore][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stTerritory][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stWork][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & (Database::gAlive | Database::gWatching)) == 0)
continue;
if (p1 != pTurn) {
Database::giveCivilReport(p1, pTurn);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p1] == 0 ||
Database::rw[p1].Treaty[pTurn] == trAlliance)
Database::giveMilReport(p1, pTurn);
}
TPlayerContext &other = Database::rw[p1];
other.Alive = Database::gAlive;
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
// remove territory of extinct nation from player maps
if ((*other.Territory)[loc1] == pTurn) {
(*other.Territory)[loc1] = -1;
(*other.Map)[loc1] &= ~static_cast<std::uint32_t>(fPeace);
}
}
return;
}
// check research
const int cost = Database::techCost(pTurn);
if (Database::gTestFlags & tfImmAdvance)
player.Research = cost;
if ((player.Happened & phTech) == 0 && player.Research >= cost) {
if (player.ResearchTech == adMilitary)
Database::enableDevModel(pTurn); // new Unit class initiated
else if (player.ResearchTech >= 0)
Database::discoverTech(pTurn, player.ResearchTech);
player.Research -= cost;
player.Happened |= phTech;
player.ResearchTech = -1;
} else if (player.ResearchTech == -2 && player.nCity > 0) {
player.Happened |= phTech;
player.ResearchTech = -1;
}
if (player.Credibility < player.MaxCredibility) {
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && player.Treaty[p1] >= trPeace) {
++player.Credibility;
break;
}
}
}
if (gWinner == 0)
checkWin(pTurn);
if (Database::mode >= Database::moMovie && gWinner == 0 &&
(showShipChange.Ship1Change[0] > 0 || showShipChange.Ship1Change[1] > 0 ||
showShipChange.Ship1Change[2] > 0)) {
showShipChange.Reason = scrProduction;
showShipChange.Ship1Owner = pTurn;
showShipChange.Ship2Owner = -1;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & (Database::gAlive | Database::gWatching))) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
if (winOnAlone && (Database::gAlive & ~((1 << pTurn) | 1)) == 0)
gWinner = 1 << pTurn; // break if only one nation left
if (Database::gTurn == player.AnarchyStart + AnarchyTurns) {
player.AnarchyStart = -AnarchyTurns - 1;
player.Government = gDespotism;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((Database::gAlive | Database::gWatching) & (1 << p1)))
Database::rw[p1].EnemyReport[pTurn]->Government = gDespotism;
player.Happened += phChangeGov;
}
} // if Difficulty[pTurn] > 0
if (pTurn == 0 && gWinner > 0) { // game over, give world map and all reports to player 0
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
if (player.Treaty[p1] < trNone) {
player.Treaty[p1] = trNone;
Database::rw[p1].Treaty[pTurn] = trNone;
}
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
} else {
// show observed areas
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0) { // supervisor - all tiles visible
if (playerBrain[pTurn]->kind != BrainType::NoTerm &&
(Database::difficulty[pTurn] > 0 || Database::mode > Database::moLoading_Fast))
Database::discoverAll(pTurn, Database::lObserveSuper);
} else {
Database::discoverViewAreas(pTurn);
if (mirBuilt)
Database::discoverAll(pTurn, Database::lObserveUnhidden);
}
}
}
void afterTurn()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc >= 0) {
city[cix].Flags &= (chCaptured | chDisorder);
CityProcessing::collectCityResources(pTurn, cix); // new style
}
}
player.Money += player.OracleIncome;
player.OracleIncome = 0;
if (Database::gWonder[woOracle].EffectiveOwner == pTurn) {
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gAlive) && (p1 == pTurn || player.Treaty[p1] > trNoContact)) {
const TCity *otherCity = *Database::rw[p1].City;
for (int cix = 0; cix < Database::rw[p1].nCity; ++cix)
if (otherCity[cix].Loc >= 0 && otherCity[cix].Built[imTemple] > 0)
++player.OracleIncome;
}
}
if ((Database::gTestFlags & tfImmImprove) == 0 && player.Government != gAnarchy)
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && (city[cix].Flags & chCaptured) == 0)
CityProcessing::payCityMaintenance(pTurn, cix);
if (Database::serverVersion[pTurn] >= 0x000EF0) { // let settlers work
for (int cix = 0; cix < player.nCity; ++cix)
city[cix].Flags &= ~static_cast<decltype(city[cix].Flags)>(chFounded);
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // next turn for all units
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (model[u.mix].Domain == dAir) {
if (u.Master >= 0 || (Database::realMap[u.Loc] & fCity) ||
(Database::realMap[u.Loc] & fTerImp) == tiBase) {
u.Fuel = static_cast<decltype(u.Fuel)>(model[u.mix].Cap[mcFuel]);
u.Flags |= unBombsLoaded;
} else if (model[u.mix].Kind == mkSpecial_Glider) { // glider
if ((Database::realMap[u.Loc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phGliderLost;
}
} else {
--u.Fuel;
if (u.Fuel < 0) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phPlaneLost;
}
}
} else if (u.Master < 0 && u.Movement > 0) { // check HostileDamage
u.Health = static_cast<decltype(u.Health)>(
u.Health - UnitProcessing::hostileDamage(pTurn, u.mix, u.Loc, u.Movement));
if (u.Health < 0)
Database::removeUnitUpdateMap(pTurn, uix);
}
} // unit loop 1
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
u.Flags &= ~static_cast<decltype(u.Flags)>(unWithdrawn);
if (u.Loc >= 0 && model[u.mix].Domain == dGround && u.Master < 0 &&
(static_cast<int>(u.Movement) == model[u.mix].Speed ||
(model[u.mix].Cap[mcAcademy] > 0 && u.Movement * 2 >= model[u.mix].Speed)))
u.Flags |= unFortified; // fortify unmoved units
}
}
if ((Database::gTestFlags & tfUncover) == 0 && Database::difficulty[pTurn] > 0) {
// restrict view area to current positions
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
Database::discoverViewAreas(pTurn);
}
if (gWinner == 0)
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
checkWin(p1);
}
void nextPlayerImpl()
{
if (Database::gTurn == 0)
beforeTurn0();
else
beforeTurn();
noLogCityTileChanges();
generateStat(pTurn);
inform(pTurn);
changeClient();
}
int executeMove(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
if (un.Master < 0)
Database::freeUnit(p, uix);
if ((moveInfo.MoveType == UnitProcessing::mtMove || moveInfo.MoveType == UnitProcessing::mtCapture) &&
moveInfo.MountainDelay)
un.Flags |= unMountainDelay;
un.Loc = -2;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc >= 0 && allUn[i].Master == uix)
allUn[i].Loc = -2;
}
Database::updateUnitMap(fromLoc);
if (Database::mode >= Database::moMovie) { // show move in interface modules
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = -1;
if (un.Master >= 0) {
if ((*player.Model)[(*player.Un)[un.Master].mix].Domain == dAir)
showMove.Flags |= umPlaneUnloading;
else
showMove.Flags |= umShipUnloading;
}
if (moveInfo.ToMaster >= 0) {
if ((*player.Model)[(*player.Un)[moveInfo.ToMaster].mix].Domain == dAir)
showMove.Flags |= umPlaneLoading;
else
showMove.Flags |= umShipLoading;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(moveInfo.MoveType == UnitProcessing::mtCapture ? cShowCapturing : cShowMoving, p1,
&showMove);
} else if (seeFrom) {
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
}
}
}
if (moveInfo.MoveType != UnitProcessing::mtSpyMission)
un.Loc = toLoc;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc == -2)
allUn[i].Loc = toLoc;
}
bool extDiscover = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
if (moveInfo.MoveType == UnitProcessing::mtCapture) {
assert(Database::occupant[toLoc] < 0);
TPlayerContext &defender = Database::rw[moveInfo.Defender];
TUn *defUn = *defender.Un;
for (int uix1 = 0; uix1 < defender.nUn; ++uix1) {
if (defUn[uix1].Loc >= 0 && defUn[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
if ((*defender.City)[moveInfo.Dcix].Size > 2 && player.nCity < nCmax) { // city captured
changeCityOwnerTellPlayers(moveInfo.Defender, moveInfo.Dcix, p);
TCity &newCity = (*player.City)[player.nCity - 1];
newCity.Flags = static_cast<decltype(newCity.Flags)>(CaptureTurns << 16);
CityProcessing::cityShrink(p, player.nCity - 1);
if (Database::mode == Database::moPlaying)
savedTiles[static_cast<std::size_t>(player.nCity - 1)] = newCity.Tiles;
extDiscover = true;
// Temple of Zeus effect
if (Database::gWonder[woZeus].EffectiveOwner == p) {
Database::giveCivilReport(p, moveInfo.Defender);
for (int i = 0; i < nAdv; ++i) {
if (!IsFutureTech(i) && player.Tech[i] < tsSeen && defender.Tech[i] >= tsApplicable) {
player.Happened |= phStealTech;
gStealFrom = moveInfo.Defender;
break;
}
}
}
if (Database::mode == Database::moPlaying)
Database::logCheckBorders(p, player.nCity - 1, moveInfo.Defender);
// territory should not be considered for the rest of the command
// execution, because during loading a game it's incorrect before
// subsequent sIntExpandTerritory is processed
} else { // city destroyed
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
}
Database::recalcPeaceMap(p);
if (Database::mode >= Database::moMovie)
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
} // if MoveInfo.MoveType = mtCapture
if (moveInfo.MoveType == UnitProcessing::mtSpyMission) {
std::uint32_t missionResult = Database::doSpyMission(p, moveInfo.Defender, moveInfo.Dcix, spyMission);
if (Database::mode == Database::moPlaying && spyMission == smStealForeignReports)
callPlayer(cShowMissionResult, p, &missionResult);
}
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Movement = static_cast<decltype(un.Movement)>(un.Movement - moveInfo.Cost);
// transport unload
if (un.Master >= 0) {
if (model.Domain == dAir)
--(*player.Un)[un.Master].AirLoad;
else {
--(*player.Un)[un.Master].TroopLoad;
assert(un.Movement <= 0);
}
un.Master = -1;
}
if (un.Health <= 0 || moveInfo.MoveType == UnitProcessing::mtSpyMission) {
Database::removeUnit(p, uix); // spy mission or victim of HostileDamage
} else { // transport load
un.Master = moveInfo.ToMaster;
if (moveInfo.ToMaster >= 0) {
if (model.Domain == dAir)
++(*player.Un)[moveInfo.ToMaster].AirLoad;
else
++(*player.Un)[moveInfo.ToMaster].TroopLoad;
} else {
Database::placeUnit(p, uix);
}
}
if (moveInfo.MoveType == UnitProcessing::mtCapture && nUpdateLoc > 0)
Database::recalcMapZoC(p);
Database::updateUnitMap(toLoc, moveInfo.MoveType == UnitProcessing::mtCapture);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (moveInfo.MoveType != UnitProcessing::mtSpyMission && un.Master < 0) {
if (model.Kind == mkDiplomat || model.Domain == dAir ||
model.Cap[mcRadar] + model.Cap[mcCarrier] + model.Cap[mcAcademy] > 0 ||
(Database::realMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains) ||
(Database::realMap[toLoc] & fTerImp) == tiFort || (Database::realMap[toLoc] & fTerImp) == tiBase)
extDiscover = true;
std::uint32_t level;
if (model.Kind == mkDiplomat || model.Cap[mcSpy] > 0)
level = Database::lObserveSuper;
else if (model.Domain == dAir || model.Cap[mcRadar] + model.Cap[mcCarrier] > 0)
level = Database::lObserveAll;
else
level = Database::lObserveUnhidden;
if (extDiscover) {
if (Database::discover21(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
} else {
if (Database::discover9(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
}
}
if (Database::mode >= Database::moMovie) { // show after-move in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeTo && moveInfo.MoveType == UnitProcessing::mtCapture)
callPlayer(cShowCityChanged, p1, &toLoc);
if (seeFrom && seeTo)
callPlayer(cShowAfterMove, p1, &toLoc);
else if (moveInfo.MoveType != UnitProcessing::mtSpyMission && seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowUnitChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
}
}
return result;
}
void ensureBattleHistoryCapacity(TPlayerContext &player)
{
if (player.nBattleHistory == 0) {
player.BattleHistory = reinterpret_cast<TBattleList *>(new TBattle[16]());
} else if (player.nBattleHistory >= 16 && (player.nBattleHistory & (player.nBattleHistory - 1)) == 0) {
TBattle *oldArr = reinterpret_cast<TBattle *>(player.BattleHistory);
auto *newArr = new TBattle[static_cast<std::size_t>(player.nBattleHistory) * 2]();
std::copy(oldArr, oldArr + player.nBattleHistory, newArr);
delete[] oldArr;
player.BattleHistory = reinterpret_cast<TBattleList *>(newArr);
}
}
void writeBattleHistory(int toLoc, int fromLoc, int attacker, int defender, int mixAttacker, int mixDefender,
bool attackerLost, bool defenderLost)
{
TPlayerContext &attackerPlayer = Database::rw[attacker];
ensureBattleHistoryCapacity(attackerPlayer);
TBattle &attackerBattle = (*attackerPlayer.BattleHistory)[attackerPlayer.nBattleHistory];
++attackerPlayer.nBattleHistory;
TPlayerContext &defenderPlayer = Database::rw[defender];
ensureBattleHistoryCapacity(defenderPlayer);
TBattle &defenderBattle = (*defenderPlayer.BattleHistory)[defenderPlayer.nBattleHistory];
++defenderPlayer.nBattleHistory;
attackerBattle.Enemy = static_cast<std::uint8_t>(defender);
attackerBattle.Flags = 0;
attackerBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
attackerBattle.mix = static_cast<std::uint16_t>(mixAttacker);
attackerBattle.mixEnemy = static_cast<std::uint16_t>(mixDefender);
attackerBattle.ToLoc = toLoc;
attackerBattle.FromLoc = fromLoc;
defenderBattle.Enemy = static_cast<std::uint8_t>(attacker);
defenderBattle.Flags = bhEnemyAttack;
defenderBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
defenderBattle.mix = static_cast<std::uint16_t>(mixDefender);
defenderBattle.mixEnemy = static_cast<std::uint16_t>(mixAttacker);
defenderBattle.ToLoc = toLoc;
defenderBattle.FromLoc = fromLoc;
if (attackerLost) {
attackerBattle.Flags |= bhMyUnitLost;
defenderBattle.Flags |= bhEnemyUnitLost;
}
if (defenderLost) {
attackerBattle.Flags |= bhEnemyUnitLost;
defenderBattle.Flags |= bhMyUnitLost;
}
}
int executeAttack(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = moveInfo.EndHealthDef;
if (moveInfo.MoveType == UnitProcessing::mtAttack)
writeBattleHistory(toLoc, fromLoc, p, moveInfo.Defender, un.mix, (*Database::rw[moveInfo.Defender].Un)[moveInfo.Duix].mix,
moveInfo.EndHealth <= 0, moveInfo.EndHealthDef <= 0);
if (Database::mode >= Database::moMovie) { // show attack in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(cShowAttacking, p1, &showMove);
}
}
}
}
bool loseCityPop = false;
TPlayerContext *defenderPlayer = (moveInfo.Defender >= 0) ? &Database::rw[moveInfo.Defender] : nullptr;
TCity *defenderCity = defenderPlayer ? &(*defenderPlayer->City)[moveInfo.Dcix] : nullptr;
if ((Database::realMap[toLoc] & fCity) &&
((moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef <= 0) ||
(moveInfo.MoveType == UnitProcessing::mtBombard &&
(BombardmentDestroysCity || defenderCity->Size > 2)))) {
switch (model.Domain) {
case dGround:
loseCityPop = model.Cap[mcArtillery] > 0 ||
(defenderCity->Built[imWalls] == 0 &&
Database::continent[toLoc] != Database::grWallContinent[moveInfo.Defender]);
break;
case dSea:
loseCityPop = defenderCity->Built[imCoastalFort] == 0;
break;
case dAir:
loseCityPop = defenderCity->Built[imMissileBat] == 0;
break;
default:
break;
}
}
const bool cityDestroyed = loseCityPop && defenderCity && defenderCity->Size <= 2;
if (moveInfo.MoveType == UnitProcessing::mtBombard) {
assert(un.Movement >= 100);
if (model.Attack == 0)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Movement -= 100;
} else if (moveInfo.MoveType == UnitProcessing::mtExpel) {
assert(un.Movement >= 100);
un.Job = jNone;
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
un.Movement -= 100;
} else {
assert(moveInfo.MoveType == UnitProcessing::mtAttack);
if (moveInfo.EndHealth == 0) {
Database::removeUnit(p, uix, moveInfo.Defender); // destroy attacker
} else { // update attacker
const int expGain = (un.Health - moveInfo.EndHealth + 1) >> 1;
if (un.Exp + expGain > (nExp - 1) * ExpCost)
un.Exp = static_cast<decltype(un.Exp)>((nExp - 1) * ExpCost);
else
un.Exp = static_cast<decltype(un.Exp)>(un.Exp + expGain);
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Job = jNone;
if ((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Domain < dAir)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
if (un.Movement > 100)
un.Movement -= 100;
else
un.Movement = 0;
}
}
bool zocDefenderDestroyed = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
int expelToLoc = -1;
if (moveInfo.MoveType == UnitProcessing::mtExpel) { // expel friendly unit
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
TCity *defCity = *defenderPlayer->City;
if (defUn.Home >= 0) {
expelToLoc = defCity[defUn.Home].Loc;
} else {
expelToLoc = defCity[0].Loc; // search destination for homeless units
for (int cix1 = 1; cix1 < defenderPlayer->nCity; ++cix1)
if (defCity[cix1].Loc >= 0 && (expelToLoc < 0 || defCity[cix1].Built[imPalace] > 0))
expelToLoc = defCity[cix1].Loc;
}
if (expelToLoc >= 0) {
Database::freeUnit(moveInfo.Defender, moveInfo.Duix);
defUn.Loc = expelToLoc;
Database::placeUnit(moveInfo.Defender, moveInfo.Duix);
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn.Loc;
++nUpdateLoc;
defUn.Flags |= unWithdrawn;
}
} else if (moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef > 0) { // update defender
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
const int expGain = (defUn.Health - moveInfo.EndHealthDef + 1) >> 1;
if (defUn.Exp + expGain > (nExp - 1) * ExpCost)
defUn.Exp = static_cast<decltype(defUn.Exp)>((nExp - 1) * ExpCost);
else
defUn.Exp = static_cast<decltype(defUn.Exp)>(defUn.Exp + expGain);
defUn.Health = static_cast<decltype(defUn.Health)>(moveInfo.EndHealthDef);
} else { // destroy defenders
if (moveInfo.MoveType != UnitProcessing::mtBombard) {
zocDefenderDestroyed =
((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Flags & mdZOC) != 0;
if ((((Database::realMap[toLoc] & fCity) == 0) && ((Database::realMap[toLoc] & fTerImp) != tiBase) &&
((Database::realMap[toLoc] & fTerImp) != tiFort)) ||
(loseCityPop && defenderCity->Size == 2)) // no city, base or fortress
Database::removeAllUnits(moveInfo.Defender, toLoc, p);
else
Database::removeUnit(moveInfo.Defender, moveInfo.Duix, p);
}
if (loseCityPop) { // city defender defeated -- shrink city
if (!cityDestroyed) {
CityProcessing::cityShrink(moveInfo.Defender, moveInfo.Dcix);
} else {
TUn *defUnits = *defenderPlayer->Un;
for (int uix1 = 0; uix1 < defenderPlayer->nUn; ++uix1) {
if (defUnits[uix1].Loc >= 0 && defUnits[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUnits[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
Database::recalcPeaceMap(p);
}
}
}
if (cityDestroyed && nUpdateLoc > 0)
Database::recalcMapZoC(p);
else if (zocDefenderDestroyed)
Database::recalcV8ZoC(p, toLoc);
Database::updateUnitMap(fromLoc);
Database::updateUnitMap(toLoc, loseCityPop);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (Database::mode >= Database::moMovie) {
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
for (int p1 = 0; p1 < nPl; ++p1) { // show after-attack in interface modules
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeTo && cityDestroyed)
callPlayer(cShowCityChanged, p1, &toLoc); // city was destroyed
if (seeFrom && seeTo) {
callPlayer(cShowAfterAttack, p1, &toLoc);
callPlayer(cShowAfterAttack, p1, &fromLoc);
} else {
if (seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
if (seeFrom)
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
if (seeTo && moveInfo.MoveType == UnitProcessing::mtExpel && expelToLoc >= 0)
callPlayer(cShowUnitChanged, p1, &expelToLoc);
}
}
}
return result;
}
int moveUnit(int p, int uix, int dx, int dy, bool testOnly)
{
assert(((1 << p) & Database::invalidTreatyMap) == 0);
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const int toLoc = Database::dLoc(un.Loc, dx, dy);
if (toLoc < 0 || toLoc >= Database::mapSize)
return eInvalid;
UnitProcessing::TMoveInfo moveInfo;
int result = UnitProcessing::calculateMove(p, uix, toLoc, 3 - (dy & 1), testOnly, moveInfo);
if (result == eZOC_EnemySpotted)
zocTile = toLoc;
if (result >= rExecuted && !testOnly) {
TShowMove showMove{};
showMove.dx = dx;
showMove.dy = dy;
showMove.FromLoc = un.Loc;
showMove.mix = un.mix;
showMove.Health = un.Health;
showMove.Fuel = un.Fuel;
showMove.Exp = un.Exp;
showMove.Load = un.TroopLoad + un.AirLoad;
showMove.Owner = p;
showMove.Flags = (un.TroopLoad > 0 || un.AirLoad > 0) ? unMulti : 0;
switch (moveInfo.MoveType) {
case UnitProcessing::mtCapture:
showMove.Flags |= umCapturing;
break;
case UnitProcessing::mtSpyMission:
showMove.Flags |= umSpyMission;
break;
case UnitProcessing::mtBombard:
showMove.Flags |= umBombarding;
break;
case UnitProcessing::mtExpel:
showMove.Flags |= umExpelling;
break;
default:
break;
}
switch (moveInfo.MoveType) {
case UnitProcessing::mtMove:
case UnitProcessing::mtCapture:
case UnitProcessing::mtSpyMission:
result = executeMove(p, uix, toLoc, moveInfo, showMove) | result;
break;
case UnitProcessing::mtAttack:
case UnitProcessing::mtBombard:
case UnitProcessing::mtExpel:
result = executeAttack(p, uix, toLoc, moveInfo, showMove) | result;
break;
default:
break;
}
}
return result;
}
int countPrice(const TOffer &offer, std::uint32_t priceType)
{
int result = 0;
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i)
if ((static_cast<std::uint32_t>(offer.Price[i]) & 0xFFFF0000u) == priceType)
++result;
return result;
}
// Equivalent of GameServer.pas's Server() - the client-to-server command
// dispatcher. FULLY PORTED: Info Request, Map Editor (except sRandomMap,
// which needs the still-deferred procedural map generator), Client
// Deactivation (incl. the sTurn turn-advance logic), Diplomacy, General,
// Model Related, Unit Related, Settlers Related, and City Related command
// groups are all implemented. Unrecognized commands fall through to the
// cClientEx/eUnknown default, matching the original's own `else` branch.
int CEVO_ABI_CALL server(int command, int player, int subject, void *data)
{
if (command == sTurn) {
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != player && ((1 << p1) & Database::gWatching)) {
int none = -1;
callPlayer(cShowTurnChange, p1, &none);
}
}
assert(Database::mapSize == Database::lx * Database::ly);
if (command < 0 || command >= 0x10000)
return eUnknown;
if (player < 0 || player >= nPl ||
(((command & (sctMask | sExecute)) != sctInfo) && (subject < 0 || subject >= 0x1000)))
return eInvalid;
if (((1 << player) & (Database::gAlive | Database::gWatching)) == 0 &&
!(command == sTurn || command == sBreak || command == sResign || command == sGetAIInfo ||
command == sGetAICredits || command == sGetVersion || (command & 0xFF0F) == sGetChart)) {
putMessage((1 << 16) + 1, QStringLiteral("NOT Alive: %1").arg(player));
return eNoTurn;
}
int result = eOK;
// check if command allowed now
if (Database::mode == Database::moPlaying &&
!(command >= cClientEx || command == sMessage || command == sSetDebugMap || command == sGetDebugMap ||
command == sGetAIInfo || command == sGetAICredits || command == sGetVersion || command == sGetTechCost ||
command == sGetDefender || command == sGetUnitReport || command == sGetCityReport ||
command == sGetCityTileInfo || command == sGetCity || command == sGetEnemyCityReport ||
command == sGetEnemyCityAreaInfo || command == sGetCityReportNew || (command & 0xFF0F) == sGetChart ||
(command & 0xFF0F) == sSetAttitude) && // commands always allowed
!(player == pTurn && command < 0x1000) && // info request always allowed for pTurn
!((pDipActive < 0 && player != pTurn) || (pDipActive >= 0 && player != pDipActive) ||
(pDipActive >= 0 && (command & sctMask) != sctEndClient))) { // no nego command
putMessage((1 << 16) + 1, QStringLiteral("No Turn: %1 calls %2").arg(player).arg(command >> 4, 0, 16));
return eNoTurn;
}
// do not return hereafter!
CmdListState formerClState{};
bool logged = false;
if (Database::mode == Database::moPlaying && command >= sExecute &&
((command & sctMask) != sctEndClient || command == sTurn) && (command & sctMask) != sctModel &&
command != sCancelTreaty && command != sSetCityTiles && command != sBuyCityProject &&
(command < cClientEx || Database::processClientData[player])) { // log command
formerClState = Database::cl.state();
Database::cl.put(command, player, subject, data);
logged = true;
}
switch (command) {
// --- Info Request Commands ---
case sMessage:
playerBrain[0]->module.call(cDebugMessage, subject, data);
break;
case sSetDebugMap:
debugMap[player] = data;
break;
case sGetDebugMap:
*static_cast<void **>(data) = debugMap[subject];
break;
case sRefreshDebugMap:
playerBrain[0]->module.call(cRefreshDebugMap, -1, &player);
break;
case sGetChart + 0 * 0x10:
case sGetChart + 1 * 0x10:
case sGetChart + 2 * 0x10:
case sGetChart + 3 * 0x10:
case sGetChart + 4 * 0x10:
case sGetChart + 5 * 0x10: {
if (subject >= 0 && subject < nPl && playerBrain[subject]) {
int stopTurn = 0;
if (Database::difficulty[player] == 0 || (Database::gTestFlags & tfUncover) || subject == player ||
gWinner > 0 || (((1 << subject) & Database::gAlive) == 0)) // chart of extinct nation
stopTurn = (subject > player) ? Database::gTurn : Database::gTurn + 1;
else if (Database::rw[player].Treaty[subject] > trNoContact)
stopTurn = ((command >> 4) & 0xF) == stMil
? Database::rw[player].EnemyReport[subject]->TurnOfMilReport + 1
: Database::rw[player].EnemyReport[subject]->TurnOfCivilReport + 1;
const int statIndex = (command >> 4) & 0xF;
auto *chart = static_cast<std::int32_t *>(data);
std::memcpy(chart, stat[static_cast<std::size_t>(statIndex)][subject].data(),
static_cast<std::size_t>(stopTurn) * sizeof(std::int32_t));
std::memset(chart + stopTurn, 0,
static_cast<std::size_t>(Database::gTurn - stopTurn) * sizeof(std::int32_t));
} else {
result = eInvalid;
}
break;
}
case sGetTechCost:
*static_cast<int *>(data) = Database::techCost(player);
break;
case sGetAIInfo:
aiInfoUtf8Cache = aiInfo[subject].toUtf8();
*static_cast<const char **>(data) = aiInfo[subject].isEmpty() ? nullptr : aiInfoUtf8Cache.constData();
break;
case sGetAICredits:
aiCreditsUtf8Cache = aiCredits.toUtf8();
*static_cast<const char **>(data) = aiCredits.isEmpty() ? nullptr : aiCreditsUtf8Cache.constData();
break;
case sGetVersion:
*static_cast<int *>(data) = CevoVersion;
break;
case sGetGameChanged:
if (player != 0)
result = eInvalid;
else if (Database::cl.state().nLog == nLogOpened && Database::cl.state().moveCode == 0 &&
!hasCityTileChanges() && !hasChanges(player))
result = eNotChanged;
break;
case sGetTileInfo:
if (subject >= 0 && subject < Database::mapSize)
result = Database::getTileInfo(player, -2, subject, *static_cast<TTileInfo *>(data));
else
result = eInvalid;
break;
case sGetCityTileInfo:
if (subject >= 0 && subject < Database::mapSize)
result = Database::getTileInfo(player, -1, subject, *static_cast<TTileInfo *>(data));
else
result = eInvalid;
break;
case sGetHypoCityTileInfo: {
if (subject < 0 || subject >= Database::mapSize) {
result = eInvalid;
break;
}
TTileInfo &info = *static_cast<TTileInfo *>(data);
if (info.ExplCity < 0 || info.ExplCity >= Database::rw[player].nCity)
result = eInvalid;
else if (((Database::observeLevel[subject] >> (player * 2)) & 3) == 0)
result = eNoPreq;
else
result = Database::getTileInfo(player, info.ExplCity, subject, info);
break;
}
case sGetJobProgress:
if (subject >= 0 && subject < Database::mapSize) {
if (((Database::observeLevel[subject] >> (player * 2)) & 3) == 0)
result = eNoPreq;
else
result = UnitProcessing::getJobProgress(player, subject, *static_cast<TJobProgressData *>(data));
} else {
result = eInvalid;
}
break;
case sGetModels:
if ((Database::gTestFlags & tfUncover) || Database::difficulty[player] == 0) { // supervisor only command
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != player && ((1 << p1) & Database::gAlive))
for (int mix = 0; mix < Database::rw[p1].nModel; ++mix)
Database::tellAboutModel(player, p1, mix);
} else {
result = eInvalid;
}
break;
case sGetUnits:
if (subject >= 0 && subject < Database::mapSize &&
((Database::observeLevel[subject] >> (player * 2)) & 3) == Database::lObserveSuper)
*static_cast<int *>(data) = Database::getUnitStack(player, subject);
else
result = eNoPreq;
break;
case sGetDefender:
if (subject >= 0 && subject < Database::mapSize && Database::occupant[subject] == player) {
int bonus = 0;
int cnt = 0;
int strength = 0;
Database::strongest(subject, *static_cast<int *>(data), strength, bonus, cnt);
} else {
result = eInvalid;
}
break;
case sGetBattleForecast:
case sGetBattleForecastEx: {
auto &forecast = *static_cast<TBattleForecast *>(data);
if (subject >= 0 && subject < Database::mapSize &&
(Database::observeLevel[subject] & (3 << (player * 2))) &&
((1 << forecast.pAtt) & Database::gAlive) && forecast.mixAtt >= 0 &&
forecast.mixAtt < Database::rw[forecast.pAtt].nModel &&
(forecast.pAtt == player || Database::rwemix[player][forecast.pAtt][forecast.mixAtt] >= 0)) {
int duix = 0;
int dcix = 0;
int aStr = 0;
int dStr = 0;
int aBaseDamage = 0;
int dBaseDamage = 0;
result = UnitProcessing::getBattleForecast(subject, forecast, duix, dcix, aStr, dStr, aBaseDamage,
dBaseDamage);
if (command == sGetBattleForecastEx) {
auto &forecastEx = *static_cast<TBattleForecastEx *>(data);
forecastEx.AStr = (aStr + 200) / 400;
forecastEx.DStr = (dStr + 200) / 400;
forecastEx.ABaseDamage = aBaseDamage;
forecastEx.DBaseDamage = dBaseDamage;
}
if (result == eOK)
result = eInvalid; // no enemy unit there!
} else {
result = eInvalid;
}
break;
}
case sGetUnitReport:
if (subject < 0 || subject >= Database::rw[player].nUn || (*Database::rw[player].Un)[subject].Loc < 0)
result = eInvalid;
else
Database::getUnitReport(player, subject, *static_cast<TUnitReport *>(data));
break;
case sGetMoveAdvice:
if (subject < 0 || subject >= Database::rw[player].nUn || (*Database::rw[player].Un)[subject].Loc < 0)
result = eInvalid;
else
result = UnitProcessing::getMoveAdvice(player, subject, *static_cast<TMoveAdviceData *>(data));
break;
case sGetPlaneReturn:
if (subject < 0 || subject >= Database::rw[player].nUn || (*Database::rw[player].Un)[subject].Loc < 0 ||
(*Database::rw[player].Model)[(*Database::rw[player].Un)[subject].mix].Domain != dAir)
result = eInvalid;
else
result = UnitProcessing::canPlaneReturn(player, subject, *static_cast<TPlaneReturnData *>(data)) ? eOK
: eNoWay;
break;
case sGetCity:
if (subject >= 0 && subject < Database::mapSize &&
((Database::observeLevel[subject] >> (player * 2)) & 3) == Database::lObserveSuper &&
(Database::realMap[subject] & fCity)) {
auto &getCityData = *static_cast<TGetCityData *>(data);
getCityData.Owner = player;
int cix1 = 0;
Database::searchCity(subject, getCityData.Owner, cix1);
getCityData.C = (*Database::rw[getCityData.Owner].City)[cix1];
if (getCityData.Owner != player && (getCityData.C.Project & cpImp) == 0)
Database::tellAboutModel(player, getCityData.Owner, getCityData.C.Project & cpIndex);
} else {
result = eInvalid;
}
break;
case sGetCityReport:
if (subject < 0 || subject >= Database::rw[player].nCity || (*Database::rw[player].City)[subject].Loc < 0)
result = eInvalid;
else
result = CityProcessing::getCityReport(player, subject, *static_cast<TCityReport *>(data));
break;
case sGetCityReportNew:
if (subject < 0 || subject >= Database::rw[player].nCity || (*Database::rw[player].City)[subject].Loc < 0)
result = eInvalid;
else
CityProcessing::getCityReportNew(player, subject, *static_cast<TCityReportNew *>(data));
break;
case sGetCityAreaInfo:
if (subject < 0 || subject >= Database::rw[player].nCity || (*Database::rw[player].City)[subject].Loc < 0)
result = eInvalid;
else
CityProcessing::getCityAreaInfo(player, (*Database::rw[player].City)[subject].Loc,
*static_cast<TCityAreaInfo *>(data));
break;
case sGetEnemyCityReport:
if (subject >= 0 && subject < Database::mapSize &&
((Database::observeLevel[subject] >> (player * 2)) & 3) == Database::lObserveSuper &&
(Database::realMap[subject] & fCity)) {
int p1 = Database::occupant[subject];
if (p1 < 0)
p1 = 1;
int cix1 = 0;
Database::searchCity(subject, p1, cix1);
auto &cityReport = *static_cast<TCityReport *>(data);
cityReport.HypoTiles = -1;
cityReport.HypoTax = -1;
cityReport.HypoLux = -1;
CityProcessing::getCityReport(p1, cix1, cityReport);
} else {
result = eInvalid;
}
break;
case sGetEnemyCityReportNew:
if (subject >= 0 && subject < Database::mapSize &&
((Database::observeLevel[subject] >> (player * 2)) & 3) == Database::lObserveSuper &&
(Database::realMap[subject] & fCity)) {
int p1 = Database::occupant[subject];
if (p1 < 0)
p1 = 1;
int cix1 = 0;
Database::searchCity(subject, p1, cix1);
auto &cityReportNew = *static_cast<TCityReportNew *>(data);
cityReportNew.HypoTiles = -1;
cityReportNew.HypoTaxRate = -1;
cityReportNew.HypoLuxuryRate = -1;
CityProcessing::getCityReportNew(p1, cix1, cityReportNew);
} else {
result = eInvalid;
}
break;
case sGetEnemyCityAreaInfo:
if (subject >= 0 && subject < Database::mapSize &&
((Database::observeLevel[subject] >> (player * 2)) & 3) == Database::lObserveSuper &&
(Database::realMap[subject] & fCity)) {
int p1 = Database::occupant[subject];
if (p1 < 0)
p1 = 1;
int cix1 = 0;
Database::searchCity(subject, p1, cix1);
CityProcessing::getCityAreaInfo(p1, subject, *static_cast<TCityAreaInfo *>(data));
} else {
result = eInvalid;
}
break;
case sGetCityTileAdvice:
if (subject < 0 || subject >= Database::rw[player].nCity || (*Database::rw[player].City)[subject].Loc < 0)
result = eInvalid;
else
CityProcessing::getCityTileAdvice(player, subject, *static_cast<TCityTileAdviceData *>(data));
break;
// --- Map Editor Commands ---
case sEditTile:
if (player == 0) {
auto &editTileData = *static_cast<TEditTileData *>(data);
Database::editTile(editTileData.Loc, static_cast<std::uint32_t>(editTileData.NewTile));
} else {
result = eInvalid;
}
break;
case sRandomMap:
// TODO: needs CreateElevation/CreateMap (full procedural map
// generator, not ported yet) - always reports unavailable for now.
result = eInvalid;
break;
case sFillMap:
if (player == 0) {
fillMap(static_cast<std::uint32_t>(static_cast<TFillMapData *>(data)->Tile), true);
Database::observeLevel.fill(0);
Database::discoverAll(player, Database::lObserveSuper);
} else {
result = eInvalid;
}
break;
case sMapGeneratorRequest:
if (!Database::mapGeneratorAvailable())
result = eInvalid;
break;
// --- Client Deactivation Commands ---
case sTurn:
case sTurn - sExecute: {
bool allHumansDead = true;
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gAlive) && playerBrain[p1]->kind == BrainType::Term) {
allHumansDead = false;
break;
}
if (pDipActive >= 0 || // still in negotiation mode
(pTurn == 0 &&
(gWinner > 0 || Database::gTurn == maxTurn || (Database::difficulty[0] > 0 && allHumansDead)))) {
result = eViolation; // game end reached
} else if (command >= sExecute) {
if (Database::mode == Database::moPlaying) {
Database::cl.setState(formerClState);
logCityTileChanges();
if (pTurn == 0) {
logChanges();
saveGame(toAutoSaveFileName(logFileName), true);
}
} else if (Database::mode == Database::moMovie && pTurn == 0) {
callPlayer(cMovieEndTurn, 0, nullptr);
}
Database::gWatching = (Database::gWatching & Database::gAlive) | 1;
Database::rw[pTurn].Happened = 0;
UnitProcessing::uixSelectedTransport = -1;
spyMission = smSabotageProd;
int checkSum = 0;
if ((1 << pTurn) & Database::gAlive) {
int totalFood = 0;
int totalProd = 0;
TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int i = 0; i < player.nCity; ++i) {
if (city[i].Loc >= 0) {
totalFood += city[i].Food;
totalProd += city[i].Prod;
}
}
checkSum = (totalFood & 7) + ((totalProd & 7) << 3) + ((player.Money & 7) << 6) +
(((UnitProcessing::worked[pTurn] / 100) & 7) << 9);
}
if (Database::mode < Database::moPlaying) { // check checksum
if (checkSum != subject)
loadOK = false;
} else { // save checksum
Database::cl.put(command, player, checkSum, data);
}
if ((1 << pTurn) & Database::gAlive) {
afterTurn();
if (Database::mode < Database::moPlaying)
insertTerritoryUpdateCommands();
}
do {
pTurn = (pTurn + 1) % nPl;
if (pTurn == 0)
++Database::gTurn;
if (playerBrain[pTurn] && (((1 << pTurn) & Database::gAlive) == 0)) {
// already made extinct -- continue statistics
stat[stExplore][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stPop][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stTerritory][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stScience][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stWork][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stMil][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
}
} while (pTurn != 0 && (((1 << pTurn) & (Database::gAlive | Database::gWatching)) == 0 || gWinner != 0));
if (Database::mode == Database::moLoading_Fast &&
(Database::gTurn == loadTurn || (Database::gTurn == loadTurn - 1 && pTurn > 0)))
Database::mode = Database::moLoading;
if (Database::mode == Database::moPlaying) {
ccCommand = cTurn;
ccPlayer = pTurn;
notifyEvent(NotifyId::NextPlayer);
} else {
if (Database::gTurn == 0)
beforeTurn0();
else
beforeTurn();
if (Database::mode == Database::moMovie && pTurn == 0) {
inform(pTurn);
callPlayer(cMovieTurn, 0, nullptr);
}
}
}
break;
} // sTurn
case sBreak:
case sResign:
case sNextRound:
case sReload: {
bool ok;
if (command == sReload) {
ok = Database::difficulty[0] == 0 && playerBrain[0]->kind != BrainType::NoTerm &&
reinterpret_cast<std::intptr_t>(data) >= 0 &&
reinterpret_cast<std::intptr_t>(data) < Database::gTurn;
for (int p1 = 1; p1 < nPl && ok; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::Term)
ok = false;
// allow reload in AI-only games only
} else {
ok = player == 0;
}
if (ok) {
if (command == sBreak || command == sResign)
notifyEvent(NotifyId::BackOn);
for (int i = 0; i < brains.count(); ++i) {
if (brains[i].initialized) {
if (brains[i].kind == BrainType::AI)
notifyEvent(NotifyId::DeinitModule, i);
callClient(i, cBreakGame, nullptr);
}
}
notifyEvent(NotifyId::EndInfo);
if (command == sBreak || command == sReload) {
logCityTileChanges();
logChanges();
saveGame(logFileName, false);
}
QFile::remove(toAutoSaveFileName(logFileName));
endGame();
switch (command) {
case sBreak:
notifyEvent(NotifyId::StartGoRefresh);
break;
case sResign:
notifyEvent(NotifyId::StartGo);
break;
case sNextRound:
startNewGame(logFileName, mapFileName, Database::lx, Database::ly, Database::landMass, maxTurn);
break;
case sReload:
loadGame(logFileName, logFileName, static_cast<int>(reinterpret_cast<std::intptr_t>(data)), false);
break;
default:
break;
}
} else {
result = eInvalid;
}
break;
}
case sAbandonMap:
case sSaveMap:
if (player == 0) {
if (command == sSaveMap) {
Map map;
map.setSize(QPoint(Database::lx, Database::ly));
map.maxTurn = maxTurn;
std::copy(Database::realMap.begin(), Database::realMap.begin() + Database::mapSize,
map.tiles.begin());
QDir().mkpath(QFileInfo(mapFileName).path());
map.saveToFile(mapFileName);
}
notifyEvent(NotifyId::BackOn);
brainTerm->module.call(cBreakGame, -1, nullptr);
Database::releaseMapEditor();
notifyEvent(command == sSaveMap ? NotifyId::StartGoRefreshMaps : NotifyId::StartGo);
} else {
result = eInvalid;
}
break;
// --- Diplomacy Commands ---
case scReject:
case scReject - sExecute:
if ((lastEndClientCommand & 0xFF0F) == scContact) {
if (command >= sExecute) { // contact requested and not accepted yet
pDipActive = -1;
assert(Database::mode == Database::moPlaying);
changeClientWhenDone(cContinue, pTurn, nullptr, 0);
}
} else {
result = eInvalid;
}
break;
case scDipStart:
case scDipStart - sExecute:
if ((lastEndClientCommand & 0xFF0F) == scContact) {
if (command >= sExecute) { // accept contact
pContacted = pDipActive;
Database::rw[pContacted].EnemyReport[pTurn]->Credibility = Database::rw[pTurn].Credibility;
pDipActive = pTurn;
assert(Database::mode == Database::moPlaying);
Database::intServer(sIntHaveContact, pTurn, pContacted, nullptr);
changeClientWhenDone(scDipStart, pDipActive, nullptr, 0);
}
} else {
result = eInvalid;
}
break;
case scDipNotice:
case scDipAccept:
case scDipCancelTreaty:
case scDipBreak:
case scDipNotice - sExecute:
case scDipAccept - sExecute:
case scDipCancelTreaty - sExecute:
case scDipBreak - sExecute:
if (pDipActive >= 0) {
assert(Database::mode == Database::moPlaying);
const int p1 = (pDipActive == pTurn) ? pContacted : pTurn;
if ((command & ~sExecute) == (scDipBreak & ~sExecute) && lastEndClientCommand != scDipBreak) {
// Ok
} else if ((command & ~sExecute) == (scDipNotice & ~sExecute) &&
(lastEndClientCommand == scDipCancelTreaty || lastEndClientCommand == scDipBreak)) {
// Ok
} else if ((command & ~sExecute) == (scDipAccept & ~sExecute) && lastEndClientCommand == scDipOffer) {
// check if offer can be accepted
if (lastOffer.nDeliver + lastOffer.nCost == 0)
result = eOfferNotAcceptable;
for (int i = 0; i < lastOffer.nDeliver + lastOffer.nCost; ++i)
if (lastOffer.Price[i] == opChoose) {
result = eOfferNotAcceptable;
break;
}
for (int i = 0; i < lastOffer.nCost; ++i)
if (!Database::payPrice(pDipActive, p1, lastOffer.Price[lastOffer.nDeliver + i], false))
result = eOfferNotAcceptable;
if (command >= sExecute && result >= rExecuted) {
Database::intServer(sIntPayPrices + lastOffer.nDeliver + lastOffer.nCost, p1, pDipActive,
&lastOffer);
// tell other players about ship part trades
bool hasShipChanged = false;
TShowShipChange showShipChange{};
for (int i = 0; i < lastOffer.nDeliver + lastOffer.nCost; ++i) {
if ((lastOffer.Price[i] & opMask) == static_cast<std::uint32_t>(opShipParts)) {
hasShipChanged = true;
const int part = static_cast<int>((lastOffer.Price[i] >> 16) & 3);
const int amount = static_cast<int>(lastOffer.Price[i] & 0xFFFF);
if (i >= lastOffer.nDeliver) { // p1 has demanded from pDipActive
showShipChange.Ship1Change[part] = amount;
showShipChange.Ship2Change[part] = -amount;
} else { // p1 has delivered to pDipActive
showShipChange.Ship1Change[part] = -amount;
showShipChange.Ship2Change[part] = amount;
}
}
}
if (hasShipChanged) {
showShipChange.Reason = scrTrade;
showShipChange.Ship1Owner = p1;
showShipChange.Ship2Owner = pDipActive;
for (int p2 = 0; p2 < nPl; ++p2) {
if (p2 != p1 && p2 != pDipActive && ((1 << p2) & (Database::gAlive | Database::gWatching))) {
std::memcpy(Database::rw[p2].Ship, Database::gShip.data(),
sizeof(Database::rw[p2].Ship));
if ((1 << p2) & Database::gWatching)
callPlayer(cShowShipChange, p2, &showShipChange);
}
}
}
}
} else if ((command & ~sExecute) == (scDipCancelTreaty & ~sExecute) &&
Database::rw[pDipActive].Treaty[p1] >= trPeace) {
if (Database::serverVersion[pDipActive] >= 0x010100 &&
Database::gTurn < Database::rw[pDipActive].LastCancelTreaty[p1] + CancelTreatyTurns) {
result = eCancelTreatyRush;
} else if (command >= sExecute) {
Database::intServer(sIntCancelTreaty, pDipActive, p1, nullptr);
for (int p2 = 0; p2 < nPl; ++p2)
if (p2 != p1 && ((1 << p2) & Database::peaceEnded)) {
int i = (p1 << 4) + pDipActive;
callPlayer(cShowSupportAllianceAgainst, p2, &i);
}
for (int p2 = 0; p2 < nPl; ++p2)
if (p2 != p1 && ((1 << p2) & Database::peaceEnded))
callPlayer(cShowCancelTreatyByAlliance, pDipActive, &p2);
}
} else {
result = eInvalid;
}
if (command >= sExecute && result >= rExecuted) {
if (lastEndClientCommand == scDipBreak) { // break negotiation
pDipActive = -1;
callPlayer(cShowEndContact, pContacted, nullptr);
changeClientWhenDone(cContinue, pTurn, nullptr, 0);
} else {
if ((Database::gTestFlags & tfUncover) || Database::difficulty[0] == 0) {
// display negotiation in log window
TShowNegoData showNegoData{};
showNegoData.pSender = pDipActive;
showNegoData.pTarget = p1;
showNegoData.Action = command;
playerBrain[0]->module.call(cShowNego, (1 << 16) + 3, &showNegoData);
}
pDipActive = p1;
changeClientWhenDone(command, pDipActive, nullptr, 0);
}
}
} else {
result = eInvalid;
}
break;
case scDipOffer:
case scDipOffer - sExecute:
if (pDipActive >= 0 && lastEndClientCommand != scDipCancelTreaty && lastEndClientCommand != scDipBreak) {
const TOffer &offer = *static_cast<const TOffer *>(data);
if (lastEndClientCommand == scDipOffer && lastOffer.nDeliver + lastOffer.nCost + offer.nDeliver + offer.nCost == 0) {
if (command >= sExecute) { // agreed discussion end
pDipActive = -1;
callPlayer(cShowEndContact, pContacted, nullptr);
assert(Database::mode == Database::moPlaying);
changeClientWhenDone(cContinue, pTurn, nullptr, 0);
}
} else {
// check if offer can be made
const int p1 = (pDipActive == pTurn) ? pContacted : pTurn;
if (Database::rw[pDipActive].Treaty[p1] < trPeace) { // no tribute allowed!
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i)
if ((offer.Price[i] & opMask) == static_cast<std::uint32_t>(opTribute)) {
result = eInvalidOffer;
break;
}
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i)
if (offer.Price[i] == static_cast<std::uint32_t>(opTreaty + trPeace)) {
result = eOK;
break;
}
}
for (int i = 0; i < offer.nDeliver; ++i)
if (offer.Price[i] != opChoose && !Database::payPrice(pDipActive, p1, offer.Price[i], false))
result = eInvalidOffer;
if (countPrice(offer, opTreaty) > 1)
result = eInvalidOffer;
for (int i = 0; i < nShipPart; ++i)
if (countPrice(offer, opShipParts + (i << 16)) > 1) {
result = eInvalidOffer;
break;
}
if (countPrice(offer, opMoney) > 1)
result = eInvalidOffer;
if (countPrice(offer, opTribute) > 1)
result = eInvalidOffer;
switch (countPrice(offer, opChoose)) {
case 0:
break;
case 1:
if (offer.nCost == 0 || offer.nDeliver == 0)
result = eInvalidOffer;
break;
default:
result = eInvalidOffer;
break;
}
// !!! check here if cost can be demanded
if (command >= sExecute && result >= rExecuted) {
bool offerFullySupported = offer.nDeliver <= 2 && offer.nCost <= 2; // >2 no more allowed
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i) {
if ((offer.Price[i] & opMask) == static_cast<std::uint32_t>(opTribute))
offerFullySupported = false; // tribute no more part of the game
if ((offer.Price[i] & opMask) == static_cast<std::uint32_t>(opTreaty) &&
static_cast<int>(offer.Price[i] - opTreaty) <= Database::rw[pDipActive].Treaty[p1])
offerFullySupported = false; // agreed treaty end no more part of the game
if (offer.Price[i] == static_cast<std::uint32_t>(opTreaty + trCeaseFire))
offerFullySupported = false; // ceasefire no more part of the game
}
if (!offerFullySupported) {
// some elements have been removed from the game -
// automatically respond with null-offer
lastOffer.nDeliver = 0;
lastOffer.nCost = 0;
changeClientWhenDone(scDipOffer, pDipActive, &lastOffer, sizeof(lastOffer));
} else {
if ((Database::gTestFlags & tfUncover) || Database::difficulty[0] == 0) {
// display negotiation in log window
TShowNegoData showNegoData{};
showNegoData.pSender = pDipActive;
showNegoData.pTarget = p1;
showNegoData.Action = command;
showNegoData.Offer = offer;
playerBrain[0]->module.call(cShowNego, (1 << 16) + 3, &showNegoData);
}
lastOffer = offer;
// show offered things to receiver
for (int i = 0; i < lastOffer.nDeliver; ++i)
Database::showPrice(pDipActive, p1, lastOffer.Price[i]);
pDipActive = p1;
assert(Database::mode == Database::moPlaying);
changeClientWhenDone(scDipOffer, pDipActive, &lastOffer, sizeof(lastOffer));
}
}
}
} else {
result = eInvalid;
}
break;
// --- Unit Related Commands ---
case sRemoveUnit:
case sRemoveUnit - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0) {
result = eInvalid;
} else {
result = eRemoved;
TUn &un = (*playerCtx.Un)[subject];
const int loc0 = un.Loc;
if (Database::realMap[loc0] & fCity) { // check utilize
int p1 = player;
int cix1 = 0;
Database::searchCity(loc0, p1, cix1);
TCity &city = (*playerCtx.City)[cix1];
if ((((*playerCtx.Model)[un.mix].Kind == mkCaravan) &&
((city.Project & cpImp) == 0 || Imp[city.Project & cpIndex].Kind != ikShipPart)) ||
((city.Project & cpImp) == 0 && (*playerCtx.Model)[city.Project & cpIndex].Kind != mkCaravan))
result = eUtilized;
if (command >= sExecute) {
if (result == eUtilized) {
int cost = static_cast<int>((*playerCtx.Model)[un.mix].Cost) * un.Health *
BuildCostMod[Database::difficulty[player]] / 1200;
if ((*playerCtx.Model)[un.mix].Cap[mcLine] > 0)
cost /= 2;
if ((city.Project & (cpImp + cpIndex)) == cpImp + imTrGoods) {
playerCtx.Money += cost;
} else {
city.Prod += cost * 2 / 3;
city.Project0 &= ~static_cast<decltype(city.Project0)>(cpCompleted);
if ((city.Project0 & ~static_cast<decltype(city.Project0)>(cpAuto)) !=
(city.Project & ~static_cast<decltype(city.Project)>(cpAuto)))
city.Project0 = city.Project;
city.Prod0 = city.Prod;
}
}
Database::removeUnitUpdateMap(player, subject);
}
} else if (command >= sExecute) {
Database::removeUnitUpdateMap(player, subject);
}
}
break;
}
case sSetUnitHome:
case sSetUnitHome - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0) {
result = eInvalid;
} else {
const int loc0 = (*playerCtx.Un)[subject].Loc;
if ((Database::realMap[loc0] & fCity) == 0) {
result = eInvalid;
} else {
int p1 = player;
int cix1 = 0;
Database::searchCity(loc0, p1, cix1);
if ((*playerCtx.City)[cix1].Flags & chCaptured)
result = eViolation;
else if (command >= sExecute)
(*playerCtx.Un)[subject].Home = cix1;
}
}
break;
}
case sLoadUnit:
case sLoadUnit - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0)
result = eInvalid;
else
result = UnitProcessing::loadUnit(player, subject, command < sExecute);
break;
}
case sUnloadUnit:
case sUnloadUnit - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0)
result = eInvalid;
else
result = UnitProcessing::unloadUnit(player, subject, command < sExecute);
break;
}
case sSelectTransport:
case sSelectTransport - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0) {
result = eInvalid;
} else {
const TModel &model = (*playerCtx.Model)[(*playerCtx.Un)[subject].mix];
if (model.Cap[mcSeaTrans] + model.Cap[mcAirTrans] + model.Cap[mcCarrier] == 0)
result = eInvalid;
else if (command >= sExecute)
UnitProcessing::uixSelectedTransport = subject;
}
break;
}
// sMoveUnit + (dx and 7 shl 4) + (dy and 7 shl 7), for the 8 valid
// hex-grid movement directions (matches the original's own explicit
// enumeration - most of the 64 raw dx/dy bit combinations are invalid).
case sMoveUnit + (0 + 6 * 8) * 16:
case sMoveUnit + (1 + 7 * 8) * 16:
case sMoveUnit + (2 + 0 * 8) * 16:
case sMoveUnit + (1 + 1 * 8) * 16:
case sMoveUnit + (0 + 2 * 8) * 16:
case sMoveUnit + (7 + 1 * 8) * 16:
case sMoveUnit + (6 + 0 * 8) * 16:
case sMoveUnit + (7 + 7 * 8) * 16:
case sMoveUnit - sExecute + (0 + 6 * 8) * 16:
case sMoveUnit - sExecute + (1 + 7 * 8) * 16:
case sMoveUnit - sExecute + (2 + 0 * 8) * 16:
case sMoveUnit - sExecute + (1 + 1 * 8) * 16:
case sMoveUnit - sExecute + (0 + 2 * 8) * 16:
case sMoveUnit - sExecute + (7 + 1 * 8) * 16:
case sMoveUnit - sExecute + (6 + 0 * 8) * 16:
case sMoveUnit - sExecute + (7 + 7 * 8) * 16: {
const int dx = ((command >> 4) + 4) % 8 - 4;
const int dy = ((command >> 7) + 4) % 8 - 4;
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0)
result = eInvalid;
else
result = moveUnit(player, subject, dx, dy, command < sExecute);
break;
}
// --- General Commands ---
case sClearTestFlag:
if (player == 0)
Database::clearTestFlags(subject);
else
result = eInvalid;
break;
case sSetTestFlag:
if (player == 0)
Database::setTestFlags(player, subject);
else
result = eInvalid;
break;
case sSetGovernment:
case sSetGovernment - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if ((playerCtx.Happened & phChangeGov) == 0) {
result = eViolation;
} else if (playerCtx.Government == subject) {
result = eNotChanged;
} else if (subject >= nGov) {
result = eInvalid;
} else if (subject >= gMonarchy && playerCtx.Tech[GovPreq[subject]] < tsApplicable) {
result = eNoPreq;
} else if (command >= sExecute) {
playerCtx.Government = subject;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != player && ((Database::gAlive | Database::gWatching) & (1 << p1)))
Database::rw[p1].EnemyReport[player]->Government = subject;
}
break;
}
case sSetRates:
case sSetRates - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if ((subject & 0xF) + (subject >> 4) > 10) {
result = eInvalid;
} else if (playerCtx.TaxRate == (subject & 0xF) * 10 && playerCtx.LuxRate == (subject >> 4) * 10) {
result = eNotChanged;
} else if (command >= sExecute) {
playerCtx.TaxRate = (subject & 0xF) * 10;
playerCtx.LuxRate = (subject >> 4) * 10;
}
break;
}
case sRevolution: {
TPlayerContext &playerCtx = Database::rw[player];
if (playerCtx.Government == gAnarchy) {
result = eInvalid;
} else {
playerCtx.Government = gAnarchy;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != player && ((Database::gAlive | Database::gWatching) & (1 << p1)))
Database::rw[p1].EnemyReport[player]->Government = gAnarchy;
playerCtx.AnarchyStart = Database::gTurn;
}
break;
}
case sSetResearch:
case sSetResearch - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if ((playerCtx.Happened & phTech) && (subject < nAdv || subject == adMilitary)) {
if (Database::mode == Database::moPlaying && subject == adMilitary &&
devModelTurn[player] != Database::gTurn) {
result = eNoModel;
} else if (subject != adMilitary) {
if (subject == futComputingTechnology) {
if (playerCtx.Tech[subject] >= MaxFutureTech_Computing)
result = eInvalid;
} else if (IsFutureTech(subject)) {
if (playerCtx.Tech[subject] >= MaxFutureTech)
result = eInvalid;
} else if (playerCtx.Tech[subject] >= tsApplicable) {
result = eInvalid; // already discovered
}
if (playerCtx.Tech[subject] != tsSeen) { // look if preqs met
if (AdvPreq[subject][2] != preNone) { // 2 of 3 required
int metCount = 0;
for (int j = 0; j < 3; ++j)
if (playerCtx.Tech[AdvPreq[subject][j]] >= tsApplicable)
++metCount;
if (metCount < 2)
result = eNoPreq;
} else if ((AdvPreq[subject][0] != preNone && playerCtx.Tech[AdvPreq[subject][0]] < tsApplicable) ||
(AdvPreq[subject][1] != preNone && playerCtx.Tech[AdvPreq[subject][1]] < tsApplicable)) {
result = eNoPreq;
}
}
if (result == eOK && command >= sExecute) {
if (Database::mode == Database::moPlaying && subject == adMilitary)
Database::intServer(sIntSetDevModel, player, 0, &playerCtx.DevModel.Kind);
// save DevModel, because sctModel commands are not Logged
playerCtx.ResearchTech = subject;
}
}
} else {
result = eViolation;
}
break;
}
case sStealTech:
case sStealTech - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if ((playerCtx.Happened & phStealTech) == 0) {
result = eInvalid;
} else if (subject >= nAdv || IsFutureTech(subject) || playerCtx.Tech[subject] >= tsSeen ||
Database::rw[gStealFrom].Tech[subject] < tsApplicable) {
result = eInvalid;
} else if (command >= sExecute) {
Database::seeTech(player, subject);
playerCtx.Happened -= phStealTech;
}
break;
}
// --- Model Related Commands ---
case sCreateDevModel:
case sCreateDevModel - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= 4) {
result = eInvalid;
} else if (Upgrade[subject][0].Preq != preNone && playerCtx.Tech[Upgrade[subject][0].Preq] < tsApplicable) {
result = eNoPreq;
} else if (command >= sExecute) {
TModel &devModel = playerCtx.DevModel;
devModel.Domain = static_cast<decltype(devModel.Domain)>(subject);
devModel.MStrength = 0;
devModel.MTrans = 0;
devModel.MCost = 0;
devModel.Upgrades = 0;
int futureMCost = 0;
for (int i = 0; i < nUpgrade; ++i) {
const UpgradeInfo &up = Upgrade[devModel.Domain][i];
if (up.Preq == preNone ||
(up.Preq >= 0 && (playerCtx.Tech[up.Preq] >= tsApplicable ||
(IsFutureTech(up.Preq) && playerCtx.Tech[up.Preq] >= 0)))) {
int j;
if (IsFutureTech(up.Preq)) {
j = playerCtx.Tech[up.Preq];
futureMCost += j * up.Cost;
} else {
j = 1;
if (up.Cost > devModel.MCost)
devModel.MCost = static_cast<decltype(devModel.MCost)>(up.Cost);
}
devModel.Upgrades |= (1 << i);
devModel.MStrength = static_cast<decltype(devModel.MStrength)>(devModel.MStrength + j * up.Strength);
devModel.MTrans = static_cast<decltype(devModel.MTrans)>(devModel.MTrans + j * up.Trans);
}
}
devModel.MCost = static_cast<decltype(devModel.MCost)>(devModel.MCost + futureMCost);
std::memset(devModel.Cap, 0, sizeof(devModel.Cap));
devModel.Cap[mcOffense] = 2;
devModel.Cap[mcDefense] = 1;
for (int i = 0; i < nFeature; ++i) {
const FeatureInfo &feature = Feature[i];
if (((1 << devModel.Domain) & feature.Domains) &&
(feature.Preq == preNone || (feature.Preq == preSun && Database::gWonder[woSun].EffectiveOwner == player) ||
(feature.Preq >= 0 && playerCtx.Tech[feature.Preq] >= tsApplicable)) &&
((AutoFeature >> i) & 1))
devModel.Cap[i] = 1;
}
devModel.MaxWeight = 5;
if (WeightPreq7[devModel.Domain] != preNA && playerCtx.Tech[WeightPreq7[devModel.Domain]] >= tsApplicable)
devModel.MaxWeight = 7;
if (WeightPreq10[devModel.Domain] != preNA && playerCtx.Tech[WeightPreq10[devModel.Domain]] >= tsApplicable)
devModel.MaxWeight = (devModel.Domain == dSea) ? 9 : 10;
Database::calculateModel(devModel);
devModelTurn[player] = Database::gTurn;
}
break;
}
// --- Settlers Related Commands ---
case sAddToCity:
case sAddToCity - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nUn || (*playerCtx.Un)[subject].Loc < 0) {
result = eInvalid;
} else {
TUn &un = (*playerCtx.Un)[subject];
const int kind = (*playerCtx.Model)[un.mix].Kind;
if (kind != mkSettler && kind != mkSlaves && (un.Flags & unConscripts) == 0) {
result = eViolation;
} else if ((Database::realMap[un.Loc] & fCity) == 0) {
result = eInvalid;
} else {
int p1 = player;
int cix1 = 0;
Database::searchCity(un.Loc, p1, cix1);
if (!CityProcessing::canCityGrow(player, cix1)) {
result = eMaxSize;
} else if (command >= sExecute) { // add to city
if (Database::mode == Database::moPlaying)
savedTiles[static_cast<std::size_t>(cix1)] = 0; // save in every case
if (CityProcessing::canCityGrow(player, cix1))
CityProcessing::cityGrowth(player, cix1);
if (kind == mkSettler && CityProcessing::canCityGrow(player, cix1))
CityProcessing::cityGrowth(player, cix1);
Database::removeUnitUpdateMap(player, subject);
}
}
}
break;
}
// --- City Related Commands ---
case sSetCityProject:
case sSetCityProject - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0) {
result = eInvalid;
break;
}
TCity &city = (*playerCtx.City)[subject];
const auto newProject = static_cast<std::int16_t>(reinterpret_cast<std::intptr_t>(data) & ~cpAuto);
if (newProject == city.Project) {
result = eNotChanged;
break;
}
auto projectType = [&playerCtx](int project) {
if (project & cpCompleted)
return ptSelect;
if ((project & (cpImp + cpIndex)) == cpImp + imTrGoods)
return ptTrGoods;
if ((project & cpImp) == 0)
return (*playerCtx.Model)[project & cpIndex].Kind == mkCaravan ? ptCaravan : ptUn;
if ((project & cpIndex) >= nImp)
return ptInvalid;
if (Imp[project & cpIndex].Kind == ikWonder)
return ptWonder;
if (Imp[project & cpIndex].Kind == ikShipPart)
return ptShip;
return ptImp;
};
const int pt0 = projectType(city.Project0);
const int pt1 = projectType(newProject);
if ((newProject & cpImp) == 0) {
if ((newProject & cpIndex) >= playerCtx.nModel) {
result = eInvalid;
} else if ((newProject & cpConscripts) &&
!(playerCtx.Tech[adConscription] >= tsApplicable &&
(*playerCtx.Model)[newProject & cpIndex].Domain == dGround &&
(*playerCtx.Model)[newProject & cpIndex].Kind < mkScout)) {
result = eViolation;
}
} else if ((newProject & cpIndex) >= nImp) {
result = eInvalid;
} else {
const int preq = Imp[newProject & cpIndex].Preq;
for (int i = 0; i < nImpReplacement; ++i) {
if (ImpReplacement[i].OldImp == (newProject & cpIndex) && city.Built[ImpReplacement[i].NewImp] > 0) {
result = eObsolete;
break;
}
}
if (result == eObsolete) {
// keep eObsolete
} else if (preq == preNA) {
result = eInvalid;
} else if (preq >= 0 && playerCtx.Tech[preq] < tsApplicable) {
result = eNoPreq;
} else if (city.Built[newProject & cpIndex] > 0) {
result = eInvalid;
} else if ((newProject & cpIndex) < nWonder &&
Database::gWonder[newProject & cpIndex].CityID != WonderNotBuiltYet) {
result = eViolation; // wonder already exists
} else if ((newProject & cpIndex) == imSpacePort && playerCtx.NatBuilt[imSpacePort] > 0) {
result = eViolation; // space port already exists
} else if ((newProject == cpImp + imBank && city.Built[imMarket] == 0) ||
(newProject == cpImp + imUniversity && city.Built[imLibrary] == 0) ||
(newProject == cpImp + imResLab && city.Built[imUniversity] == 0) ||
(newProject == cpImp + imMfgPlant && city.Built[imFactory] == 0)) {
result = eNoPreq;
}
switch (newProject - cpImp) {
case woLighthouse:
case woMagellan:
case imCoastalFort:
case imHarbor:
case imPlatform: { // city at ocean?
int count = 0;
Database::Vicinity8Loc adjacent;
Database::v8ToLoc(city.Loc, adjacent);
for (int v8 = 0; v8 < 8; ++v8) {
const int loc1 = adjacent[static_cast<std::size_t>(v8)];
if (loc1 >= 0 && loc1 < Database::mapSize &&
(Database::realMap[loc1] & fTerrain) == static_cast<std::uint32_t>(fShore))
++count;
}
if (count == 0)
result = eNoPreq;
break;
}
case woHoover:
case imHydro: { // city at river or mountains?
int count = 0;
Database::Vicinity8Loc adjacent;
Database::v8ToLoc(city.Loc, adjacent);
for (int v8 = 0; v8 < 8; ++v8) {
const int loc1 = adjacent[static_cast<std::size_t>(v8)];
if (loc1 >= 0 && loc1 < Database::mapSize &&
((Database::realMap[loc1] & fTerrain) == static_cast<std::uint32_t>(fMountains) ||
(Database::realMap[loc1] & fRiver)))
++count;
}
if (count == 0)
result = eNoPreq;
break;
}
case woMir:
case imShipComp:
case imShipPow:
case imShipHab:
if (playerCtx.NatBuilt[imSpacePort] == 0)
result = eNoPreq;
break;
default:
break;
}
if ((Database::gTestFlags & tfNoRareNeed) == 0 && Imp[newProject & cpIndex].Kind == ikShipPart) {
if (playerCtx.Tech[adMassProduction] < tsApplicable) {
result = eNoPreq;
} else { // check for rare resources
int rareType;
if ((newProject & cpIndex) == imShipComp)
rareType = 1;
else if ((newProject & cpIndex) == imShipPow)
rareType = 2;
else
rareType = 3;
int count = 0;
Database::Vicinity21Loc radius;
Database::v21ToLoc(city.Loc, radius);
for (int v21 = 1; v21 <= 26; ++v21) {
const int loc1 = radius[static_cast<std::size_t>(v21)];
if (loc1 >= 0 && loc1 < Database::mapSize &&
((Database::realMap[loc1] >> 25) & 3) == static_cast<std::uint32_t>(rareType))
++count;
}
if (count == 0)
result = eNoPreq;
}
}
}
if (command >= sExecute && result >= rExecuted) {
if (pt0 != ptSelect) {
if ((newProject & (cpImp | cpIndex)) == (city.Project0 & (cpImp | cpIndex))) {
city.Prod = city.Prod0;
} else if (pt1 == ptTrGoods || pt1 == ptShip || (pt1 != pt0 && pt0 != ptCaravan)) {
playerCtx.Money += city.Prod0;
city.Prod = 0;
city.Prod0 = 0;
city.Project0 = cpImp + imTrGoods;
} else {
city.Prod = static_cast<std::int16_t>(city.Prod0 * 2 / 3);
}
}
city.Project = newProject;
}
break;
}
case sBuyCityProject:
case sBuyCityProject - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0) {
result = eInvalid;
break;
}
TCity &city = (*playerCtx.City)[subject];
if (playerCtx.Government == gAnarchy || (city.Flags & chCaptured)) {
result = eOutOfControl;
} else if ((city.Project & cpImp) &&
((city.Project & cpIndex) == imTrGoods || Imp[city.Project & cpIndex].Kind == ikShipPart)) {
result = eInvalid; // don't buy colony ship
} else {
TCityReport cityReport{};
cityReport.HypoTiles = -1;
cityReport.HypoTax = -1;
cityReport.HypoLux = -1;
CityProcessing::getCityReport(player, subject, cityReport);
int cost = cityReport.ProdCost;
int nextProd = cityReport.ProdRep - cityReport.Support;
if (cityReport.Working - cityReport.Happy > (city.Size >> 1) || nextProd < 0) // !!! change to new style disorder
nextProd = 0;
cost = cost - city.Prod - nextProd;
if (Database::gWonder[woMich].EffectiveOwner == player && (city.Project & cpImp))
cost *= 2;
else
cost *= 4;
if (cost <= 0)
result = eNotChanged;
else if (cost > playerCtx.Money)
result = eViolation;
else if (command >= sExecute)
Database::intServer(sIntBuyMaterial, player, subject, &cost);
// need to save material/cost because city tiles are not correct
// when loading
}
break;
}
case sSellCityProject:
case sSellCityProject - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0) {
result = eInvalid;
} else if (command >= sExecute) {
TCity &city = (*playerCtx.City)[subject];
playerCtx.Money += city.Prod0;
city.Prod = 0;
city.Prod0 = 0;
}
break;
}
case sSellCityImprovement:
case sSellCityImprovement - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0) {
result = eInvalid;
break;
}
TCity &city = (*playerCtx.City)[subject];
const auto imp = static_cast<int>(reinterpret_cast<std::intptr_t>(data));
if (city.Built[imp] == 0) {
result = eInvalid;
} else if (playerCtx.Government == gAnarchy || (city.Flags & chCaptured)) {
result = eOutOfControl;
} else if (city.Flags & chImprovementSold) {
result = eOnlyOnce;
} else if (command >= sExecute) {
playerCtx.Money += Imp[imp].Cost * BuildCostMod[Database::difficulty[player]] / 12;
city.Built[imp] = 0;
if (Imp[imp].Kind == ikNatLocal || Imp[imp].Kind == ikNatGlobal) {
playerCtx.NatBuilt[imp] = 0;
if (imp == imGrWall)
Database::grWallContinent[player] = -1;
else if (imp == imSpacePort)
destroySpacePortTellPlayers(player, -1);
}
city.Flags += chImprovementSold;
}
break;
}
case sRebuildCityImprovement:
case sRebuildCityImprovement - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0) {
result = eInvalid;
break;
}
const auto oldImp = static_cast<int>(reinterpret_cast<std::intptr_t>(data));
TCity &city = (*playerCtx.City)[subject];
if (oldImp < 0 || oldImp >= nImp ||
!(Imp[oldImp].Kind == ikCommon || Imp[oldImp].Kind == ikNatLocal || Imp[oldImp].Kind == ikNatGlobal)) {
result = eInvalid;
} else if (city.Built[oldImp] == 0 || (city.Project & cpImp) == 0 ||
!(Imp[city.Project & cpIndex].Kind == ikCommon || Imp[city.Project & cpIndex].Kind == ikNatLocal ||
Imp[city.Project & cpIndex].Kind == ikNatGlobal)) {
result = eInvalid;
} else if (playerCtx.Government == gAnarchy || (city.Flags & chCaptured)) {
result = eOutOfControl;
} else if (city.Flags & chImprovementSold) {
result = eOnlyOnce;
} else if (command >= sExecute) {
city.Prod = static_cast<std::int16_t>(
city.Prod + Imp[oldImp].Cost * BuildCostMod[Database::difficulty[player]] / 12 * 2 / 3);
city.Project0 &= ~static_cast<std::int16_t>(cpCompleted);
if ((city.Project0 & ~cpAuto) != (city.Project & ~cpAuto))
city.Project0 = city.Project;
city.Prod0 = city.Prod;
city.Built[oldImp] = 0;
if (Imp[oldImp].Kind == ikNatLocal || Imp[oldImp].Kind == ikNatGlobal) { // nat. project lost
playerCtx.NatBuilt[oldImp] = 0;
if (oldImp == imGrWall)
Database::grWallContinent[player] = -1;
else if (oldImp == imSpacePort)
destroySpacePortTellPlayers(player, -1);
}
city.Flags += chImprovementSold;
}
break;
}
case sSetCityTiles:
case sSetCityTiles - sExecute: {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= playerCtx.nCity || (*playerCtx.City)[subject].Loc < 0)
result = eInvalid;
else
result = CityProcessing::setCityTiles(player, subject, static_cast<int>(reinterpret_cast<std::intptr_t>(data)),
command < sExecute);
break;
}
// sSetDevModelCap is dispatched from default: below (NewCap is encoded
// in command bits 4-9, a dense range the switch can't match directly -
// same reason sSetSpyMission/sCreateUnit are pattern-matched there too).
// --- Everything else is now covered; fall through to the original's
// own cClientEx/eUnknown fallback for anything truly unrecognized.
// scContact/sSetAttitude/sSetSpyMission/sCreateUnit/sStartJob/
// sSetDevModelCap are pattern-matched here (not enumerated as switch
// cases) since the original encodes a dense range into their low bits.
default:
if ((command & ~0xF0) == scContact || (command & ~0xF0) == scContact - sExecute) {
const int p1 = (command >> 4) & 0xF;
if (pDipActive >= 0 || ((1 << p1) & Database::gAlive) == 0) {
result = eInvalid;
} else if (gWinner > 0) {
result = eViolation; // game end reached
} else if (Database::rw[player].Treaty[p1] == trNoContact) {
result = eNoPreq;
} else if (Database::gTurn < gColdWarStart + ColdWarTurns) {
result = eColdWar;
} else if (Database::rw[player].Government == gAnarchy) {
result = eAnarchy;
} else if (Database::rw[p1].Government == gAnarchy) {
result = eAnarchy;
lastEndClientCommand = scReject; // enable cancel treaty
pContacted = p1;
} else if (command >= sExecute) { // contact request
pContacted = p1;
pDipActive = pContacted;
assert(Database::mode == Database::moPlaying);
inform(pDipActive);
changeClientWhenDone(scContact, pDipActive, &pTurn, 4);
}
} else if ((command & 0xFF0F) == sSetAttitude || (command & 0xFF0F) == sSetAttitude - sExecute) {
const int p1 = (command >> 4) & 0xF;
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= nAttitude || p1 >= nPl || !playerCtx.EnemyReport[p1]) {
result = eInvalid;
} else if (playerCtx.Treaty[p1] == trNoContact) {
result = eNoPreq;
} else if (playerCtx.Attitude[p1] == subject) {
result = eNotChanged;
} else if (command >= sExecute) {
playerCtx.Attitude[p1] = subject;
Database::rw[p1].EnemyReport[player]->Attitude = subject;
}
} else if ((command & ~0x70) == sSetSpyMission || (command & ~0x70) == sSetSpyMission - sExecute) {
if (((command >> 4) & 0xF) < nSpyMission && command >= sExecute)
spyMission = (command >> 4) & 0xF;
} else if ((command & ~0x3F0) == sStartJob || (command & ~0x3F0) == sStartJob - sExecute) {
TPlayerContext &playerCtx = Database::rw[player];
int loc0 = (subject < playerCtx.nUn) ? (*playerCtx.Un)[subject].Loc : -1;
const int newJob = (command >> 4) & 0x3F;
if (subject >= playerCtx.nUn || loc0 < 0 || newJob >= nJob) {
result = eInvalid;
} else {
result = UnitProcessing::startJob(player, subject, newJob, command < sExecute);
if (result == eCity) { // new city
const int cix1 = playerCtx.nCity - 1;
CityProcessing::addBestCityTile(player, cix1);
if (Database::mode == Database::moPlaying)
savedTiles[static_cast<std::size_t>(cix1)] = 0; // save in every case
if (Database::mode >= Database::moMovie) // show new city in interface modules
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != player &&
(Database::observeLevel[loc0] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc0);
}
}
} else if ((command & ~0x3F0) == sSetDevModelCap || (command & ~0x3F0) == sSetDevModelCap - sExecute) {
TPlayerContext &playerCtx = Database::rw[player];
if (subject >= nFeature) {
result = eInvalid;
} else if (devModelTurn[player] != Database::gTurn) {
result = eNoModel;
} else {
const int newCap = (command >> 4) & 0x3F;
TModel &devModel = playerCtx.DevModel;
if (((1 << devModel.Domain) & Feature[subject].Domains) == 0) {
result = eDomainMismatch;
} else if (!(Feature[subject].Preq == preNone ||
(Feature[subject].Preq == preSun && Database::gWonder[woSun].EffectiveOwner == player) ||
(Feature[subject].Preq >= 0 && playerCtx.Tech[Feature[subject].Preq] >= tsApplicable))) {
result = eNoPreq;
} else {
int minCap = ((AutoFeature >> subject) & 1) || subject == mcDefense ? 1 : 0;
int maxCap;
if (subject >= mcFirstNonCap) {
maxCap = 1;
} else if (subject == mcDefense) {
maxCap = (devModel.Domain == dGround) ? 2 : 3;
if (playerCtx.Tech[adSteel] >= tsApplicable)
++maxCap;
} else {
maxCap = 8;
}
const int capWeight =
(devModel.Domain == dGround && subject == mcDefense) ? 2 : Feature[subject].Weight;
if (newCap < minCap || newCap > maxCap ||
devModel.Weight + (newCap - devModel.Cap[subject]) * capWeight > devModel.MaxWeight) {
result = eViolation;
} else if (command >= sExecute) {
devModel.Cap[subject] = static_cast<std::uint8_t>(newCap);
// mutual feature exclusion
switch (subject) {
case mcSub:
if (Database::serverVersion[player] >= 0x010103)
devModel.Cap[mcSeaTrans] = 0;
devModel.Cap[mcArtillery] = 0;
devModel.Cap[mcCarrier] = 0;
if (devModel.Cap[mcDefense] > 2)
devModel.Cap[mcDefense] = 2;
break;
case mcSeaTrans:
if (Database::serverVersion[player] >= 0x010103)
devModel.Cap[mcSub] = 0;
break;
case mcCarrier:
case mcArtillery:
devModel.Cap[mcSub] = 0;
break;
case mcAlpine:
devModel.Cap[mcOver] = 0;
devModel.Cap[mcMob] = 0;
break;
case mcOver:
devModel.Cap[mcAlpine] = 0;
break;
case mcMob:
devModel.Cap[mcAlpine] = 0;
break;
default:
break;
}
Database::calculateModel(devModel);
}
}
}
} else if ((command & ~0xF0) == sCreateUnit || (command & ~0xF0) == sCreateUnit - sExecute) {
const int p1 = (command >> 4) & 0xF;
const int loc1 = static_cast<int>(reinterpret_cast<std::intptr_t>(data));
const TModel &model = (*Database::rw[p1].Model)[subject];
if ((Database::occupant[loc1] >= 0 && p1 != Database::occupant[loc1]) ||
((Database::realMap[loc1] & fCity) && (Database::realMap[loc1] >> 27) != static_cast<std::uint32_t>(p1)) ||
(model.Domain < dAir && (model.Domain == dSea) != ((Database::realMap[loc1] & fTerrain) <
static_cast<std::uint32_t>(fGrass)))) {
result = eViolation;
} else if (command >= sExecute) {
Database::createUnit(p1, subject);
TPlayerContext &targetCtx = Database::rw[p1];
(*targetCtx.Un)[targetCtx.nUn - 1].Loc = loc1;
Database::placeUnit(p1, targetCtx.nUn - 1);
Database::updateUnitMap(loc1);
}
} else if (command >= cClientEx) {
if (Database::processClientData[player] || Database::mode == Database::moPlaying)
callPlayer(command, player, data);
} else {
result = eUnknown;
}
break;
}
// do not log invalid and non-relevant commands
if (result == eZOC_EnemySpotted) {
assert(Database::mode == Database::moPlaying);
Database::cl.setState(formerClState);
Database::intServer(sIntDiscoverZOC, player, 0, &zocTile);
} else if ((result & rEffective) == 0) {
if (Database::mode < Database::moPlaying) {
loadOK = false;
} else {
if (logged)
Database::cl.setState(formerClState);
if (result < rExecuted && command >= sExecute)
putMessage((1 << 16) + 1,
QStringLiteral("INVALID: %1 calls %2 (%3)").arg(player).arg(command, 0, 16).arg(subject));
}
}
if ((command & (cClientEx | sExecute | sctMask)) == (sExecute | sctEndClient) && result >= rExecuted)
lastEndClientCommand = command;
return result;
}
} // namespace
void init(const NotifyFunction &notifyFunction)
{
notify = notifyFunction;
previewElevation = false;
playersBrain.fill(nullptr);
playerBrain.fill(nullptr);
brains.clear();
brainNoTerm = &brains.addNew();
brainNoTerm->fileName = QStringLiteral(":AIT");
brainNoTerm->flags = 0;
brainNoTerm->initialized = false;
brainNoTerm->kind = BrainType::NoTerm;
brainSuperVirtual = &brains.addNew();
brainSuperVirtual->fileName = QStringLiteral(":Supervisor");
brainSuperVirtual->flags = 0;
brainSuperVirtual->initialized = false;
brainSuperVirtual->kind = BrainType::SuperVirtual;
if (networkEnabled) {
brainNetworkClient = &brains.addNew();
brainNetworkClient->fileName = QStringLiteral(":NetworkClient");
brainNetworkClient->flags = fMultiple;
brainNetworkClient->initialized = false;
brainNetworkClient->serverVersion = CevoVersion;
brainNetworkClient->kind = BrainType::NetworkClient;
}
brainTerm = &brains.addNew();
brainTerm->fileName = QStringLiteral(":StdIntf");
brainTerm->flags = fMultiple;
brainTerm->initialized = false;
brainTerm->serverVersion = CevoVersion;
brainTerm->kind = BrainType::Term;
brainRandom = &brains.addNew();
brainRandom->fileName = QStringLiteral(":Random");
brainRandom->flags = fMultiple;
brainRandom->initialized = false;
brainRandom->kind = BrainType::Random;
if (networkEnabled) {
brainNetworkServer = &brains.addNew();
brainNetworkServer->fileName = QStringLiteral(":NetworkServer");
brainNetworkServer->flags = fMultiple;
brainNetworkServer->initialized = false;
brainNetworkServer->serverVersion = CevoVersion;
brainNetworkServer->kind = BrainType::NetworkServer;
}
// get available brains
const QDir aiDir(getAiDir());
const QStringList entries = aiDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (const QString &name : entries) {
const QString basePath = aiDir.filePath(name);
auto newBrain = std::make_unique<Brain>();
newBrain->kind = BrainType::AI;
try {
newBrain->loadFromFile(QDir(basePath).filePath(name + QStringLiteral(".ai.txt")));
} catch (const std::exception &) {
// Disclosed deviation: the original has no try/except around
// LoadFromFile here, so one malformed AI spec file would crash
// the whole Init() - skipping just that one brain instead.
continue;
}
// DotNetClient/.NET AI module interop is not supported by this
// port (Windows/.NET-specific, no sensible cross-platform
// equivalent) - simplified from the original's `(Flags and
// fDotNet = 0) or (@DotNetClient <> nil)` accordingly.
if (newBrain->serverVersion >= FirstAICompatibleVersion && newBrain->serverVersion <= CevoVersion &&
(newBrain->flags & fDotNet) == 0 && !newBrain->dllName.isEmpty()) {
brains.add(std::move(newBrain));
}
}
if (brains.kindCount(BrainType::AI) == 0)
throw std::runtime_error(("No AI libraries found in directory " + getAiDir()).toStdString());
}
void done()
{
for (int i = 0; i < brains.count(); ++i) {
Brain &brain = brains[i];
if (brain.initialized) {
callClient(i, cReleaseModule, nullptr);
if (brain.kind == BrainType::AI && (brain.flags & fDotNet) == 0)
brain.module.unload();
}
}
playersBrain.fill(nullptr);
playerBrain.fill(nullptr);
brains.clear();
}
const std::uint32_t *previewMap(int landMass)
{
Database::lx = lxmax;
Database::ly = lymax;
Database::mapSize = Database::lx * Database::ly;
// TODO: needs LandMass/DelphiRandSeed/CreateElevation/CreateMap, which
// live in Database.pas's Map Editor section (not ported yet).
Q_UNUSED(landMass);
Q_UNUSED(previewElevation);
return Database::realMap.data();
}
QString getLogFileName()
{
return logFileName;
}
namespace {
constexpr QLatin1Char AutoSavePrefix('~');
QString fromAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (!info.fileName().isEmpty() && info.fileName().at(0) == AutoSavePrefix)
return info.path() + QLatin1Char('/') + info.fileName().mid(1);
return fileName;
}
}
QString toAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (info.fileName().isEmpty() || info.fileName().at(0) != AutoSavePrefix)
return info.path() + QLatin1Char('/') + AutoSavePrefix + info.fileName();
return fileName;
}
bool isAutoSaveFileName(const QString &fileName)
{
const QString name = QFileInfo(fileName).fileName();
return !name.isEmpty() && name.at(0) == AutoSavePrefix;
}
void changeClient()
{
const double t = nowPrecise();
putMessage((1 << 16) + 2, QStringLiteral("CLIENT: took %1 ms").arg((t - lastClientTime) * 1000.0, 0, 'f', 1));
lastClientTime = t;
putMessage((1 << 16) + 2,
QStringLiteral("CLIENT: calling %1 (%2)").arg(ccPlayer).arg(playerBrain[ccPlayer]->name()));
if (ccCommand == cTurn)
for (int p = 0; p < nPl; ++p)
if (p != ccPlayer && ((1 << p) & Database::gWatching))
callPlayer(cShowTurnChange, p, &ccPlayer);
const int p = ccPlayer;
ccPlayer = -1;
callPlayer(ccCommand, p, ccData.data());
if (Database::mode == Database::moPlaying && (playerBrain[p]->flags & aiThreaded) == 0 && ccPlayer < 0) {
notifyEvent(NotifyId::DeactivationMissing, p);
forceClientDeactivation();
}
}
void nextPlayer()
{
nextPlayerImpl();
}
void fillMap(std::uint32_t terrainType, bool specialResources)
{
if (specialResources) {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::editTile(loc1, terrainType | (0xFu << 27));
} else {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::realMap[loc1] = terrainType | (0xFu << 27);
}
}
void directHelp(int command)
{
initBrain(*brainTerm);
brainTerm->module.call(command, -1, nullptr);
aiCredits = QString(QChar(0));
}
void startNewGame(const QString &fileName, const QString &mapFileNameArg, int newlx, int newly, int newLandMass,
int newMaxTurn)
{
notifyEvent(NotifyId::StartDone);
savePath = QFileInfo(fileName).path();
logFileName = fileName;
mapFileName = mapFileNameArg;
Database::lx = newlx;
Database::ly = newly;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = mapFileName.isEmpty() ? newLandMass : 0;
maxTurn = newMaxTurn;
Database::delphiRandSeed = static_cast<std::int32_t>(QDateTime::currentMSecsSinceEpoch());
Database::rnd = Database::delphiRandSeed;
Database::mode = Database::moPlaying;
Database::cl = CmdList();
startGame();
noLogChanges();
callAllPlayers(cGetReady, nullptr);
logChanges();
Database::cl.put(sTurn, 0, 0, nullptr);
beforeTurn0();
noLogCityTileChanges();
generateStat(pTurn);
nLogOpened = -1;
lastEndClientCommand = -1;
callPlayer(cShowGame, 0, nullptr);
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::NetworkServer)
callPlayer(cShowGame, i, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cTurn, 0, nullptr, 0);
}
bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode)
{
savePath = QFileInfo(writeFileName).path();
logFileName = writeFileName;
loadTurn = turn;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
throw std::runtime_error(("Cannot open " + fileName).toStdString());
auto readInt32 = [&file]() {
std::int32_t value = 0;
file.read(reinterpret_cast<char *>(&value), 4);
return value;
};
char id[8];
file.read(id, 8); // file id, unused
const std::int32_t version = readInt32();
readInt32(); // exe time, unused
bool result = version >= FirstBookCompatibleVersion && version <= CevoVersion;
if (result) {
Database::lx = readInt32();
Database::ly = readInt32();
Database::mapSize = Database::lx * Database::ly;
Database::landMass = readInt32();
if (Database::landMass == 0) // use predefined map
file.read(reinterpret_cast<char *>(Database::realMap.data()), Database::mapSize * 4);
maxTurn = readInt32();
Database::rnd = readInt32();
Database::gTurn = readInt32();
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(((Database::mapSize - 1) / 4 + 1) * 4), 0);
file.read(reinterpret_cast<char *>(saveMap.data()), 4);
if (saveMap[0] != 0x80)
file.read(reinterpret_cast<char *>(saveMap.data() + 4), static_cast<qint64>(saveMap.size()) - 4);
for (int p1 = 0; p1 < nPl; ++p1) {
unsigned char header[4];
file.read(reinterpret_cast<char *>(header), 4);
if (header[0] == 0) {
playersBrain[p1] = nullptr;
continue;
}
const int len = header[0];
// Pascal shortstring-style decoding: matches SaveGame's (len div
// 4 + 1) * 4 total byte count, split here into the 4-byte
// header already read plus (len div 4) * 4 more bytes.
std::vector<char> buffer(static_cast<std::size_t>(4 + (len / 4) * 4), '\0');
std::memcpy(buffer.data(), header, 4);
if (len / 4 * 4 > 0)
file.read(buffer.data() + 4, len / 4 * 4);
const QString name = QString::fromLatin1(buffer.data() + 1, len);
originalDataVersion[p1] = readInt32();
readInt32(); // "behavior" string, always empty, kept for on-disk compatibility
Database::difficulty[p1] = readInt32();
Brain *found = nullptr;
for (int k = brains.count() - 1; k >= 0; --k) {
if (brains[k].fileName.compare(name, Qt::CaseInsensitive) == 0) {
found = &brains[k];
break;
}
}
if (!found) { // ai not found -- replace by local player
Database::processClientData[p1] = false;
notifyMessage = name;
notifyEvent(NotifyId::AiError);
found = brainTerm;
} else {
Database::processClientData[p1] = true;
}
if (found->kind == BrainType::NoTerm) // crashed tournament -- load as supervisor
found = brainSuperVirtual;
playersBrain[p1] = found;
}
}
if (result)
Database::cl.loadFromFile(file);
file.close();
if (!result)
return false;
notifyEvent(NotifyId::StartDone);
if (loadTurn < 0)
loadTurn = Database::gTurn;
if (movieMode)
Database::mode = Database::moMovie;
else if (loadTurn == 0)
Database::mode = Database::moLoading;
else
Database::mode = Database::moLoading_Fast;
loadOK = true;
startGame();
if (movieMode) {
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
} else {
notifyEvent(NotifyId::LoadBegin);
}
bool started = false;
bool statRequest = false;
movieStopped = false;
while (!movieStopped && Database::cl.progress() < 1000) {
const CmdListState formerClState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (p1 < 0)
p1 = pTurn;
if (statRequest && (command & (sctMask | sExecute)) != (sctInternal | sExecute)) {
generateStat(pTurn);
statRequest = false;
}
// complete all internal commands following an sTurn before generating statistics
if (command == sTurn && !started) {
for (int p2 = 0; p2 < nPl; ++p2)
if (playerBrain[p2] && (Database::mode != Database::moMovie || p2 == 0))
callPlayer(cReplay, p2, nullptr);
beforeTurn0();
if (movieMode) {
inform(pTurn);
callPlayer(cMovieTurn, 0, nullptr);
}
statRequest = true;
started = true;
} else if (command == sTurn && pTurn == 0 && Database::gTurn == loadTurn) {
assert(Database::cl.state().loadPos == formerClState.loadPos + 4); // size of sTurn
Database::cl.setState(formerClState);
Database::cl.cut();
break;
} else if (command == sIntDataChange) {
if (Database::processClientData[p1])
Database::cl.getDataChanges(static_cast<std::uint32_t *>(Database::rw[p1].Data),
playerBrain[p1]->dataSize);
else
Database::cl.getDataChanges(nullptr, 0);
} else {
if ((command & (sctMask | sExecute)) == (sctInternal | sExecute))
Database::intServer(command, p1, subject, data);
else {
statRequest = command == sTurn;
server(command, p1, subject, const_cast<void *>(data));
}
}
if (!movieMode)
notifyEvent(NotifyId::LoadState, Database::cl.progress() * 128 / 1000);
}
if (movieMode) {
notifyEvent(NotifyId::BackOn);
playerBrain[0]->module.call(cBreakGame, -1, nullptr);
endGame();
notifyEvent(NotifyId::StartGo);
return false;
}
if (statRequest)
generateStat(pTurn);
assert(started);
noLogChanges();
noLogCityTileChanges();
if (isAutoSaveFileName(logFileName)) {
logFileName = fromAutoSaveFileName(logFileName);
nLogOpened = -1;
} else {
nLogOpened = Database::cl.state().nLog;
}
Database::mode = Database::moPlaying;
lastEndClientCommand = -1;
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0)
Database::discoverAll(pTurn, Database::lObserveSuper); // supervisor - all tiles visible
else
Database::discoverViewAreas(pTurn);
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
Database::recalcPeaceMap(p1);
TUnitInfo *enemyUn = *Database::rw[p1].EnemyUn;
for (int ix = 0; ix < Database::rw[p1].nEnemyUn; ++ix)
enemyUn[ix].emix = static_cast<std::uint16_t>(Database::rwemix[p1][enemyUn[ix].Owner][enemyUn[ix].mix]);
inform(p1);
}
}
notifyEvent(NotifyId::EndInfo);
if (!loadOK) {
notifyMessage = logFileName;
notifyEvent(NotifyId::LoadError);
}
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cResume, 0, nullptr, 0);
return true;
}
} // namespace GameServer
} // namespace Cevo