diff --git a/game/include/Cevo/Database.h b/game/include/Cevo/Database.h index 52e0686..c5bff63 100644 --- a/game/include/Cevo/Database.h +++ b/game/include/Cevo/Database.h @@ -71,6 +71,10 @@ constexpr int nemmax = 1024; constexpr int necmax = 1024; constexpr int neumax = 4096; +// Database.pas's `TerrType_Canalable` set, as a bitmask indexed by fTerrain. +constexpr std::uint32_t terrTypeCanalableMask = (1u << fGrass) | (1u << fDesert) | (1u << fPrairie) | + (1u << fTundra) | (1u << fSwamp) | (1u << fForest) | (1u << fHills); + // Equivalent of Database.pas's TGameMode - ordinal comparisons () match // the original's enum declaration order. enum GameMode { moLoading_Fast, moLoading, moMovie, moPlaying }; @@ -100,6 +104,10 @@ extern int gWatching; extern int gAI; extern int gTurn; // current turn extern int gTestFlags; +extern std::array founded; // number of cities founded per player +// Debug-only cross-check (Database.pas's `{$IFOPT O-}InvalidTreatyMap`): +// bitset of players whose territory must not be considered mid-command. +extern int invalidTreatyMap; extern std::array gWonder; extern std::array grWallContinent; // continent id the Great Wall was built on, -1 if none extern std::array gShip; @@ -199,6 +207,29 @@ void freeUnit(int p, int uix); // to that player (use only from inside sMoveUnit if attack). void removeUnit(int p, int uix, int enemy = -1); void removeUnitUpdateMap(int p, int uix); +void removeDomainUnits(int d, int p, int loc); +void foundCity(int p, int foundLoc); + +// Database.pas's own formula function (originally in Protocol.pas), used +// only by actualSpecialTile() to recompute hidden special-resource bits +// after a terrain change (ClearTerrain/AfforestTerrain/TransTerrain jobs). +int specialTile(int loc, int terrType, int lx); +std::uint32_t actualSpecialTile(int loc); + +// Applies a completed terrain improvement job's effect to the map. +void completeJob(int p, int loc, int job); + +// --- Territory Calculation --- + +// OriginLoc: only changes in CountryRadius around this location possible, +// -1 for complete map, -2 for double-check (debug only). PlayerLosingCity: +// do nothing but remove tiles no longer in reach from this player's +// territory, -1 for full border recalculation. +void checkBorders(int originLoc, int playerLosingCity = -1); +void logCheckBorders(int p, int cix, int playerLosingCity = -1); + +// recalculate fPeace flags for the whole map +void recalcPeaceMap(int p); // --- Diplomacy --- diff --git a/game/include/Cevo/UnitProcessing.h b/game/include/Cevo/UnitProcessing.h new file mode 100644 index 0000000..431023a --- /dev/null +++ b/game/include/Cevo/UnitProcessing.h @@ -0,0 +1,85 @@ +// 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. + +#pragma once + +#include "Cevo/Protocol.h" + +#include + +namespace Cevo { +namespace UnitProcessing { + +// Equivalent of UnitProcessing.pas (~1469 lines): unit movement/combat, +// terrain improvement jobs, and their Start/End Game hooks. Private +// implementation-section helpers (Controlled/GetMoveCost/CalculateJobWork) +// live in an anonymous namespace in UnitProcessing.cpp, matching the +// original's own interface/implementation visibility split. + +enum TMoveType { mtInvalid, mtMove, mtCapture, mtSpyMission, mtAttack, mtBombard, mtExpel }; + +struct TMoveInfo { + TMoveType MoveType = mtInvalid; + int Cost = 0; + int ToMaster = -1; + int EndHealth = 0; + int Defender = -1; + int Dcix = -1; + int Duix = -1; + int EndHealthDef = -1; + bool MountainDelay = false; +}; + +extern int uixSelectedTransport; +extern std::array worked; // settler work statistics + +// --- Moving/Combat --- + +int hostileDamage(int p, int mix, int loc, int mp); +int calculateMove(int p, int uix, int toLoc, int moveLength, bool testOnly, TMoveInfo &moveInfo); +int getBattleForecast(int loc, TBattleForecast &battleForecast, int &duix, int &dcix, int &aStr, int &dStr, + int &aBaseDamage, int &dBaseDamage); +int loadUnit(int p, int uix, bool testOnly); +int unloadUnit(int p, int uix, bool testOnly); +void recover(int p, int uix); +int getMoveAdvice(int p, int uix, TMoveAdviceData &a); +bool canPlaneReturn(int p, int uix, const TPlaneReturnData &planeReturnData); + +// --- Terrain Improvement --- + +int startJob(int p, int uix, int newJob, bool testOnly); +bool work(int p, int uix); +int getJobProgress(int p, int loc, TJobProgressData &jobProgressData); + +// --- Start/End Game --- + +void initGame(); +void releaseGame(); + +} // namespace UnitProcessing +} // namespace Cevo diff --git a/game/src/Database.cpp b/game/src/Database.cpp index ba13ed4..3a328b5 100644 --- a/game/src/Database.cpp +++ b/game/src/Database.cpp @@ -30,6 +30,7 @@ #include #include +#include #include #include @@ -55,6 +56,8 @@ int gWatching = 0; int gAI = 0; int gTurn = 0; int gTestFlags = 0; +std::array founded{}; +int invalidTreatyMap = 0; std::array gWonder{}; std::array grWallContinent{}; std::array gShip{}; @@ -78,6 +81,14 @@ int primitive = 0; // (number of units built, used to assign unique per-player unit IDs). std::array unBuilt{}; +// Equivalent of Database.pas's private `TerritoryCount: array[0..nPl]`. +std::array territoryCount{}; + +// Equivalent of Database.pas's private `BorderChanges` (sIntExpandTerritory +// and $F == 8 packed Cardinal words, 4 bits per tile in the CountryRadius +// area around a city). +std::array borderChanges{}; + // Equivalent of Database.pas's private FreeSlaves(). void freeSlaves() { @@ -99,6 +110,11 @@ void countLost(int p, int mix, int enemy) tellAboutModel(enemy, p, mix); ++destroyed[enemy][p][mix]; } + +// Forward declarations: defined further below (Territory Calculation +// section), needed earlier by intServer()'s sIntExpandTerritory case. +void changeTerritory(int loc, int p); +void expandTerritory(int originLoc); } // namespace void maskD(std::uint32_t *x, int count, std::uint32_t mask) @@ -639,6 +655,175 @@ void removeUnitUpdateMap(int p, int uix) updateUnitMap(loc0); } +void removeDomainUnits(int d, int p, int loc) +{ + TPlayerContext &player = rw[p]; + TUn *un = *player.Un; + const TModel *model = *player.Model; + for (int uix = 0; uix < player.nUn; ++uix) + if (model[un[uix].mix].Domain == d && un[uix].Loc == loc) + removeUnit(p, uix); +} + +int specialTile(int loc, int terrType, int lx) +{ + if (terrType == fOcean) + return 0; + const int y = loc / lx; + const int x = loc - y * lx; + if (terrType == fGrass) { // formula for productive grassland + const int v1 = lymax + x - (y >> 1); + return (((v1 >> 1) + x + ((y + 1) >> 1)) & 1) ? 1 : 0; + } + // formula for special resources + const int a = 4 * x - y + 9980; + const int qx = a / 10; + if (qx * 10 != a || (qx & 3) == 0) + return 0; + const int qy = (y + x) / 5; + if ((qy & 3) == ((qx >> 2) & 1) * 2) + return 0; + if (terrType == fArctic || terrType == fSwamp) + return 1; + if (terrType == fShore) { + if (((qx + qy) & 1) == 0) + return (qx & 3) == 2 ? 2 : 1; + return 0; + } + return ((qx + qy) & 1) + 1; +} + +std::uint32_t actualSpecialTile(int loc) +{ + return static_cast(specialTile(loc, static_cast(realMap[loc] & fTerrain), lx)); +} + +void foundCity(int p, int foundLoc) +{ + TPlayerContext &player = rw[p]; + if (player.nCity == nCmax) + return; + ++player.nCity; + TCity &city = (*player.City)[player.nCity - 1]; + city.Size = 2; + city.Status = 0; + city.SavedStatus = 0; + std::fill(std::begin(city.Built), std::end(city.Built), 0); + city.Food = 0; + city.Project = cpImp + imTrGoods; + city.Prod = 0; + city.Project0 = city.Project; + city.Prod0 = 0; + city.Pollution = 0; + city.N1 = 0; + city.Loc = foundLoc; + if (usedByCity[foundLoc] >= 0) { // central tile is exploited - toggle in exploiting city + int p1 = p; + int cix1; + searchCity(usedByCity[foundLoc], p1, cix1); + int dx, dy; + dxdy(usedByCity[foundLoc], foundLoc, dx, dy); + const int v21 = ((dy + 3) << 2) + ((dx + 3) >> 1); + (*rw[p1].City)[cix1].Tiles &= ~(1u << v21); + } + city.Tiles = 1u << 13; // exploit central tile + usedByCity[foundLoc] = foundLoc; + realMap[foundLoc] = + (realMap[foundLoc] & (fTerrain | fSpecial | fRiver | (static_cast(nPl) << 27))) | fCity; + + changeTerritory(city.Loc, p); +} + +void completeJob(int p, int loc, int job) +{ + assert(job != jCity); + int changedTerrain = -1; + switch (job) { + case jRoad: + realMap[loc] |= fRoad; + break; + case jRR: + realMap[loc] = (realMap[loc] & ~static_cast(fRoad)) | fRR; + break; + case jClear: + changedTerrain = Terrain[realMap[loc] & fTerrain].ClearTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + break; + case jIrr: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiIrrigation; + break; + case jFarm: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFarm; + break; + case jAfforest: + changedTerrain = Terrain[realMap[loc] & fTerrain].AfforestTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + break; + case jMine: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiMine; + break; + case jFort: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFort; + break; + case jCanal: + realMap[loc] |= fCanal; + break; + case jTrans: + changedTerrain = Terrain[realMap[loc] & fTerrain].TransTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + if (((terrTypeCanalableMask >> (realMap[loc] & fTerrain)) & 1) == 0) { + removeDomainUnits(dSea, p, loc); + realMap[loc] &= ~static_cast(fCanal); + } + break; + case jPoll: + realMap[loc] &= ~static_cast(fPoll); + break; + case jBase: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiBase; + break; + case jPillage: + if (realMap[loc] & fTerImp) { + if ((realMap[loc] & fTerImp) == tiBase) + removeDomainUnits(dAir, p, loc); + realMap[loc] &= ~static_cast(fTerImp); + } else if (realMap[loc] & fCanal) { + removeDomainUnits(dSea, p, loc); + realMap[loc] &= ~static_cast(fCanal); + } else if (realMap[loc] & fRR) { + realMap[loc] = (realMap[loc] & ~static_cast(fRR)) | fRoad; + } else if (realMap[loc] & fRoad) { + realMap[loc] &= ~static_cast(fRoad); + } + break; + default: + break; + } + + if (changedTerrain >= 0) { // remove terrain improvements if not possible on new terrain + if (((realMap[loc] & fTerImp) == tiIrrigation || (realMap[loc] & fTerImp) == tiFarm) && + (Terrain[changedTerrain].IrrClearWork == 0 || Terrain[changedTerrain].ClearTerrain >= 0)) + realMap[loc] &= ~static_cast(fTerImp); + if ((realMap[loc] & fTerImp) == tiMine && + (Terrain[changedTerrain].MineAfforestWork == 0 || Terrain[changedTerrain].AfforestTerrain >= 0)) + realMap[loc] &= ~static_cast(fTerImp); + } + + // update map of all observing players + if (mode > moLoading_Fast) { + constexpr std::uint32_t mask = fTerrain | fSpecial | fTerImp | fRoad | fRR | fCanal | fPoll; + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & (gAlive | gWatching)) && (((observeLevel[loc] >> (2 * p1)) & 3) > lNoObserve)) { + std::uint32_t &tile = (*rw[p1].Map)[loc]; + tile = (tile & ~mask) | (realMap[loc] & mask); + } + } + } +} + void introduceEnemy(int p1, int p2) { rw[p1].Treaty[p2] = trNone; @@ -703,13 +888,18 @@ void intServer(int command, int player, int subject, const void *data) rwemix[p1][player][subject] = static_cast(toldPlayer.nEnemyModel); ++toldPlayer.nEnemyModel; assert(toldPlayer.nEnemyModel < nemmax); + } else if (command == sIntExpandTerritory) { + if (mode < moPlaying) { + std::memcpy(borderChanges.data(), data, sizeof(borderChanges)); + expandTerritory((*rw[player].City)[subject].Loc); + } } // Other sIntXxx cases (sIntHaveContact/sIntCancelTreaty/sIntDiscoverZOC/ - // sIntExpandTerritory/sIntBuyMaterial/sIntPayPrices/sIntSetDevModel/ - // sIntSetXxxStatus) are NOT implemented yet - each needs its own - // not-yet-ported Database.pas function (CancelTreaty, Discover9, - // ExpandTerritory, PayPrice, DiscoverViewAreas, ...). Add them here once - // those exist - see repo memory for the current dependency-chain status. + // sIntBuyMaterial/sIntPayPrices/sIntSetDevModel/sIntSetXxxStatus) are NOT + // implemented yet - each needs its own not-yet-ported Database.pas + // function (CancelTreaty, Discover9, PayPrice, DiscoverViewAreas, ...). + // Add them here once those exist - see repo memory for the current + // dependency-chain status. } void tellAboutModel(int p, int taOwner, int tamix) @@ -1102,5 +1292,209 @@ void updateUnitMap(int loc, bool cityChange) } } +void recalcPeaceMap(int p) +{ + if (mode != moPlaying) + return; + TPlayerContext &player = rw[p]; + maskD(*player.Map, mapSize, ~static_cast(fPeace)); + std::array peacePlayer{}; // index p1+1, covers p1 in -1..nPl-1 + for (int p1 = 0; p1 < nPl; ++p1) + peacePlayer[p1 + 1] = p1 != p && ((1 << p1) & gAlive) && + (player.Treaty[p1] == trPeace || player.Treaty[p1] == trFriendlyContact); + std::uint32_t *map = *player.Map; + const TOwnerList &territory = *player.Territory; + for (int loc = 0; loc < mapSize; ++loc) + if (peacePlayer[territory[loc] + 1]) + map[loc] |= fPeace; +} + +namespace { +void changeTerritory(int loc, int p) +{ + assert(p >= 0); // no player's territory indicated by p == nPl + --territoryCount[realMap[loc] >> 27]; + ++territoryCount[p]; + realMap[loc] = (realMap[loc] & ~(0xFu << 27)) | (static_cast(p) << 27); + if (p == 0xF) + p = -1; + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & (gAlive | gWatching)) == 0) + continue; + TPlayerContext &player = rw[p1]; + if (((*player.Map)[loc] & fTerrain) == fUNKNOWN) + continue; + (*player.Territory)[loc] = static_cast(p); + // Faithful port of the original relying on x86 SHL masking the shift + // count to 5 bits when p==-1 (so `1 shl p` becomes `1 shl 31`, never + // matching gAlive, rather than C++'s real UB for negative shifts) - + // see repo memory's policy on preserving known upstream quirks. + if (p < nPl && p != p1 && ((1u << (p & 31)) & static_cast(gAlive)) && + (player.Treaty[p] == trPeace || player.Treaty[p] == trFriendlyContact)) + (*player.Map)[loc] |= fPeace; + else + (*player.Map)[loc] &= ~static_cast(fPeace); + } +} + +void expandTerritory(int originLoc) +{ + if (originLoc == -1) + throw std::runtime_error("Location error"); + int i = 0; + int dyMax = 0; + while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) + ++dyMax; + for (int dy = -dyMax; dy <= dyMax; ++dy) { + int dxMax = dy & 1; + while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) + dxMax += 2; + for (int dx = -dxMax; dx <= dxMax; ++dx) { + if (((dy + dx) & 1) == 0) { + const std::uint32_t newOwner = (borderChanges[i / 8] >> ((i % 8) * 4)) & 0xF; + const int loc = dLoc(originLoc, dx, dy); + if (loc >= 0 && newOwner != (realMap[loc] >> 27)) + changeTerritory(loc, static_cast(newOwner)); + ++i; + } + } + } +} +} // namespace + +void checkBorders(int originLoc, int playerLosingCity) +{ + std::array country{}; + std::array formerCountry{}; + std::array dist{}; + std::array formerDist{}; + std::array stolenDist{}; + std::array, nPl + 1> atPeace{}; + Vicinity8Loc adjacent; + + constexpr std::uint32_t noZocTerrainMask = (1u << fShore) | (1u << fMountains) | (1u << fArctic); + + if (playerLosingCity >= 0) { + for (int loc = 0; loc < mapSize; ++loc) + stolenDist[loc] = static_cast(CountryRadius + 1); + for (int cix = 0; cix < rw[playerLosingCity].nCity; ++cix) { + const int loc = (*rw[playerLosingCity].City)[cix].Loc; + if (loc >= 0) + stolenDist[loc] = 0; + } + + for (int r = 1; r <= (CountryRadius >> 1); ++r) { + formerDist = stolenDist; + for (int loc = 0; loc < mapSize; ++loc) { + if (formerDist[loc] <= CountryRadius - 2 && + ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + const int newDist = formerDist[loc] + 2 + (v8 & 1); + if (loc1 >= 0 && loc1 < mapSize && newDist < stolenDist[loc1]) + stolenDist[loc1] = static_cast(newDist); + } + } + } + } + } + + country.fill(-1); + for (int loc = 0; loc < mapSize; ++loc) + dist[loc] = static_cast(CountryRadius + 1); + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gAlive) == 0) + continue; + for (int cix = 0; cix < rw[p1].nCity; ++cix) { + const int loc = (*rw[p1].City)[cix].Loc; + if (loc >= 0) { + country[loc] = static_cast(p1); + dist[loc] = 0; + } + } + } + + for (int r = 1; r <= (CountryRadius >> 1); ++r) { + formerCountry = country; + formerDist = dist; + for (int loc = 0; loc < mapSize; ++loc) { + if (formerDist[loc] <= CountryRadius - 2 && + ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { + assert(formerCountry[loc] >= 0); + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + const int newDist = formerDist[loc] + 2 + (v8 & 1); + if (loc1 >= 0 && loc1 < mapSize && newDist < dist[loc1]) { + country[loc1] = formerCountry[loc]; + dist[loc1] = static_cast(newDist); + } + } + } + } + } + + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gAlive) == 0) + continue; + for (int p2 = 0; p2 < nPl; ++p2) + if (p2 != p1 && ((1 << p2) & gAlive) && rw[p1].Treaty[p2] >= trPeace) + atPeace[p1][p2] = true; + } + + if (originLoc >= 0) { + int i = 0; + borderChanges.fill(0); + int dyMax = 0; + while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) + ++dyMax; + for (int dy = -dyMax; dy <= dyMax; ++dy) { + int dxMax = dy & 1; + while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) + dxMax += 2; + for (int dx = -dxMax; dx <= dxMax; ++dx) { + if (((dy + dx) & 1) == 0) { + const int loc = dLoc(originLoc, dx, dy); + if (loc >= 0) { + const int oldOwner = static_cast(realMap[loc] >> 27); + int newOwner = country[loc] & 0xF; + if (newOwner != oldOwner) { + if (atPeace[newOwner][oldOwner] && + !(oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius)) + newOwner = oldOwner; // peace fixes borders + else + changeTerritory(loc, newOwner); + } + borderChanges[i >> 3] |= static_cast(newOwner) << ((i & 7) * 4); + } + ++i; + } + } + } + } else { + for (int loc = 0; loc < mapSize; ++loc) { + const int oldOwner = static_cast(realMap[loc] >> 27); + const int newOwner = country[loc] & 0xF; + if (newOwner != oldOwner && + (!atPeace[newOwner][oldOwner] || (oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius))) { + assert(originLoc != -2); // test if border saving works + changeTerritory(loc, newOwner); + } + } + } + +#ifndef NDEBUG + if (originLoc != -2) + checkBorders(-2); // check: single pass should do! +#endif +} + +void logCheckBorders(int p, int cix, int playerLosingCity) +{ + checkBorders((*rw[p].City)[cix].Loc, playerLosingCity); + intServer(sIntExpandTerritory, p, cix, borderChanges.data()); +} + } // namespace Database } // namespace Cevo diff --git a/game/src/UnitProcessing.cpp b/game/src/UnitProcessing.cpp new file mode 100644 index 0000000..d529624 --- /dev/null +++ b/game/src/UnitProcessing.cpp @@ -0,0 +1,1202 @@ +// 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 "Cevo/UnitProcessing.h" + +#include "Cevo/Database.h" +#include "Cevo/IPQ.h" + +#include +#include +#include + +namespace Cevo { +namespace UnitProcessing { + +int uixSelectedTransport = 0; // matches Pascal's zero-initialized global +std::array worked{}; + +namespace { + +constexpr int eMountains = 0x6000FFFF; // additional return code for server internal use + +// tile control flags +constexpr int coKnown = 0x02; +constexpr int coTrue = 0x04; + +// ContraJobs[newJob]: bitset (1 << job) of jobs that get cancelled when +// newJob is started on the same tile. +constexpr std::array contraJobs = { + static_cast(0), // jNone + static_cast(1u << jCity), // jRoad + static_cast(1u << jCity), // jRR + static_cast((1u << jCity) | (1u << jTrans)), // jClear + static_cast((1u << jCity) | (1u << jFarm) | (1u << jAfforest) | (1u << jMine) | (1u << jBase) | + (1u << jFort)), // jIrr + static_cast((1u << jCity) | (1u << jIrr) | (1u << jAfforest) | (1u << jMine) | (1u << jBase) | + (1u << jFort)), // jFarm + static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jTrans)), // jAfforest + static_cast((1u << jCity) | (1u << jTrans) | (1u << jIrr) | (1u << jFarm) | (1u << jBase) | + (1u << jFort)), // jMine + static_cast((1u << jCity) | (1u << jTrans)), // jCanal + static_cast((1u << jCity) | (1u << jClear) | (1u << jAfforest) | (1u << jMine) | + (1u << jCanal)), // jTrans + static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jMine) | (1u << jBase)), // jFort + static_cast(1u << jCity), // jPoll + static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jMine) | (1u << jFort)), // jBase + static_cast(1u << jCity), // jPillage + static_cast(((1u << jPillage) << 1) - (1u << jRoad)), // jCity: jRoad..jPillage +}; + +// Equivalent of the private `ToWork: ^TToWorkList` (work left for each tile +// and job), sized to the map at initGame() instead of a GetMem block sized +// to the theoretical TToWorkList bound. +std::vector> toWork; + +// whether tile at loc is in control zone of enemy unit; returns a +// combination of the tile control flags above. +int controlled(int p, int loc, bool isDest) +{ + if (isDest && Database::occupant[loc] == p && Database::zocMap[loc] > 0) + return 0; + int result = 0; + if ((Database::realMap[loc] & fCity) == 0 || + (static_cast(Database::realMap[loc] >> 27) != p && Database::serverVersion[p] >= 0x000EF0)) { + Database::Vicinity8Loc adjacent; + Database::v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + if (loc1 >= 0 && loc1 < Database::mapSize && Database::zocMap[loc1] > 0 && Database::occupant[loc1] >= 0 && + Database::occupant[loc1] != p && Database::rw[p].Treaty[Database::occupant[loc1]] < trAlliance) { + if ((Database::observeLevel[loc1] & (3u << (p * 2))) > 0) { + return coKnown | coTrue; + } else { + result = coTrue; + } + } + } + } + return result; +} + +// MoveLength - 2 for short move, 3 for long move +int getMoveCost(int p, int mix, int fromLoc, int toLoc, int moveLength, int &moveCost) +{ + int result = eOK; + const std::uint32_t fromTile = Database::realMap[fromLoc]; + const std::uint32_t toTile = Database::realMap[toLoc]; + const TModel &model = (*Database::rw[p].Model)[mix]; + switch (model.Domain) { + case dGround: + if ((toTile & fTerrain) >= fGrass) { // domain ok, valid move + if ((fromTile & (fRR | fCity)) != 0 && (toTile & (fRR | fCity)) != 0) { + if (Database::gWonder[woShinkansen].EffectiveOwner == p) + moveCost = 0; + else + moveCost = (model.Speed * (4 * 1311)) >> 17; // move along railroad + } else if (((fromTile & (fRoad | fRR | fCity)) != 0 && (toTile & (fRoad | fRR | fCity)) != 0) || + (fromTile & toTile & (fRiver | fCanal)) != 0 || model.Cap[mcAlpine] > 0) { + // move along road, river or canal + moveCost = (model.Cap[mcOver] > 0) ? 40 : 20; + } else if (model.Cap[mcOver] > 0) { + result = eNoRoad; + } else { + switch (Terrain[toTile & fTerrain].MoveCost) { + case 1: + moveCost = 50; // plain terrain + break; + case 2: + assert(model.Speed - 150 <= 600); + moveCost = 50 + (((model.Speed - 150) * 13) >> 7); // heavy terrain + break; + case 3: + moveCost = model.Speed; + return eMountains; + } + } + moveCost *= moveLength; + } else { + result = eDomainMismatch; + } + break; + + case dSea: + if ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) < fGrass) { // domain ok + if ((toTile & fTerrain) != fOcean || model.Cap[mcNav] > 0) + moveCost = 50 * moveLength; // valid move + else + result = eNoNav; // navigation required for open sea + } else { + result = eDomainMismatch; + } + break; + + case dAir: + moveCost = 50 * moveLength; // always valid move + break; + } + return result; +} + +} // namespace + +// --- Moving/Combat --- + +int hostileDamage(int p, int mix, int loc, int mp) +{ + const std::uint32_t tile = Database::realMap[loc]; + const TModel &model = (*Database::rw[p].Model)[mix]; + if (model.Domain >= dSea || (model.Kind == mkSettler && model.Speed >= 200) || + (tile & (fCity | fRiver | fCanal)) != 0 || (tile & fTerImp) == tiBase || + Database::gWonder[woGardens].EffectiveOwner == p) { + return 0; + } else if ((tile & fTerrain) == fDesert && (tile & fSpecial) != fSpecial1 /* Oasis */) { + assert((tile & fTerImp) != tiIrrigation && (tile & fTerImp) != tiFarm); + return ((DesertThurst * mp - 1) / model.Speed) + 1; + } else if ((tile & fTerrain) == fArctic) { + assert((tile & fTerImp) != tiIrrigation && (tile & fTerImp) != tiFarm); + return ((ArcticThurst * mp - 1) / model.Speed) + 1; + } + return 0; +} + +int calculateMove(int p, int uix, int toLoc, int moveLength, bool testOnly, TMoveInfo &moveInfo) +{ + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + const TModel &pModel = (*player.Model)[un.mix]; + const int fromLoc = un.Loc; + + TBattleForecast battleForecast{}; + battleForecast.pAtt = p; + battleForecast.mixAtt = un.mix; + battleForecast.HealthAtt = un.Health; + battleForecast.ExpAtt = un.Exp; + battleForecast.FlagsAtt = static_cast(un.Flags); + battleForecast.Movement = un.Movement; + int aStr = 0, dStr = 0, aBaseDamage = 0, dBaseDamage = 0; + int result = getBattleForecast(toLoc, battleForecast, moveInfo.Duix, moveInfo.Dcix, aStr, dStr, aBaseDamage, dBaseDamage); + + if (result == eHiddenUnit) { + if (testOnly) + result = eOK; // behave just like unit was moving + else if (Database::mode > Database::moLoading_Fast) + (*player.Map)[toLoc] |= fHiddenUnit; + } + if (result == eStealthUnit) { + if (testOnly) + result = eOK; // behave just like unit was moving + else if (Database::mode > Database::moLoading_Fast) + (*player.Map)[toLoc] |= fStealthUnit; + } + if (result < rExecuted) + return result; + + switch (result) { + case eOK: + moveInfo.MoveType = mtMove; + break; + case eExpelled: + moveInfo.MoveType = mtExpel; + break; + default: + moveInfo.MoveType = mtAttack; + break; + } + + if (moveInfo.MoveType == mtMove) { + if (Database::mode == Database::moPlaying) { + const int p1 = static_cast(Database::realMap[toLoc] >> 27); + if (p1 < nPl && p1 != p && + (((static_cast(Database::realMap[un.Loc] >> 27) != static_cast(p1)) && + pModel.Kind != mkDiplomat && player.Treaty[p1] >= trPeace && player.Treaty[p1] < trAlliance) || + ((Database::realMap[toLoc] & fCity) != 0 && player.Treaty[p1] >= trPeace))) { + return eTreaty; // keep peace treaty! + } + } + if ((Database::realMap[toLoc] & fCity) != 0 && + static_cast(Database::realMap[toLoc] >> 27) != static_cast(p)) { // empty enemy city + if (pModel.Kind == mkDiplomat) { + moveInfo.MoveType = mtSpyMission; + } else if (pModel.Domain == dGround) { + if (pModel.Flags & mdCivil) + return eNoCapturer; + moveInfo.MoveType = mtCapture; + } else { + if (pModel.Domain == dSea && pModel.Cap[mcArtillery] == 0) + return eDomainMismatch; + if (pModel.Attack == 0 && !(pModel.Cap[mcBombs] > 0 && (un.Flags & unBombsLoaded) != 0)) + return eNoBombarder; + if (un.Movement < 100) + return eNoTime_Bombard; + moveInfo.MoveType = mtBombard; + result = eBombarded; + } + } + } + + moveInfo.MountainDelay = false; + if (moveInfo.MoveType == mtAttack || moveInfo.MoveType == mtBombard || moveInfo.MoveType == mtExpel) { + if (un.Master >= 0 || (pModel.Domain == dSea && (Database::realMap[fromLoc] & fTerrain) >= fGrass) || + (pModel.Domain == dAir && + ((Database::realMap[fromLoc] & fCity) != 0 || (Database::realMap[fromLoc] & fTerImp) == tiBase))) + return eViolation; + if (moveInfo.MoveType == mtBombard) { + moveInfo.EndHealth = un.Health; + moveInfo.EndHealthDef = -1; + } else { + moveInfo.EndHealth = battleForecast.EndHealthAtt; + moveInfo.EndHealthDef = battleForecast.EndHealthDef; + } + } else { // mtMove / mtCapture / mtSpyMission + if (un.Master >= 0 && pModel.Domain < dSea) { // transport unload + moveInfo.Cost = pModel.Speed; + if ((Database::realMap[toLoc] & fTerrain) < fGrass) + result = eDomainMismatch; + } else { + result = getMoveCost(p, un.mix, fromLoc, toLoc, moveLength, moveInfo.Cost); + if (result == eMountains) { + result = eOK; + moveInfo.MountainDelay = true; + } + } + if (result >= rExecuted && moveInfo.MoveType == mtSpyMission) + result = eMissionDone; + + moveInfo.ToMaster = -1; + TUn *allUn = *player.Un; + const TModel *allModel = *player.Model; + if (result == eDomainMismatch && pModel.Domain < dSea && pModel.Cap[mcOver] == 0) { + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { // check load to transport + TUn &un1 = allUn[uix1]; + if (un1.Loc == toLoc && + un1.TroopLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcSeaTrans]) { + result = eLoaded; + moveInfo.Cost = pModel.Speed; + moveInfo.ToMaster = uix1; + if (uixSelectedTransport >= 0 && uix1 == uixSelectedTransport) + break; + } + } + } else if (pModel.Domain == dAir && pModel.Cap[mcAirTrans] == 0 && (Database::realMap[toLoc] & fCity) == 0 && + (Database::realMap[toLoc] & fTerImp) != tiBase) { + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { + TUn &un1 = allUn[uix1]; + if (un1.Loc == toLoc && un1.AirLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcCarrier]) { // load plane to ship + result = eLoaded; + moveInfo.ToMaster = uix1; + if (uixSelectedTransport >= 0 && uix1 == uixSelectedTransport) + break; + } + } + } + if (result < rExecuted) + return result; + + if (un.Master < 0 && moveInfo.ToMaster < 0) + moveInfo.EndHealth = un.Health - hostileDamage(p, un.mix, toLoc, moveInfo.Cost); + else + moveInfo.EndHealth = un.Health; + + if (Database::mode == Database::moPlaying && (pModel.Flags & mdZOC) != 0 && un.Master < 0 && + moveInfo.ToMaster < 0 && controlled(p, fromLoc, false) >= coTrue) { + const int destControlled = controlled(p, toLoc, true); + if (destControlled >= coTrue + coKnown) + return eZOC; + else if (!testOnly && destControlled >= coTrue) + return eZOC_EnemySpotted; + } + if ((un.Movement == 0 && Database::serverVersion[p] >= 0x0100F1) || moveInfo.Cost > un.Movement) { + if (un.Master >= 0 || moveInfo.ToMaster >= 0) + return eNoTime_Load; + else + return eNoTime_Move; + } + if (moveInfo.EndHealth <= 0 || moveInfo.MoveType == mtSpyMission) + result |= rUnitRemoved; // spy mission or victim of HostileDamage + } + + if (moveInfo.MoveType == mtAttack || moveInfo.MoveType == mtExpel) { + moveInfo.Defender = Database::occupant[toLoc]; + } else if (Database::realMap[toLoc] & fCity) { // moveInfo.Dcix not set yet + moveInfo.Defender = static_cast(Database::realMap[toLoc] >> 27); + Database::searchCity(toLoc, moveInfo.Defender, moveInfo.Dcix); + } + return result; +} + +int getBattleForecast(int loc, TBattleForecast &battleForecast, int &duix, int &dcix, int &aStr, int &dStr, + int &aBaseDamage, int &dBaseDamage) +{ + int defender = Database::occupant[loc]; + if (defender < 0 || defender == battleForecast.pAtt) + return eOK; // no attack, simple move + + const TModel &pModel = (*Database::rw[battleForecast.pAtt].Model)[battleForecast.mixAtt]; + int dBon = 0; + { + int dCnt = 0; + Database::strongest(loc, duix, dStr, dBon, dCnt); // get defense strength and bonus + } + if (pModel.Kind == mkDiplomat && (Database::realMap[loc] & fCity) != 0) { // spy mission -- as if move was possible + battleForecast.EndHealthAtt = battleForecast.HealthAtt; + battleForecast.EndHealthDef = (*Database::rw[defender].Un)[duix].Health; + return eOK; + } + + const TModel &dModel = (*Database::rw[defender].Model)[(*Database::rw[defender].Un)[duix].mix]; + if ((Database::realMap[loc] & fCity) == 0 && (Database::realMap[loc] & fTerImp) != tiBase) { + if (dModel.Cap[mcSub] > 0 && (Database::realMap[loc] & fTerrain) < fGrass && + ((Database::observeLevel[loc] >> (2 * battleForecast.pAtt)) & 3) < Database::lObserveAll) + return eHiddenUnit; // attacking submarine not allowed + if (dModel.Cap[mcStealth] > 0 && + ((Database::observeLevel[loc] >> (2 * battleForecast.pAtt)) & 3) != Database::lObserveSuper) + return eStealthUnit; // attacking stealth aircraft not allowed + if (dModel.Domain == dAir && dModel.Kind != mkSpecial_Glider && pModel.Domain != dAir) + return eDomainMismatch; // can't attack plane + } + if ((pModel.Cap[mcArtillery] == 0 || + (Database::serverVersion[battleForecast.pAtt] >= 0x010200 && (Database::realMap[loc] & fTerrain) < fGrass && + dModel.Cap[mcSub] > 0)) // ground units can't attack submarines + && ((pModel.Domain == dGround && (Database::realMap[loc] & fTerrain) < fGrass) || + (pModel.Domain == dSea && (Database::realMap[loc] & fTerrain) >= fGrass))) + return eDomainMismatch; + if (pModel.Attack == 0 && + !(pModel.Cap[mcBombs] > 0 && (battleForecast.FlagsAtt & unBombsLoaded) != 0 && dModel.Domain < dAir)) + return eInvalid; + + if (battleForecast.Movement == 0) + return eNoTime_Attack; + + if (Database::rw[battleForecast.pAtt].Treaty[defender] >= trPeace) { + if (pModel.Domain != dAir && pModel.Attack > 0 && + static_cast(Database::realMap[loc] >> 27) == battleForecast.pAtt) { + if (battleForecast.Movement >= 100) { // expel friendly unit + battleForecast.EndHealthDef = (*Database::rw[defender].Un)[duix].Health; + battleForecast.EndHealthAtt = battleForecast.HealthAtt; + return eExpelled; + } else { + return eNoTime_Expel; + } + } else { + return eTreaty; + } + } + + // calculate defender strength + if (Database::realMap[loc] & fCity) { // consider city improvements + Database::searchCity(loc, defender, dcix); + if (pModel.Domain < dSea && pModel.Cap[mcArtillery] == 0 && + ((*Database::rw[defender].City)[dcix].Built[imWalls] == 1 || + Database::continent[(*Database::rw[defender].City)[dcix].Loc] == Database::grWallContinent[defender])) + dBon += 8; + else if (pModel.Domain == dSea && (*Database::rw[defender].City)[dcix].Built[imCoastalFort] == 1) + dBon += 4; + else if (pModel.Domain == dAir && (*Database::rw[defender].City)[dcix].Built[imMissileBat] == 1) + dBon += 4; + if ((*Database::rw[defender].City)[dcix].Built[imBunker] == 1) + dBon += 4; + } + if (pModel.Domain == dAir && dModel.Cap[mcAirDef] > 0) + dBon += 4; + dStr = dModel.Defense * dBon * 100; + if (dModel.Domain == dAir && ((Database::realMap[loc] & fCity) != 0 || (Database::realMap[loc] & fTerImp) == tiBase)) + dStr = 0; + if (dModel.Domain == dSea && (Database::realMap[loc] & fTerrain) >= fGrass) + dStr >>= 1; + + // calculate attacker strength + int time; + if (pModel.Cap[mcWill] > 0) { + time = 100; + } else { + time = battleForecast.Movement; + if (time > 100) + time = 100; + } + const int aBon = 4 + battleForecast.ExpAtt / ExpCost; + aStr = pModel.Attack; + if ((battleForecast.FlagsAtt & unBombsLoaded) != 0 && dModel.Domain < dAir) // use bombs + aStr += pModel.Cap[mcBombs] * pModel.MStrength * 2; + aStr = time * aStr * aBon; + + const TUn &defenderUn = (*Database::rw[defender].Un)[duix]; + + // base damage for defender + if (dStr == 0) { + dBaseDamage = defenderUn.Health; + } else { + dBaseDamage = battleForecast.HealthAtt * aStr / dStr; + if (dBaseDamage == 0) + dBaseDamage = 1; + if (dBaseDamage > defenderUn.Health) + dBaseDamage = defenderUn.Health; + } + + // base damage for attacker + if (aStr == 0) { + aBaseDamage = battleForecast.HealthAtt; + } else { + aBaseDamage = defenderUn.Health * dStr / aStr; + if (aBaseDamage == 0) + aBaseDamage = 1; + if (aBaseDamage > battleForecast.HealthAtt) + aBaseDamage = battleForecast.HealthAtt; + } + + // final damage for defender + int multiDamage = 2; + if (aBaseDamage == battleForecast.HealthAtt && pModel.Cap[mcFanatic] > 0 && + !(Database::rw[battleForecast.pAtt].Government == gRepublic || + Database::rw[battleForecast.pAtt].Government == gDemocracy || + Database::rw[battleForecast.pAtt].Government == gFuture)) + multiDamage *= 2; // fanatic attacker died + battleForecast.EndHealthDef = defenderUn.Health - multiDamage * dBaseDamage / 2; + if (battleForecast.EndHealthDef < 0) + battleForecast.EndHealthDef = 0; + + // final damage for attacker + multiDamage = 2; + if (dBaseDamage == defenderUn.Health) { + if (dModel.Cap[mcFanatic] > 0 && + !(Database::rw[defender].Government == gRepublic || Database::rw[defender].Government == gDemocracy || + Database::rw[defender].Government == gFuture)) + multiDamage *= 2; // fanatic defender died + if (pModel.Cap[mcFirst] > 0) + multiDamage >>= 1; // first strike unit wins + } + time = battleForecast.Movement; + if (time > 100) + time = 100; + battleForecast.EndHealthAtt = + battleForecast.HealthAtt - multiDamage * aBaseDamage / 2 - hostileDamage(battleForecast.pAtt, battleForecast.mixAtt, loc, time); + if (battleForecast.EndHealthAtt < 0) + battleForecast.EndHealthAtt = 0; + + if (battleForecast.EndHealthDef > 0) + return eLost; + else if (battleForecast.EndHealthAtt > 0) + return eWon; + return eBloody; +} + +int loadUnit(int p, int uix, bool testOnly) +{ + int result = eOK; + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + const int d = (*player.Model)[un.mix].Domain; + if (un.Master >= 0 || d == dSea || (*player.Model)[un.mix].Cap[mcAirTrans] + (*player.Model)[un.mix].Cap[mcOver] > 0) { + result = eViolation; + } else { + int toMaster = -1; + TUn *allUn = *player.Un; + const TModel *allModel = *player.Model; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { + if (allUn[uix1].Loc == un.Loc) { + TUn &un1 = allUn[uix1]; + const TModel &model1 = allModel[un1.mix]; // candidate transport's own model (its own capacity) + if ((d < dSea && un1.TroopLoad < model1.MTrans * (model1.Cap[mcSeaTrans] + model1.Cap[mcAirTrans])) || + (d == dAir && un1.AirLoad < model1.MTrans * model1.Cap[mcCarrier])) { // load onto unit uix1 + if (uixSelectedTransport < 0 || uix1 == uixSelectedTransport) { + toMaster = uix1; + break; + } else if (toMaster < 0) { + toMaster = uix1; + } + } + } + } + if (toMaster < 0) { + result = eNoLoadCapacity; + } else { + const int cost = (d == dAir) ? 100 : (*player.Model)[un.mix].Speed; + if (un.Movement < cost) { + result = eNoTime_Load; + } else if (!testOnly) { + Database::freeUnit(p, uix); + un.Movement -= static_cast(cost); + if (d == dAir) + ++allUn[toMaster].AirLoad; + else + ++allUn[toMaster].TroopLoad; + un.Master = static_cast(toMaster); + Database::updateUnitMap(un.Loc); + } + } + } + return result; +} + +int unloadUnit(int p, int uix, bool testOnly) +{ + int result = eOK; + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + const TModel &model = (*player.Model)[un.mix]; + if (un.Master < 0) { + result = eNotChanged; + } else if (model.Domain < dSea && (Database::realMap[un.Loc] & fTerrain) < fGrass) { + result = eDomainMismatch; + } else { + const int cost = (model.Domain == dAir) ? 100 : model.Speed; + if (un.Movement < cost) { + result = eNoTime_Load; + } else if (!testOnly) { + un.Movement -= static_cast(cost); + TUn &masterUn = (*player.Un)[un.Master]; + if (model.Domain == dAir) + --masterUn.AirLoad; + else + --masterUn.TroopLoad; // Movement:=0 // no more movement after unload (commented out upstream too) + un.Master = -1; + Database::placeUnit(p, uix); + Database::updateUnitMap(un.Loc); + } + } + return result; +} + +void recover(int p, int uix) +{ + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + const TModel &model = (*player.Model)[un.mix]; + int recovery; + if (un.Master >= 0 && (*player.Model)[(*player.Un)[un.Master].mix].Cap[mcSupplyShip] > 0) { + recovery = FastRecovery; // hospital ship + } else if ((Database::realMap[un.Loc] & fTerImp) == tiBase) { + recovery = CityRecovery; + } else if (Database::realMap[un.Loc] & fCity) { // unit in city + int cix = player.nCity - 1; + const TCity *allCity = *player.City; + while (cix >= 0 && allCity[cix].Loc != un.Loc) + --cix; + if (allCity[cix].Flags & chDisorder) { + recovery = NoCityRecovery; + } else if ((model.Domain == dGround && allCity[cix].Built[imBarracks] + allCity[cix].Built[imElite] > 0) || + (model.Domain == dSea && allCity[cix].Built[imDockyard] == 1) || + (model.Domain == dAir && allCity[cix].Built[imAirport] == 1)) { + recovery = FastRecovery; // city has barracks/shipyard/airport + } else { + recovery = CityRecovery; + } + } else if ((Database::realMap[un.Loc] & fTerrain) >= fGrass && model.Domain != dAir) { + recovery = NoCityRecovery; + } else { + recovery = 0; + } + + recovery = recovery * un.Movement / model.Speed; // recovery depends on movement unused + if (recovery > un.Health) // health max. doubled each turn + recovery = un.Health; + if (recovery > 100 - un.Health) + recovery = 100 - un.Health; + un.Health = static_cast(un.Health + recovery); +} + +int getMoveAdvice(int p, int uix, TMoveAdviceData &a) +{ + // domains + constexpr int gmaAir = 0; + constexpr int gmaSea = 1; + constexpr int gmaGround_NoZoC = 2; + constexpr int gmaGround_ZoC = 3; + // flags + constexpr int gmaNav = 4; + constexpr int gmaOver = 4; + constexpr int gmaAlpine = 8; + + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + + int maxDamage = un.Health - 1; + if (maxDamage > a.MaxHostile_MovementLeft) + maxDamage = (a.MaxHostile_MovementLeft >= 0) ? a.MaxHostile_MovementLeft : 0; + + const std::uint32_t *map = *player.Map; + if (a.ToLoc != maNextCity && (a.ToLoc < 0 || a.ToLoc >= Database::mapSize)) + return eInvalid; + if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) == fUNKNOWN) + return eNoWay; + + const TModel &model = (*player.Model)[un.mix]; + int moveInfo = 0; + int heavyCost = 0; + int railCost = 0; + int maxMov = 0; + int initMov = 0; + bool resistant = false; + switch (model.Domain) { + case dGround: + if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) == fOcean) + return eDomainMismatch; + moveInfo = (model.Flags & mdZOC) ? gmaGround_ZoC : gmaGround_NoZoC; + if (model.Cap[mcOver] > 0) + moveInfo += gmaOver; + if (model.Cap[mcAlpine] > 0) + moveInfo += gmaAlpine; + heavyCost = 50 + (((model.Speed - 150) * 13) >> 7); + railCost = (Database::gWonder[woShinkansen].EffectiveOwner == p) ? 0 : (model.Speed * (4 * 1311)) >> 17; + maxMov = model.Speed; + initMov = 0; + resistant = Database::gWonder[woGardens].EffectiveOwner == p || (model.Kind == mkSettler && model.Speed >= 200); + break; + case dSea: + if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) >= fGrass && (map[a.ToLoc] & (fCity | fUnit | fCanal)) == 0) + return eDomainMismatch; + moveInfo = gmaSea; + if (model.Cap[mcNav] > 0) + moveInfo += gmaNav; + maxMov = Database::unitSpeed(p, un.mix, 100); + initMov = maxMov - Database::unitSpeed(p, un.mix, un.Health); + break; + case dAir: + moveInfo = gmaAir; + maxMov = model.Speed; + initMov = 0; + break; + } + + const int fromLoc = un.Loc; + std::array from{}; + std::array time{}; + std::array damage{}; + time.fill(-1); + damage[fromLoc] = 0; + + Cevo::IPQ q(Database::mapSize); + q.put(fromLoc, (maxMov - un.Movement) << 8); + int loc = -1; + int t = 0; + while (q.get(loc, t)) { + time[loc] = t; + if (t >= (a.MoreTurns + 1) << 20) { + loc = -1; + break; + } + const std::uint32_t fromTile = map[loc]; + if (loc == a.ToLoc || (a.ToLoc == maNextCity && (fromTile & fCity) != 0)) + break; + if ((t & 0xFFF00) == 0xFFF00) + t += 0x100000; // indicates mountain delay + Database::Vicinity8Loc adjacent; + Database::v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + if (loc1 < 0 || loc1 >= Database::mapSize || time[loc1] >= 0) + continue; + const std::uint32_t toTile = map[loc1]; + if (loc1 == a.ToLoc && (toTile & (fUnit | fOwned)) == fUnit && + !((moveInfo & 3) == gmaSea && (fromTile & fTerrain) >= fGrass) && + !((moveInfo & 3) == gmaAir && ((fromTile & fCity) != 0 || (fromTile & fTerImp) == tiBase))) { + // attack position found + if (q.put(loc1, t + 1)) + from[loc1] = loc; + } else if ((toTile & fTerrain) != fUNKNOWN && (loc1 == a.ToLoc || (toTile & (fCity | fOwned)) != fCity) && + (loc1 == a.ToLoc || (toTile & (fUnit | fOwned)) != fUnit) && + ((toTile & ~fromTile) & fPeace) == 0 && + ((moveInfo & 3) < gmaGround_ZoC || (toTile & fromTile & fInEnemyZoC) == 0 || + (toTile & fOwnZoCUnit) != 0 || (fromTile & fCity) != 0 || + (toTile & (fCity | fOwned)) == (fCity | fOwned))) { + int addDamage = 0; + bool mountainDelay = false; + int moveCost; + switch (moveInfo) { + case gmaAir: + moveCost = 50; // always valid move + break; + case gmaSea: + moveCost = ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) == fShore) ? 50 : -1; + break; + case gmaSea + gmaNav: + moveCost = ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) < fGrass) ? 50 : -1; + break; + default: // ground unit + if ((toTile & fTerrain) >= fGrass) { // domain ok, valid move + if ((fromTile & (fRR | fCity)) != 0 && (toTile & (fRR | fCity)) != 0) { + moveCost = railCost; // move along railroad + } else if (((fromTile & (fRoad | fRR | fCity)) != 0 && (toTile & (fRoad | fRR | fCity)) != 0) || + (fromTile & toTile & (fRiver | fCanal)) != 0 || (moveInfo & gmaAlpine) != 0) { + // move along road, river or canal + moveCost = (moveInfo & gmaOver) ? 40 : 20; + } else if (moveInfo & gmaOver) { + moveCost = -1; + } else { + switch (Terrain[toTile & fTerrain].MoveCost) { + case 1: + moveCost = 50; // plain terrain + break; + case 2: + moveCost = heavyCost; // heavy terrain + break; + case 3: + moveCost = maxMov; + mountainDelay = true; + break; + default: + moveCost = -1; + break; + } + } + + // calculate HostileDamage + if (!resistant && (toTile & fTerImp) != tiBase) { + if ((toTile & (fTerrain | fCity | fRiver | fCanal | fSpecial1 /* Oasis */)) == + static_cast(fDesert)) { + addDamage = (v8 & 1) ? ((DesertThurst * 3 * moveCost - 1) / maxMov) + 1 + : ((DesertThurst * 2 * moveCost - 1) / maxMov) + 1; + } else if ((toTile & (fTerrain | fCity | fRiver | fCanal)) == static_cast(fArctic)) { + addDamage = (v8 & 1) ? ((ArcticThurst * 3 * moveCost - 1) / maxMov) + 1 + : ((ArcticThurst * 2 * moveCost - 1) / maxMov) + 1; + } + } + } else { + moveCost = -1; + } + break; + } + + if (moveCost > 0 && !mountainDelay) + moveCost = (v8 & 1) ? moveCost + moveCost * 2 : moveCost + moveCost; + + if ((moveInfo & 2) != 0 // ground unit, check transport load/unload + && (((moveCost < 0) && (toTile & (fUnit | fOwned)) == (fUnit | fOwned)) // assume ship/plane is transport + || (moveCost >= 0 && (fromTile & fTerrain) < fGrass))) + moveCost = maxMov; // transport load or unload + + if (moveCost >= 0) { // valid move + const int movementLeft = maxMov - ((t >> 8) & 0xFFF) - moveCost; + int t1; + if (movementLeft < 0 || (moveCost == 0 && movementLeft == 0)) { // must wait for next turn + if ((moveInfo & 2) != 0 /* ground unit */ && !resistant && (fromTile & fTerImp) != tiBase) { + if ((fromTile & (fTerrain | fCity | fRiver | fCanal | fSpecial1)) == static_cast(fDesert)) + addDamage += ((DesertThurst * (maxMov - ((t >> 8) & 0xFFF)) - 1) / maxMov) + 1; + else if ((fromTile & (fTerrain | fCity | fRiver | fCanal)) == static_cast(fArctic)) + addDamage += ((ArcticThurst * (maxMov - ((t >> 8) & 0xFFF)) - 1) / maxMov) + 1; + } + t1 = (t & 0x7FF000FF) + 0x100000 + ((initMov + moveCost) << 8); + } else { + t1 = t + (moveCost << 8) + 1; + } + if (mountainDelay) + t1 |= 0xFFF00; + if (damage[loc] + addDamage <= maxDamage && (t1 & 0xFF) < 0xFF) { + if (q.put(loc1, t1)) { + from[loc1] = loc; + damage[loc1] = damage[loc] + addDamage; + } + } + } + } + } + } + + int result; + if (loc == a.ToLoc || (a.ToLoc == maNextCity && loc >= 0 && (map[loc] & fCity) != 0)) { + a.MoreTurns = t >> 20; + const int endLoc = loc; + a.nStep = 0; + while (loc != fromLoc) { + if (time[loc] < 0x100000) + ++a.nStep; + loc = from[loc]; + } + loc = endLoc; + int i = a.nStep; + while (loc != fromLoc) { + if (time[loc] < 0x100000) { + --i; + if (i < 25) { + const int v1 = (loc % Database::lx) * 2 + ((loc / Database::lx) & 1); + const int v2 = (from[loc] % Database::lx) * 2 + ((from[loc] / Database::lx) & 1); + a.dx[i] = ((v1 - v2 + 3 * Database::lx) % (2 * Database::lx)) - Database::lx; + a.dy[i] = loc / Database::lx - from[loc] / Database::lx; + } + } + loc = from[loc]; + } + a.MaxHostile_MovementLeft = maxMov - ((time[endLoc] >> 8) & 0xFFF); + if (a.nStep > 25) + a.nStep = 25; + result = eOK; + } else { + result = eNoWay; + } + return result; +} + +bool canPlaneReturn(int p, int uix, const TPlaneReturnData &planeReturnData) +{ + constexpr std::uint8_t mfEnd = 1; + constexpr std::uint8_t mfReached = 2; + + TPlayerContext &player = Database::rw[p]; + const std::uint32_t *map = *player.Map; + std::array mapFlags{}; + + TUn &un = (*player.Un)[uix]; + const TModel &model = (*player.Model)[un.mix]; + + if (model.Kind == mkSpecial_Glider) { + for (int loc = 0; loc < Database::mapSize; ++loc) + if ((map[loc] & fTerrain) >= fGrass) + mapFlags[loc] |= mfEnd; + } else { + int loc = 0; + for (loc = 0; loc < Database::mapSize; ++loc) + if ((map[loc] & (fCity | fOwned)) == (fCity | fOwned) || + ((map[loc] & fTerImp) == tiBase && (map[loc] & fObserved) != 0 && (map[loc] & (fUnit | fOwned)) != fUnit)) + mapFlags[loc] |= mfEnd; + if (model.Cap[mcAirTrans] == 0) { // plane can land on carriers + TUn *allUn = *player.Un; + const TModel *allModel = *player.Model; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { + TUn &un1 = allUn[uix1]; + // Faithful port: the original reuses the preceding loop's + // stale `Loc` (left at MapSize-1) here instead of un1.Loc - + // looks like a dormant upstream bug, preserved as-is. + if (un1.AirLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcCarrier]) + mapFlags[loc] |= mfEnd; + } + } + } + + if (un.Master >= 0) // can return to same carrier, even if full now + mapFlags[un.Loc] |= mfEnd; + const int maxMov = model.Speed; + + bool result = false; + Cevo::IPQ q(Database::mapSize); + q.put(planeReturnData.Loc, (maxMov - planeReturnData.Movement) << 8); + int loc = 0; + int t = 0; + while (q.get(loc, t)) { + mapFlags[loc] |= mfReached; + if (t >= (planeReturnData.Fuel + 1) << 20) { + result = false; + break; + } + if (mapFlags[loc] & mfEnd) { + result = true; + break; + } + const std::uint32_t fromTile = map[loc]; + Database::Vicinity8Loc adjacent; + Database::v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + if (loc1 < 0 || loc1 >= Database::mapSize || (mapFlags[loc1] & mfReached)) + continue; + const std::uint32_t toTile = map[loc1]; + if ((toTile & fTerrain) != fUNKNOWN && (toTile & (fCity | fOwned)) != fCity && + (toTile & (fUnit | fOwned)) != fUnit && ((toTile & ~fromTile) & fPeace) == 0) { + const int moveCost = (v8 & 1) ? 150 : 100; + int t1; + if (moveCost + ((t >> 8) & 0xFFF) > maxMov) // must wait for next turn + t1 = (t & 0x7FF000FF) + 0x100000 + (moveCost << 8); + else + t1 = t + (moveCost << 8); + q.put(loc1, t1); + } + } + } + return result; +} + +// --- Terrain Improvement --- + +namespace { +int calculateJobWork(int p, int loc, int job, int &jobWork) +{ + int result = eOK; + const int terrType = static_cast(Database::realMap[loc] & fTerrain); + const TerrainInfo &terrain = Terrain[terrType]; + switch (job) { + case jCity: + if (Database::realMap[loc] & fCity) + result = eInvalid; + else if (terrain.IrrEff == 0) + result = eNoCityTerrain; + else + jobWork = CityWork; + break; + case jRoad: + if ((Database::realMap[loc] & (fRoad | fRR)) == 0) { + jobWork = terrain.MoveCost * RoadWork; + if (Database::realMap[loc] & fRiver) { + if (Database::rw[p].Tech[adBridgeBuilding] >= tsApplicable) + jobWork += RoadBridgeWork; // across river + else + result = eNoBridgeBuilding; + } + } else { + result = eInvalid; + } + break; + case jRR: + if ((Database::realMap[loc] & fRoad) == 0) + result = eNoPreq; + else if (Database::realMap[loc] & fRR) + result = eInvalid; + else { + jobWork = terrain.MoveCost * RRWork; + if (Database::realMap[loc] & fRiver) + jobWork += RRBridgeWork; // across river + } + break; + case jClear: + if (terrType == fDesert && Database::gWonder[woGardens].EffectiveOwner != p) + result = eInvalid; + else if (terrain.ClearTerrain >= 0) + jobWork = terrain.IrrClearWork; + else + result = eInvalid; + break; + case jIrr: + jobWork = terrain.IrrClearWork; + if (terrain.IrrEff == 0 || (Database::realMap[loc] & fTerImp) == tiIrrigation || + (Database::realMap[loc] & fTerImp) == tiFarm) + result = eInvalid; + break; + case jFarm: + if ((Database::realMap[loc] & fTerImp) != tiIrrigation) { + result = eNoPreq; + } else { + jobWork = terrain.IrrClearWork * FarmWork; + if (jobWork <= 0 || (Database::realMap[loc] & fTerImp) == tiFarm) + result = eInvalid; + } + break; + case jAfforest: + if (terrain.AfforestTerrain >= 0) + jobWork = terrain.MineAfforestWork; + else + result = eInvalid; + break; + case jMine: + jobWork = terrain.MineAfforestWork; + if (terrain.MineEff == 0 || (Database::realMap[loc] & fTerImp) == tiMine) + result = eInvalid; + break; + case jFort: + if ((Database::realMap[loc] & fTerImp) != tiFort) + jobWork = terrain.MoveCost * FortWork; + else + result = eInvalid; + break; + case jCanal: + if ((Database::realMap[loc] & fCanal) == 0 && ((Database::terrTypeCanalableMask >> terrType) & 1)) + jobWork = CanalWork; + else + result = eInvalid; + break; + case jTrans: + jobWork = terrain.TransWork; + if (jobWork <= 0) + result = eInvalid; + break; + case jPoll: + if (Database::realMap[loc] & fPoll) + jobWork = PollWork; + else + result = eInvalid; + break; + case jBase: + if ((Database::realMap[loc] & fTerImp) != tiBase) + jobWork = terrain.MoveCost * BaseWork; + else + result = eInvalid; + break; + case jPillage: + if (Database::realMap[loc] & (fRoad | fRR | fCanal | fTerImp)) + jobWork = PillageWork; + else + result = eInvalid; + break; + default: + break; + } + return result; +} +} // namespace + +int startJob(int p, int uix, int newJob, bool testOnly) +{ + assert(((1 << p) & Database::invalidTreatyMap) == 0); + int result = eOK; + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + if (newJob == un.Job) + return eNotChanged; + if (newJob == jNone) { + if (!testOnly) + un.Job = static_cast(jNone); + return result; + } + const int loc0 = un.Loc; + if ((Database::realMap[loc0] & fDeadLands) != 0 && newJob != jRoad && newJob != jRR) + return eDeadLands; + const int terrType = static_cast(Database::realMap[loc0] & fTerrain); + const TModel &model = (*player.Model)[un.mix]; + const bool allowed = ((newJob == jPillage) && model.Domain == dGround) || model.Kind == mkSettler || + ((newJob != jCity) && model.Kind == mkSlaves && Database::gWonder[woPyramids].EffectiveOwner >= 0); + if ((Database::realMap[loc0] & fCity) != 0 || terrType < fGrass || un.Master >= 0 || !allowed) + return eInvalid; + if (JobPreq[newJob] != preNone && player.Tech[JobPreq[newJob]] < tsApplicable) + return eNoPreq; + + int jobWork = 0; + result = calculateJobWork(p, loc0, newJob, jobWork); + if (Database::mode == Database::moPlaying && result == eOK && newJob != jPoll) { // not in friendly territory + const int p1 = static_cast(Database::realMap[loc0] >> 27); // owner of territory + if (p1 < nPl && p1 != p && player.Treaty[p1] >= trPeace) + result = eTreaty; // keep peace treaty! + } + if (testOnly || result < rExecuted) + return result; + + if (toWork[loc0][newJob] == 0 || toWork[loc0][newJob] > jobWork) + toWork[loc0][newJob] = static_cast(jobWork); + un.Job = static_cast(newJob); + un.Flags &= ~static_cast(unFortified); + TUn *allUn = *player.Un; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) + if (allUn[uix1].Loc == loc0 && (contraJobs[newJob] & (1u << allUn[uix1].Job))) + allUn[uix1].Job = static_cast(jNone); // stop contradictive jobs + if (Database::serverVersion[p] < 0x000EF0) + if (work(p, uix)) + result = eJobDone; + if (newJob == jCity && result == eJobDone) { + Database::removeUnitUpdateMap(p, uix); + result = eCity; + } else if (un.Health <= 0) { // victim of HostileDamage + Database::removeUnitUpdateMap(p, uix); + result |= rUnitRemoved; + } + if (Database::mode > Database::moLoading_Fast) { + if (result == eCity) { + Database::observeLevel[loc0] &= ~(3u << (2 * p)); + Database::discover21(loc0, p, Database::lObserveUnhidden, true, true); + } + } + return result; +} + +bool work(int p, int uix) +{ + bool result = false; + TPlayerContext &player = Database::rw[p]; + TUn &un = (*player.Un)[uix]; + if (un.Movement >= 100) { + assert(toWork[un.Loc][un.Job] < 0xFFFFu); // should have been set by startJob + if (un.Job >= jRoad) { + if (static_cast(un.Movement) >= static_cast(toWork[un.Loc][un.Job])) { // work complete + result = true; + if (un.Job != jIrr) + un.Health = static_cast(un.Health - hostileDamage(p, un.mix, un.Loc, toWork[un.Loc][un.Job])); + un.Movement -= static_cast(toWork[un.Loc][un.Job]); + if (un.Job != jCity && un.Job != jPillage && un.Job != jPoll) + worked[p] += toWork[un.Loc][un.Job]; + if (un.Job == jCity) { // found new city + Database::foundCity(p, un.Loc); + ++Database::founded[p]; + TCity &city = (*player.City)[player.nCity - 1]; + city.ID = static_cast((p << 12) + Database::founded[p] - 1); + city.Flags = chFounded; + if (Database::mode == Database::moPlaying) { + Database::logCheckBorders(p, player.nCity - 1); + Database::recalcPeaceMap(p); + } + if (Database::mode < Database::moPlaying) + Database::invalidTreatyMap = ~(1 << p); + // 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 + un.Health = 0; // causes unit to be removed later + } else { + Database::completeJob(p, un.Loc, un.Job); + } + toWork[un.Loc][un.Job] = 0; + const int j0 = un.Job; + TUn *allUn = *player.Un; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) + if (allUn[uix1].Loc == un.Loc && allUn[uix1].Job == j0) + allUn[uix1].Job = static_cast(jNone); + } else { + toWork[un.Loc][un.Job] = static_cast(toWork[un.Loc][un.Job] - un.Movement); + if (un.Job != jCity && un.Job != jPillage && un.Job != jPoll) + worked[p] += un.Movement; + un.Health = static_cast(un.Health - hostileDamage(p, un.mix, un.Loc, un.Movement)); + un.Movement = 0; + } + } + } + return result; +} + +int getJobProgress(int p, int loc, TJobProgressData &jobProgressData) +{ + TPlayerContext &player = Database::rw[p]; + for (int job = 0; job < nJob; ++job) { + const int jobResult = calculateJobWork(p, loc, job, jobProgressData[job].Required); + if (jobResult == eOK) { + if (toWork[loc][job] == 0xFFFFu) + jobProgressData[job].Done = 0; + else + jobProgressData[job].Done = jobProgressData[job].Required - toWork[loc][job]; + } else { + jobProgressData[job].Required = 0; + jobProgressData[job].Done = 0; + } + jobProgressData[job].NextTurnPlus = 0; + } + const TUn *un = *player.Un; + for (int uix = 0; uix < player.nUn; ++uix) + if (un[uix].Loc == loc && un[uix].Movement >= 100) + jobProgressData[un[uix].Job].NextTurnPlus += un[uix].Movement; + return eOK; +} + +// --- Start/End Game --- + +void initGame() +{ + toWork.assign(static_cast(Database::mapSize), {}); + for (auto &row : toWork) + row.fill(0xFFFFu); +} + +void releaseGame() +{ + toWork.clear(); + toWork.shrink_to_fit(); +} + +} // namespace UnitProcessing +} // namespace Cevo