initial port for Cevo game in C++ (libs)

This commit is contained in:
Geoffray Levasseur committed 2026-10-22 17:20:45 +02:00
commit 8436242032
375 files changed
+46282

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
#include "Cevo/AiModule.h"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <dlfcn.h>
#endif
namespace Cevo {
AiModule::~AiModule()
{
unload();
}
bool AiModule::load(const std::string &fileName)
{
unload();
#if defined(_WIN32)
m_handle = LoadLibraryA(fileName.c_str());
if (!m_handle) {
m_error = "LoadLibrary failed for " + fileName;
return false;
}
m_client = reinterpret_cast<TClientCall>(reinterpret_cast<void *>(
GetProcAddress(static_cast<HMODULE>(m_handle), "client")));
#else
m_handle = dlopen(fileName.c_str(), RTLD_NOW);
if (!m_handle) {
m_error = dlerror();
return false;
}
dlerror(); // clear any pending error before dlsym
m_client = reinterpret_cast<TClientCall>(dlsym(m_handle, "client"));
#endif
if (!m_client) {
m_error = "module " + fileName + " does not export a \"client\" entry point";
unload();
return false;
}
return true;
}
void AiModule::unload()
{
if (m_handle) {
#if defined(_WIN32)
FreeLibrary(static_cast<HMODULE>(m_handle));
#else
dlclose(m_handle);
#endif
m_handle = nullptr;
}
m_client = nullptr;
}
void AiModule::call(int command, int player, void *data) const
{
if (m_client)
m_client(command, player, data);
}
} // namespace Cevo
+101
View File
@@ -0,0 +1,101 @@
#include "Cevo/AiModuleHost.h"
#include "Cevo/Geometry.h"
namespace Cevo {
bool AiModuleHost::handle(int command, int player, void *data)
{
switch (command) {
case cmInitModule: {
auto &init = *static_cast<TInitModuleData *>(data);
CustomAI::setServerCall(init.Server);
init.DataSize = m_rwDataSize;
return true;
}
case cmNewGame:
case cmLoadGame: {
m_game = *static_cast<TNewGameData *>(data);
InitGeometry(m_game);
for (int p = nPl - 1; p >= 0; --p) {
if (m_game.RO[p]) {
m_ai[static_cast<size_t>(p)] = m_factory(p);
m_ai[static_cast<size_t>(p)]->bind(m_game.RO[p]);
m_ai[static_cast<size_t>(p)]->setDataDefaults();
} else {
m_ai[static_cast<size_t>(p)].reset();
}
}
m_defender = -1;
return true;
}
case cmGetReady:
for (auto &a : m_ai)
if (a)
a->setDataRandom();
return true;
case cmBreakGame:
for (auto &a : m_ai)
a.reset();
return true;
case cmShowAttacking:
case cmShowCapturing: {
const auto &move = *static_cast<const TShowMove *>(data);
const int y0 = move.FromLoc / m_game.lx;
const int toLoc =
(move.FromLoc + ((move.dx + (y0 & 1) + m_game.lx + m_game.lx) >> 1)) % m_game.lx +
m_game.lx * (y0 + move.dy);
if (player >= 0 && player < nPl && m_game.RO[player] && m_game.RO[player]->Map &&
((*m_game.RO[player]->Map)[toLoc] & fOwned) != 0) {
TUnitInfo unitInfo{};
unitInfo.Loc = move.FromLoc;
unitInfo.mix = static_cast<std::uint16_t>(move.mix);
unitInfo.emix = static_cast<std::uint16_t>(move.emix);
unitInfo.Owner = static_cast<std::uint8_t>(move.Owner);
unitInfo.Health = static_cast<std::int8_t>(move.Health);
unitInfo.Fuel = static_cast<std::int8_t>(move.Fuel);
unitInfo.Job = jNone;
unitInfo.Exp = static_cast<std::uint8_t>(move.Exp);
unitInfo.Load = static_cast<std::uint8_t>(move.Load);
unitInfo.Flags = static_cast<std::uint16_t>(move.Flags);
if (m_ai[static_cast<size_t>(player)]) {
if (command == cmShowAttacking)
m_ai[static_cast<size_t>(player)]->onBeforeEnemyAttack(unitInfo, toLoc, move.EndHealth,
move.EndHealthDef);
else
m_ai[static_cast<size_t>(player)]->onBeforeEnemyCapture(unitInfo, toLoc);
}
m_defender = player;
}
return true;
}
case cmShowAfterAttack:
if (player == m_defender) {
if (m_ai[static_cast<size_t>(player)])
m_ai[static_cast<size_t>(player)]->onAfterEnemyAttack();
m_defender = -1;
}
return true;
case cmShowAfterMove:
if (player == m_defender) {
if (m_ai[static_cast<size_t>(player)])
m_ai[static_cast<size_t>(player)]->onAfterEnemyCapture();
m_defender = -1;
}
return true;
default:
break;
}
if (player < 0 || player >= nPl || !m_ai[static_cast<size_t>(player)])
return false;
if (command == cmTurn || command == cmContinue || command == cmShowNego || command == cmShowEndContact ||
(command >= scContact && command <= scDipBreak)) {
m_ai[static_cast<size_t>(player)]->process(command, data);
return true;
}
return false;
}
} // namespace Cevo
+574
View File
@@ -0,0 +1,574 @@
#include "Cevo/CustomAI.h"
#include "Cevo/Geometry.h"
#include <cstdlib>
namespace Cevo {
TServerCall CustomAI::s_server = nullptr;
CustomAI::~CustomAI()
{
rawServerCall(sSetDebugMap, 0, nullptr);
}
void CustomAI::bind(TPlayerContext *playerContext)
{
ro = playerContext;
map = *ro->Map;
myUnit = *ro->Un;
myCity = *ro->City;
myModel = *ro->Model;
}
namespace {
int randomInt(int n) // Pascal's RTL Random(n); not ABI/determinism-relevant
{
return n > 0 ? std::rand() % n : 0;
}
} // namespace
void CustomAI::process(int command, void *data)
{
switch (command) {
case cmTurn:
case cmContinue: {
if ((ro->Alive & (1 << me)) == 0) { // I'm dead
rawServerCall(sTurn, 0, nullptr);
return;
}
if (command == cmTurn) {
cixStateImp.fill(-1);
for (int cix = 0; cix < ro->nCity; ++cix)
if (myCity[cix].Loc >= 0)
for (int iix = imPalace; iix <= imSpacePort; ++iix)
if (myCity[cix].Built[iix] > 0)
cixStateImp[static_cast<size_t>(iix - imPalace)] = cix;
if (ro->Happened & phChangeGov) {
const int newGov = chooseGovernment();
if (newGov > gAnarchy)
rawServerCall(sSetGovernment, newGov, nullptr);
}
haveTurned = false;
contacted.reset();
}
if (command == cmContinue && myAction == scContact) {
if (onNegoRejected_CancelTreaty())
if (ro->Treaty[opponent] >= trPeace)
rawServerCall(sCancelTreaty, 0, nullptr);
} else {
unwantedNego.reset();
}
opponent = -1;
for (;;) {
const NegoTime negoTime = haveTurned ? NegoTime::EndOfTurn : NegoTime::BeginOfTurn;
if (ro->Government != gAnarchy) {
for (int nation = 0; nation < nPl; ++nation) {
if (nation != me && (ro->Alive & (1 << nation)) != 0 && ro->Treaty[nation] >= trNone &&
!contacted[static_cast<size_t>(nation)] && !unwantedNego[static_cast<size_t>(nation)] &&
rawServerCall(scContact - sExecute + (nation << 4), 0, nullptr) >= rExecuted) {
if (wantNegotiation(nation, negoTime)) {
if (rawServerCall(scContact + (nation << 4), 0, nullptr) >= rExecuted) {
contacted.set(static_cast<size_t>(nation));
opponent = nation;
myAction = scContact;
return;
}
} else {
unwantedNego.set(static_cast<size_t>(nation));
}
}
}
}
if (negoTime == NegoTime::BeginOfTurn) {
doTurn();
haveTurned = true;
contacted.reset();
unwantedNego.reset();
} else {
break;
}
}
if (ro->Happened & phTech) {
int newResearch = chooseResearchAdvance();
if (newResearch < 0) { // choose random research
int count = 0;
for (int ad = 0; ad < nAdv; ++ad)
if (advanceResearchable(ad)) {
++count;
if (randomInt(count) == 0)
newResearch = ad;
}
}
rawServerCall(sSetResearch, newResearch, nullptr);
}
rawServerCall(sTurn, 0, nullptr);
break;
}
case scContact: {
const int nation = static_cast<int>(reinterpret_cast<std::intptr_t>(data));
if (wantNegotiation(nation, NegoTime::EnemyCalled)) {
rawServerCall(scDipStart, 0, nullptr);
opponent = nation;
myAction = scDipStart;
} else {
rawServerCall(scReject, 0, nullptr);
}
break;
}
case scDipStart:
case scDipNotice:
case scDipAccept:
case scDipCancelTreaty:
case scDipOffer:
case scDipBreak: {
oppoAction = command;
if (command == scDipOffer)
oppoOffer = *static_cast<TOffer *>(data);
if (command == scDipStart) {
myLastAction = scContact;
} else {
myLastAction = myAction;
myLastOffer = myOffer;
}
if (oppoAction == scDipCancelTreaty || oppoAction == scDipBreak) {
myAction = scDipNotice;
} else {
myAction = scDipOffer;
myOffer.nDeliver = 0;
myOffer.nCost = 0;
}
doNegotiation();
if (myAction == scDipOffer)
rawServerCall(myAction, 0, &myOffer);
else
rawServerCall(myAction, 0, nullptr);
break;
}
case cmShowEndContact:
opponent = -1;
break;
default:
break;
}
}
// ---- general functions ----
int CustomAI::researchCost() const
{
int result = 0;
rawServerCall(sGetTechCost, 0, &result);
return result;
}
int CustomAI::changeAttitude(int nation, int attitude) const
{
return rawServerCall(sSetAttitude + (nation << 4), attitude, nullptr);
}
int CustomAI::revolution() const
{
return rawServerCall(sRevolution, 0, nullptr);
}
int CustomAI::changeRates(int tax, int lux) const
{
return rawServerCall(sSetRates, (tax / 10 & 0xF) + ((lux / 10 & 0xF) << 4), nullptr);
}
int CustomAI::prepareNewModel(int domain) const
{
return rawServerCall(sCreateDevModel, domain, nullptr);
}
int CustomAI::setNewModelFeature(int feature, int count) const
{
return rawServerCall(sSetDevModelCap + (count << 4), feature, nullptr);
}
bool CustomAI::advanceResearchable(int advance) const
{
return rawServerCall(sSetResearch - sExecute, advance, nullptr) >= rExecuted;
}
bool CustomAI::advanceStealable(int advance) const
{
return rawServerCall(sStealTech - sExecute, advance, nullptr) >= rExecuted;
}
bool CustomAI::getJobProgress(int loc, TJobProgressData &jobProgress) const
{
return rawServerCall(sGetJobProgress, loc, jobProgress) >= rExecuted;
}
bool CustomAI::debugMessage(int level, const std::string &text) const
{
std::string prefixed = "P" + std::to_string(me) + " " + text;
if (prefixed.size() > 254)
prefixed.resize(254);
rawServerCall(sMessage, level, const_cast<char *>(prefixed.c_str()));
return true; // always true, so callers can write assert(debugMessage(...))
}
bool CustomAI::setDebugMap(void *debugMap) const
{
rawServerCall(sSetDebugMap, 0, debugMap);
return true;
}
// ---- unit functions ----
int CustomAI::unit_FindMyDefender(int loc) const
{
int uix = -1;
return rawServerCall(sGetDefender, loc, &uix) < rExecuted ? -1 : uix;
}
int CustomAI::unit_FindEnemyDefender(int loc) const
{
int euix = ro->nEnemyUn - 1;
while (euix >= 0 && (*ro->EnemyUn)[euix].Loc != loc)
--euix;
return euix;
}
void CustomAI::stealAdvance()
{
int steal = chooseStealAdvance();
if (steal < 0) {
int count = 0;
for (int ad = 0; ad < nAdv; ++ad)
if (advanceStealable(ad)) {
++count;
if (randomInt(count) == 0)
steal = ad;
}
}
if (steal >= 0)
rawServerCall(sStealTech, steal, nullptr);
ro->Happened &= ~phStealTech;
}
int CustomAI::unit_Move(int uix, int toLoc)
{
TMoveAdviceData advice{};
advice.ToLoc = toLoc;
advice.MoreTurns = 9999;
advice.MaxHostile_MovementLeft = 100;
int result = rawServerCall(sGetMoveAdvice, uix, &advice);
if (result != eOK)
return result;
bool destinationReached = false;
int step = 0;
for (;;) {
if ((result & (rExecuted | rUnitRemoved)) == rExecuted) {
if (toLoc >= 0 && advice.MoreTurns == 0 && step == advice.nStep - 1 &&
((map[toLoc] & (fUnit | fOwned)) == fUnit || // attack
((map[toLoc] & (fCity | fOwned)) == fCity &&
(myModel[myUnit[uix].mix].Domain != dGround || // bombardment
(myModel[myUnit[uix].mix].Flags & mdCivil) != 0)))) { // can't capture
destinationReached = true;
break;
}
if (step == advice.nStep) {
destinationReached = true;
}
}
if (step == advice.nStep || (result != eOK && result != eLoaded))
break;
result = rawServerCall(sMoveUnit + ((advice.dx[step] & 7) << 4) + ((advice.dy[step] & 7) << 7), uix,
nullptr);
++step;
if (ro->Happened & phStealTech)
stealAdvance();
}
if (destinationReached) {
if (advice.nStep == 25)
result = unit_Move(uix, toLoc); // Shinkansen
else if (advice.MoreTurns == 0)
result |= rLocationReached;
else
result |= rMoreTurns;
}
return result;
}
int CustomAI::unit_Step(int uix, int toLoc)
{
int a, b;
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
int result = rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
if (ro->Happened & phStealTech)
stealAdvance();
return result;
}
int CustomAI::unit_Attack(int uix, int toLoc) const
{
int a, b;
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
return rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
}
int CustomAI::unit_DoMission(int uix, int missionType, int toLoc) const
{
int result = rawServerCall(sSetSpyMission + (missionType << 4), 0, nullptr);
if (result < rExecuted)
return result;
int a, b;
Loc_to_ab(myUnit[uix].Loc, toLoc, a, b);
result =
rawServerCall(sMoveUnit - sExecute + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
if (result == eMissionDone)
result = rawServerCall(sMoveUnit + (((a - b) & 7) << 4) + (((a + b) & 7) << 7), uix, nullptr);
else if (result != eNoTime_Move && result != eTreaty && result != eNoTurn)
result = eInvalid; // not a special commando mission!
return result;
}
bool CustomAI::unit_MoveForecast(int uix, int toLoc, int &remainingMovement) const
{
TMoveAdviceData advice{};
advice.ToLoc = toLoc;
advice.MoreTurns = 0;
advice.MaxHostile_MovementLeft = 100;
if (rawServerCall(sGetMoveAdvice, uix, &advice) == eOK) {
remainingMovement = advice.MaxHostile_MovementLeft;
return true;
}
remainingMovement = -1;
return false;
}
bool CustomAI::unit_AttackForecast(int uix, int toLoc, int attackMovement, int &remainingHealth) const
{
remainingHealth = -0x100;
if (attackMovement < 0)
return false;
TBattleForecast forecast{};
forecast.pAtt = me;
forecast.mixAtt = myUnit[uix].mix;
forecast.HealthAtt = myUnit[uix].Health;
forecast.ExpAtt = myUnit[uix].Exp;
forecast.FlagsAtt = static_cast<int>(myUnit[uix].Flags);
forecast.Movement = attackMovement;
if (rawServerCall(sGetBattleForecast, toLoc, &forecast) < rExecuted)
return false;
remainingHealth = forecast.EndHealthAtt > 0 ? forecast.EndHealthAtt : -forecast.EndHealthDef;
return true;
}
bool CustomAI::unit_DefenseForecast(int euix, int toLoc, int &remainingHealth) const
{
remainingHealth = 0x100;
const TUnitInfo &enemy = (*ro->EnemyUn)[euix];
TBattleForecast forecast{};
forecast.pAtt = enemy.Owner;
forecast.mixAtt = enemy.mix;
forecast.HealthAtt = enemy.Health;
forecast.ExpAtt = enemy.Exp;
forecast.FlagsAtt = enemy.Flags;
forecast.Movement = 100;
if (rawServerCall(sGetBattleForecast, toLoc, &forecast) < rExecuted)
return false;
remainingHealth = forecast.EndHealthDef > 0 ? forecast.EndHealthDef : -forecast.EndHealthAtt;
return true;
}
int CustomAI::unit_Disband(int uix) const
{
return rawServerCall(sRemoveUnit, uix, nullptr);
}
int CustomAI::unit_StartJob(int uix, int newJob) const
{
return rawServerCall(sStartJob + (newJob << 4), uix, nullptr);
}
int CustomAI::unit_SetHomeHere(int uix) const
{
return rawServerCall(sSetUnitHome, uix, nullptr);
}
int CustomAI::unit_Load(int uix) const
{
return rawServerCall(sLoadUnit, uix, nullptr);
}
int CustomAI::unit_Unload(int uix) const
{
return rawServerCall(sUnloadUnit, uix, nullptr);
}
int CustomAI::unit_SelectTransport(int uix) const
{
return rawServerCall(sSelectTransport, uix, nullptr);
}
int CustomAI::unit_AddToCity(int uix) const
{
return rawServerCall(sAddToCity, uix, nullptr);
}
// ---- city functions ----
int CustomAI::city_FindMyCity(int loc) const
{
if ((map[loc] & (fCity | fOwned)) != (fCity | fOwned))
return -1;
int cix = ro->nCity - 1;
while (cix >= 0 && myCity[cix].Loc != loc)
--cix;
return cix;
}
int CustomAI::city_FindEnemyCity(int loc) const
{
if ((map[loc] & (fCity | fOwned)) != fCity)
return -1;
int ecix = ro->nEnemyCity - 1;
while (ecix >= 0 && (*ro->EnemyCity)[ecix].Loc != loc)
--ecix;
return ecix;
}
bool CustomAI::city_HasProject(int cix) const
{
return (myCity[cix].Project & (cpImp + cpIndex)) != cpImp + imTrGoods;
}
int CustomAI::city_CurrentImprovementProject(int cix) const
{
if ((myCity[cix].Project & cpImp) == 0)
return -1;
const int result = myCity[cix].Project & cpIndex;
return result == imTrGoods ? -1 : result;
}
int CustomAI::city_CurrentUnitProject(int cix) const
{
return (myCity[cix].Project & cpImp) != 0 ? -1 : myCity[cix].Project & cpIndex;
}
int CustomAI::city_GetTileInfo(int cix, int tileLoc, TTileInfo &tileInfo) const
{
tileInfo.ExplCity = cix;
return rawServerCall(sGetHypoCityTileInfo, tileLoc, &tileInfo);
}
int CustomAI::city_GetReport(int cix, TCityReport &report) const
{
report.HypoTiles = -1;
report.HypoTax = -1;
report.HypoLux = -1;
return rawServerCall(sGetCityReport, cix, &report);
}
int CustomAI::city_GetHypoReport(int cix, int hypoTiles, int hypoTax, int hypoLux, TCityReport &report) const
{
report.HypoTiles = hypoTiles;
report.HypoTax = hypoTax;
report.HypoLux = hypoLux;
return rawServerCall(sGetCityReport, cix, &report);
}
int CustomAI::city_GetReportNew(int cix, TCityReportNew &report) const
{
report.HypoTiles = -1;
report.HypoTaxRate = -1;
report.HypoLuxuryRate = -1;
return rawServerCall(sGetCityReportNew, cix, &report);
}
int CustomAI::city_GetHypoReportNew(int cix, int hypoTiles, int hypoTaxRate, int hypoLuxuryRate,
TCityReportNew &report) const
{
report.HypoTiles = hypoTiles;
report.HypoTaxRate = hypoTaxRate;
report.HypoLuxuryRate = hypoLuxuryRate;
return rawServerCall(sGetCityReportNew, cix, &report);
}
int CustomAI::city_GetAreaInfo(int cix, TCityAreaInfo &areaInfo) const
{
return rawServerCall(sGetCityAreaInfo, cix, &areaInfo);
}
int CustomAI::city_StartUnitProduction(int cix, int mix) const
{
if ((myCity[cix].Project & (cpImp + cpIndex)) == mix)
return eNotChanged;
return rawServerCall(sSetCityProject, cix, &mix);
}
int CustomAI::city_StartEmigration(int cix, int mix, bool allowDisbandCity, bool asConscripts) const
{
int newProject = mix;
if (allowDisbandCity)
newProject |= cpDisbandCity;
if (asConscripts)
newProject |= cpConscripts;
return rawServerCall(sSetCityProject, cix, &newProject);
}
int CustomAI::city_StartImprovement(int cix, int iix) const
{
int newProject = iix + cpImp;
if ((myCity[cix].Project & (cpImp + cpIndex)) == newProject)
return eNotChanged;
return rawServerCall(sSetCityProject, cix, &newProject);
}
bool CustomAI::city_Improvable(int cix, int iix) const
{
int newProject = iix + cpImp;
return rawServerCall(sSetCityProject - sExecute, cix, &newProject) >= rExecuted;
}
int CustomAI::city_StopProduction(int cix) const
{
int newProject = imTrGoods + cpImp;
return rawServerCall(sSetCityProject, cix, &newProject);
}
int CustomAI::city_BuyProject(int cix) const
{
return rawServerCall(sBuyCityProject, cix, nullptr);
}
int CustomAI::city_SellImprovement(int cix, int iix) const
{
return rawServerCall(sSellCityImprovement, cix, &iix);
}
int CustomAI::city_RebuildImprovement(int cix, int iix) const
{
return rawServerCall(sRebuildCityImprovement, cix, &iix);
}
int CustomAI::city_SetTiles(int cix, int newTiles) const
{
return rawServerCall(sSetCityTiles, cix, &newTiles);
}
void CustomAI::city_OptimizeTiles(int cix, std::uint32_t resourceWeights) const
{
TCityTileAdviceData advice{};
advice.ResourceWeights = resourceWeights;
rawServerCall(sGetCityTileAdvice, cix, &advice);
city_SetTiles(cix, static_cast<int>(advice.Tiles));
}
// ---- negotiation ----
int CustomAI::nego_CheckMyAction() const
{
if (myAction == scDipOffer)
return rawServerCall(myAction - sExecute, 0, const_cast<TOffer *>(&myOffer));
return rawServerCall(myAction - sExecute, 0, nullptr);
}
} // namespace Cevo
+165
View File
@@ -0,0 +1,165 @@
#include "Cevo/Geometry.h"
#include <cstdlib>
namespace Cevo {
namespace {
int g_lx = 1;
int g_ly = 1;
int g_mapSize = 1;
std::int32_t g_difficulty[nPl] = {};
constexpr int ab_v8[9] = { 5, 6, 7, 4, -1, 0, 3, 2, 1 }; // index = 3*B + A + 4
constexpr int v8_a[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
constexpr int v8_b[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
} // namespace
void InitGeometry(const TNewGameData &newGameData)
{
g_lx = newGameData.lx;
g_ly = newGameData.ly;
g_mapSize = g_lx * g_ly;
for (int i = 0; i < nPl; ++i)
g_difficulty[i] = newGameData.Difficulty[i];
}
int MapWidth() { return g_lx; }
int MapHeight() { return g_ly; }
int MapSize() { return g_mapSize; }
int Difficulty(int nation) { return g_difficulty[nation]; }
void ab_to_Loc(int Loc0, int A, int B, int &Loc)
{
const int y0 = Loc0 / g_lx;
Loc = (Loc0 + ((A - B + (y0 & 1) + g_lx + g_lx) >> 1)) % g_lx + g_lx * (y0 + A + B);
if (Loc >= g_mapSize)
Loc = -0x1000;
}
void Loc_to_ab(int Loc0, int Loc, int &A, int &B)
{
const int dx = ((Loc % g_lx * 2 + (Loc / g_lx & 1)) - (Loc0 % g_lx * 2 + (Loc0 / g_lx & 1)) + 3 * g_lx) %
(2 * g_lx) -
g_lx;
const int dy = Loc / g_lx - Loc0 / g_lx;
A = (dx + dy) / 2;
B = (dy - dx) / 2;
}
void ab_to_V8(int A, int B, int &V8)
{
V8 = ab_v8[3 * B + A + 4];
}
void V8_to_ab(int V8, int &A, int &B)
{
A = v8_a[V8];
B = v8_b[V8];
}
void ab_to_V21(int A, int B, int &V21)
{
V21 = ((A + B + 3) << 2) + ((A - B + 3) >> 1);
}
void V21_to_ab(int V21, int &A, int &B)
{
const int dy = (V21 >> 2) - 3;
const int dx = (((V21 & 3) << 1) - 3) + ((dy + 3) & 1);
A = (dx + dy) / 2;
B = (dy - dx) / 2;
}
void V8_to_Loc(int Loc0, TVicinity8Loc &VicinityLoc)
{
const int lx = g_lx;
const int y0 = Loc0 / lx;
const int x0 = Loc0 - y0 * lx;
VicinityLoc[1] = Loc0 + lx * 2;
VicinityLoc[3] = Loc0 - 1;
VicinityLoc[5] = Loc0 - lx * 2;
VicinityLoc[7] = Loc0 + 1;
Loc0 += y0 & 1;
VicinityLoc[0] = Loc0 + lx;
VicinityLoc[2] = Loc0 + lx - 1;
VicinityLoc[4] = Loc0 - lx - 1;
VicinityLoc[6] = Loc0 - lx;
// world is round!
if (x0 < lx - 1) {
if (x0 == 0) {
VicinityLoc[3] += lx;
if ((y0 & 1) == 0) {
VicinityLoc[2] += lx;
VicinityLoc[4] += lx;
}
}
} else {
VicinityLoc[7] -= lx;
if ((y0 & 1) == 1) {
VicinityLoc[0] -= lx;
VicinityLoc[6] -= lx;
}
}
// check south pole
switch (g_ly - y0) {
case 1:
VicinityLoc[0] = -0x1000;
VicinityLoc[1] = -0x1000;
VicinityLoc[2] = -0x1000;
break;
case 2:
VicinityLoc[1] = -0x1000;
break;
default:
break;
}
}
void V21_to_Loc(int Loc0, TVicinity21Loc &VicinityLoc)
{
const int y0 = Loc0 / g_lx;
int xComp0 = Loc0 - y0 * g_lx - 1;
int xCompSwitch = xComp0 - 1 + (y0 & 1);
if (xComp0 < 0)
xComp0 += g_lx;
if (xCompSwitch < 0)
xCompSwitch += g_lx;
xCompSwitch ^= xComp0;
int yComp = g_lx * (y0 - 3);
int *dst = VicinityLoc;
unsigned bit = 1;
for (int dy = 0; dy <= 6; ++dy) {
if (yComp < g_mapSize) {
xComp0 ^= xCompSwitch;
int xComp = xComp0;
for (int dx = 0; dx <= 3; ++dx) {
*dst = (bit & 0x67F7F76u) ? xComp + yComp : -1;
++xComp;
if (xComp >= g_lx)
xComp -= g_lx;
++dst;
bit <<= 1;
}
yComp += g_lx;
} else {
for (int dx = 0; dx <= 3; ++dx) {
*dst = -0x1000;
++dst;
}
}
}
}
int Distance(int Loc0, int Loc1)
{
int A, B;
Loc_to_ab(Loc0, Loc1, A, B);
const int dx = std::abs(A - B);
const int dy = std::abs(A + B);
return dx + dy + (std::abs(dx - dy) >> 1);
}
} // namespace Cevo
+95
View File
@@ -0,0 +1,95 @@
#include "Cevo/Pile.h"
#include <algorithm>
#include <cassert>
namespace Cevo {
void Pile::create(int size)
{
assert(size <= MaxSize);
if (n_ != 0 || size > currentSize_) {
std::fill_n(ix_, size, -1);
n_ = 0;
}
currentSize_ = size;
}
void Pile::empty()
{
if (n_ != 0) {
std::fill_n(ix_, currentSize_, -1);
n_ = 0;
}
}
// Parent(i) = (i-1)/2.
bool Pile::put(int item, int value) // O(lg(n))
{
assert(item < currentSize_);
int i = ix_[item];
if (i >= 0) {
if (bh_[i].value <= value)
return false;
} else {
i = n_;
++n_;
}
while (i > 0) {
const int j = (i - 1) >> 1; // Parent(i) = (i-1)/2
if (value >= bh_[j].value)
break;
bh_[i] = bh_[j];
ix_[bh_[i].item] = i;
i = j;
}
// Insert the new item at the insertion point found.
bh_[i].value = value;
bh_[i].item = item;
ix_[bh_[i].item] = i;
return true;
}
bool Pile::testPut(int item, int value) const
{
assert(item < currentSize_);
const int i = ix_[item];
return i < 0 || bh_[i].value > value;
}
// Left(i) = 2*i+1, Right(i) = Left(i)+1.
bool Pile::get(int &item, int &value) // O(lg(n))
{
if (n_ == 0)
return false;
item = bh_[0].item;
value = bh_[0].value;
ix_[item] = -1;
--n_;
if (n_ > 0) {
const HeapItem last = bh_[n_];
int i = 0;
int j = 1;
while (j < n_) {
if (j < n_ - 1 && bh_[j].value > bh_[j + 1].value)
++j; // Right(i) = Left(i)+1
if (last.value <= bh_[j].value)
break;
bh_[i] = bh_[j];
ix_[bh_[i].item] = i;
i = j;
j = (j << 1) + 1; // Left(j) = 2*j+1
}
// Insert the root in the correct place in the heap.
bh_[i] = last;
ix_[last.item] = i;
}
return true;
}
} // namespace Cevo
+146
View File
@@ -0,0 +1,146 @@
#include "Cevo/Protocol.h"
#include <cstddef>
namespace Cevo {
void MakeUnitInfo(int P, const TUn &U, TUnitInfo &ui)
{
ui.Owner = static_cast<std::uint8_t>(P);
ui.Loc = U.Loc;
ui.Health = U.Health;
ui.Fuel = U.Fuel;
ui.Job = U.Job;
ui.Exp = U.Exp;
ui.Load = static_cast<std::uint8_t>(U.TroopLoad + U.AirLoad);
ui.mix = static_cast<std::uint16_t>(U.mix);
ui.Flags = static_cast<std::uint16_t>(U.Flags);
}
void MakeModelInfo(int P, int mix, const TModel &M, TModelInfo &mi)
{
mi.Owner = static_cast<std::uint16_t>(P);
mi.mix = static_cast<std::uint16_t>(mix);
mi.ID = M.ID;
mi.Domain = M.Domain;
// Important for IsSameModel(): enemy-developed models compare equal to
// the same capability developed by ourselves.
mi.Kind = M.Kind == mkEnemyDeveloped ? mkSelfDeveloped : M.Kind;
mi.Attack = M.Attack;
mi.Defense = M.Defense;
mi.Speed = M.Speed;
mi.Cost = M.Cost;
if (mi.Domain == dAir) {
mi.TTrans = static_cast<std::uint8_t>(M.Cap[mcAirTrans] * M.MTrans);
mi.ATrans_Fuel = M.Cap[mcFuel];
} else {
mi.TTrans = static_cast<std::uint8_t>(M.Cap[mcSeaTrans] * M.MTrans);
mi.ATrans_Fuel = static_cast<std::uint8_t>(M.Cap[mcCarrier] * M.MTrans);
}
mi.Bombs = static_cast<std::uint16_t>(M.Cap[mcBombs] * M.MStrength * 2);
mi.Cap = 0;
for (int i = mcFirstNonCap; i < nFeature; ++i)
if (M.Cap[i] > 0)
mi.Cap |= 1u << (i - mcFirstNonCap);
mi.MaxUpgrade = 0;
for (int i = 1; i < nUpgrade; ++i)
if (M.Upgrades & (1u << i))
mi.MaxUpgrade = static_cast<std::uint8_t>(i);
mi.Weight = M.Weight;
mi.Lost = 0;
}
bool IsSameModel(const TModelInfo &mi1, const TModelInfo &mi2)
{
// Mirrors the original's raw-word comparison: compares everything up to
// (and including) Cap, ignoring ID (only its high word, Kind+Domain, is
// compared) and ignoring MaxUpgrade/Weight/Lost entirely. Relies on
// TModelInfo having zero padding before Cap, which it does (every field
// already falls on its natural alignment boundary).
static_assert(offsetof(TModelInfo, Cap) == 20, "TModelInfo layout changed");
const auto *compare1 = reinterpret_cast<const std::uint32_t *>(&mi1);
const auto *compare2 = reinterpret_cast<const std::uint32_t *>(&mi2);
return (compare1[1] & 0xFFFF0000u) == (compare2[1] & 0xFFFF0000u) && compare1[2] == compare2[2] &&
compare1[3] == compare2[3] && compare1[4] == compare2[4] && compare1[5] == compare2[5];
}
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
return (((lymax + x - (y >> 1)) >> 1) + x + ((y + 1) >> 1)) % 2 != 0 ? 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) {
const int qy = (y + x) / 5;
if ((qy & 3) != (qx >> 2 & 1) * 2) {
if (TerrType == fArctic || TerrType == fSwamp)
return 1;
if (TerrType == fShore) {
if ((qx + qy) % 2 == 0)
return (qx & 3) == 2 ? 2 : 1;
return 0;
}
return (qx + qy) % 2 + 1;
}
}
return 0;
}
int GetCommandDataSize(TCommand Command)
{
switch (Command) {
case cmInitModule:
return sizeof(TInitModuleData);
case cmGetReady:
return 0;
case cmTurn:
return 0;
case cmShowTurnChange:
return sizeof(std::int32_t);
case cmShowNego:
return sizeof(TShowNegoData);
case cmNewGame:
case cmLoadGame:
case cmMovie:
case cmNewMap:
return sizeof(TNewGameData);
case cmShowShipChange:
return sizeof(TShowShipChange);
case cmShowGreatLibTech:
return sizeof(std::int32_t);
case cmShowCityChanged:
return sizeof(std::int32_t);
case cmShowPeaceViolation:
return sizeof(std::int32_t);
case cmShowMoving:
return sizeof(TShowMove);
case cmShowUnitChanged:
return sizeof(std::int32_t);
case cmShowMissionResult:
return sizeof(std::uint32_t);
case cmShowAfterMove:
return sizeof(std::int32_t);
case cmShowAfterAttack:
return sizeof(std::int32_t);
case cmShowSupportAllianceAgainst:
return sizeof(std::int32_t);
case cmShowCancelTreatyByAlliance:
return sizeof(std::int32_t);
case cmShowEndContact:
return 0;
case cmShowGame:
return 0;
default:
return 0;
}
}
} // namespace Cevo
+1173
View File
File diff suppressed because it is too large. Load diff