Files
c-evo-evo/game/GameServer.Server.cpp
T
2026-10-29 11:18:07 +01:00

1677 lines
74 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 "GameServerInternal.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 {
// 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 GameServer
} // namespace Cevo