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

+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include "Cevo/Protocol.h"
#include <string>
namespace Cevo {
// Cross-platform dynamic-library loader for brain modules (AI plugins, and
// in principle any other module speaking the same protocol) exporting the
// "client" entry point defined by Protocol.h (TClientCall). This is the
// host-side counterpart of AIProject.lpr's `library` wrapper: it lets the
// game load precompiled AI .dll/.so files (StdAI, Capital AI, KIAI, ...)
// exactly as the original Pascal game did, with no dependency on Qt or any
// other framework - just the platform's native dynamic-loading API
// (LoadLibrary/GetProcAddress on Windows, dlopen/dlsym on POSIX).
class AiModule {
public:
AiModule() = default;
~AiModule();
AiModule(const AiModule &) = delete;
AiModule &operator=(const AiModule &) = delete;
// fileName: a .dll on Windows, .so on Linux/BSD, .dylib on macOS.
// Returns false (with errorMessage() set) if the file can't be loaded or
// doesn't export a "client" symbol.
bool load(const std::string &fileName);
void unload();
bool isLoaded() const { return m_client != nullptr; }
const std::string &errorMessage() const { return m_error; }
// Invokes the module's Client(Command, Player, Data) entry point.
void call(int command, int player, void *data) const;
private:
void *m_handle = nullptr;
TClientCall m_client = nullptr;
std::string m_error;
};
} // namespace Cevo
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include "Cevo/CustomAI.h"
#include <array>
#include <functional>
#include <memory>
namespace Cevo {
// Generic module-level harness: owns one CustomAI-derived instance per
// nation and dispatches every command a brain module's exported "client"
// entry point can receive, mirroring StdAI.lpr's `Client` procedure exactly
// (lifecycle commands, turn/negotiation via CustomAI::process(), map
// geometry setup, and the cmShowAttacking/cmShowCapturing/cmShowAfterAttack/
// cmShowAfterMove enemy-move notifications with their TShowMove->TUnitInfo
// conversion and cross-call "Defender" tracking). A concrete AI module's
// exported "client" entry point just forwards every call here via
// CEVO_EXPORT_AI_CLIENT below - this class *is* the reusable "common
// interface"; StdAI.lpr (or an equivalent for a new AI) only needs to supply
// the CustomAI subclass.
class AiModuleHost {
public:
using Factory = std::function<std::unique_ptr<CustomAI>(int nation)>;
// rwDataSize: extra per-nation read/write scratch size (in bytes) this
// module asks the server to allocate, reported back via
// TInitModuleData.DataSize at cmInitModule (0 if the module keeps no
// persistent per-nation data beyond what CustomAI already tracks).
explicit AiModuleHost(Factory factory, int rwDataSize = 0)
: m_factory(std::move(factory)), m_rwDataSize(rwDataSize)
{
}
// Returns true if `command` was recognized and handled here.
bool handle(int command, int player, void *data);
CustomAI *ai(int nation) const { return m_ai[static_cast<size_t>(nation)].get(); }
private:
Factory m_factory;
int m_rwDataSize;
std::array<std::unique_ptr<CustomAI>, nPl> m_ai;
TNewGameData m_game{};
int m_defender = -1;
};
} // namespace Cevo
// Place once in a plugin's main translation unit to export the required C
// ABI "client" entry point, forwarding every call to a (file-scope)
// Cevo::AiModuleHost instance:
//
// Cevo::AiModuleHost host([](int nation) { return std::make_unique<MyAI>(nation); });
// CEVO_EXPORT_AI_CLIENT(host)
#define CEVO_EXPORT_AI_CLIENT(hostVar) \
extern "C" void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data) \
{ \
(hostVar).handle(command, player, data); \
}
+153
View File
@@ -0,0 +1,153 @@
#pragma once
#include "Cevo/Protocol.h"
#include <array>
#include <bitset>
#include <string>
namespace Cevo {
enum class NegoTime { BeginOfTurn, EndOfTurn, EnemyCalled };
constexpr int CityOwnTile = 13; // = ab_to_V21(0, 0)
// C++ equivalent of CustomAI.pas's TCustomAI: the base class for a single
// player's AI "brain". Mirrors the original's full Process() dispatch and
// its protected Unit_*/City_*/general Server-call wrappers, so ported AI
// logic (StdAI's TAI, etc.) plugs in the same way.
class CustomAI {
public:
explicit CustomAI(int nation) : me(nation) {}
virtual ~CustomAI();
// Attaches the player context handed out by the server at
// cmNewGame/cmLoadGame (TNewGameData.RO[nation]).
void bind(TPlayerContext *playerContext);
// Set once per module from cmInitModule's TInitModuleData.Server; shared
// by every CustomAI instance in this process, matching the original's
// single unit-level `Server` global.
static void setServerCall(TServerCall call) { s_server = call; }
// Dispatches a single Command/Data pair received from the host (mirrors
// TCustomAI.Process in full: turn/negotiation loop, scContact probing,
// scDipStart..scDipBreak). cmShowAttacking/cmShowCapturing/
// cmShowAfterAttack/cmShowAfterMove are NOT dispatched through here
// (unlike cmTurn etc.): the original's library wrapper (StdAI.lpr)
// intercepts them directly to call onBeforeEnemyAttack() and friends, see
// AiModuleHost.
void process(int command, void *data);
virtual void setDataDefaults() {}
virtual void setDataRandom() {}
virtual void onBeforeEnemyAttack(const TUnitInfo &unitInfo, int toLoc, int endHealth, int endHealthDef) {}
virtual void onBeforeEnemyCapture(const TUnitInfo &unitInfo, int toLoc) {}
virtual void onAfterEnemyAttack() {}
virtual void onAfterEnemyCapture() {}
protected:
int me; // index of the controlled nation
TPlayerContext *ro = nullptr;
std::uint32_t *map = nullptr; // ro->Map, indexable as map[loc]
TUn *myUnit = nullptr; // ro->Un, indexable as myUnit[uix]
TCity *myCity = nullptr; // ro->City, indexable as myCity[cix]
TModel *myModel = nullptr; // ro->Model, indexable as myModel[mix]
// cix of the city that built a given "state" (unique per empire)
// improvement, indexed by iix - imPalace; -1 if none. Refreshed once per
// cmTurn.
std::array<int, imSpacePort - imPalace + 1> cixStateImp{};
// negotiation
int opponent = -1; // nation i'm in negotiation with, -1 = no negotiation
int myAction = 0, myLastAction = 0, oppoAction = 0;
TOffer myOffer{}, myLastOffer{}, oppoOffer{};
virtual void doTurn() {}
virtual void doNegotiation() {}
virtual int chooseResearchAdvance() { return -1; }
virtual int chooseStealAdvance() { return -1; }
virtual int chooseGovernment() { return gDespotism; }
virtual bool wantNegotiation(int nation, NegoTime negoTime) { return false; }
virtual bool onNegoRejected_CancelTreaty() { return false; }
// ---- general functions ----
bool isResearched(int advance) const
{
return advance == preNone || (advance != preNA && ro->Tech[advance] >= tsApplicable);
}
int researchCost() const;
int changeAttitude(int nation, int attitude) const;
int revolution() const;
int changeRates(int tax, int lux) const;
int prepareNewModel(int domain) const;
int setNewModelFeature(int feature, int count) const;
bool advanceResearchable(int advance) const;
bool advanceStealable(int advance) const;
bool getJobProgress(int loc, TJobProgressData &jobProgress) const;
bool debugMessage(int level, const std::string &text) const;
bool setDebugMap(void *debugMap) const;
// ---- unit functions ----
int unit_FindMyDefender(int loc) const;
int unit_FindEnemyDefender(int loc) const;
int unit_Move(int uix, int toLoc);
int unit_Step(int uix, int toLoc);
int unit_Attack(int uix, int toLoc) const;
int unit_DoMission(int uix, int missionType, int toLoc) const;
bool unit_MoveForecast(int uix, int toLoc, int &remainingMovement) const;
bool unit_AttackForecast(int uix, int toLoc, int attackMovement, int &remainingHealth) const;
bool unit_DefenseForecast(int euix, int toLoc, int &remainingHealth) const;
int unit_Disband(int uix) const;
int unit_StartJob(int uix, int newJob) const;
int unit_SetHomeHere(int uix) const;
int unit_Load(int uix) const;
int unit_Unload(int uix) const;
int unit_SelectTransport(int uix) const;
int unit_AddToCity(int uix) const;
// ---- city functions ----
int city_FindMyCity(int loc) const;
int city_FindEnemyCity(int loc) const;
bool city_HasProject(int cix) const;
int city_CurrentImprovementProject(int cix) const;
int city_CurrentUnitProject(int cix) const;
int city_GetTileInfo(int cix, int tileLoc, TTileInfo &tileInfo) const;
int city_GetReport(int cix, TCityReport &report) const;
int city_GetHypoReport(int cix, int hypoTiles, int hypoTax, int hypoLux, TCityReport &report) const;
int city_GetReportNew(int cix, TCityReportNew &report) const;
int city_GetHypoReportNew(int cix, int hypoTiles, int hypoTaxRate, int hypoLuxuryRate,
TCityReportNew &report) const;
int city_GetAreaInfo(int cix, TCityAreaInfo &areaInfo) const;
int city_StartUnitProduction(int cix, int mix) const;
int city_StartEmigration(int cix, int mix, bool allowDisbandCity, bool asConscripts) const;
int city_StartImprovement(int cix, int iix) const;
bool city_Improvable(int cix, int iix) const;
int city_StopProduction(int cix) const;
int city_BuyProject(int cix) const;
int city_SellImprovement(int cix, int iix) const;
int city_RebuildImprovement(int cix, int iix) const;
int city_SetTiles(int cix, int newTiles) const;
void city_OptimizeTiles(int cix, std::uint32_t resourceWeights = rwMaxGrowth) const;
// ---- negotiation ----
int nego_CheckMyAction() const;
// Direct Server() call: Server(command, me, subject, data).
int rawServerCall(int command, int subject, void *data) const
{
return s_server ? s_server(command, me, subject, data) : 0;
}
private:
void stealAdvance();
static TServerCall s_server;
bool haveTurned = false;
std::bitset<nPl> unwantedNego;
std::bitset<nPl> contacted;
};
} // namespace Cevo
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "Cevo/Protocol.h"
namespace Cevo {
using TVicinity8Loc = std::int32_t[8];
using TVicinity21Loc = std::int32_t[28];
// Map-geometry helpers ported from CustomAI.pas's free functions (ab_to_Loc,
// Loc_to_ab, ...). Call InitGeometry() once per game (cmNewGame/cmLoadGame,
// before any CustomAI instances are created) - mirrors CustomAI.pas's
// Init(NewGameData). Process-global, like the original's unit-level G/MapSize.
void InitGeometry(const TNewGameData &newGameData);
int MapWidth();
int MapHeight();
int MapSize();
// G.Difficulty[nation] from the same TNewGameData passed to InitGeometry().
int Difficulty(int nation);
// Relative location from Loc0, in (A, B) hex-offset coordinates; -0x1000 if
// off the (south-pole-capped) map.
void ab_to_Loc(int Loc0, int A, int B, int &Loc);
void Loc_to_ab(int Loc0, int Loc, int &A, int &B);
void ab_to_V8(int A, int B, int &V8);
void V8_to_ab(int V8, int &A, int &B);
void ab_to_V21(int A, int B, int &V21);
void V21_to_ab(int V21, int &A, int &B);
void V8_to_Loc(int Loc0, TVicinity8Loc &VicinityLoc);
void V21_to_Loc(int Loc0, TVicinity21Loc &VicinityLoc);
int Distance(int Loc0, int Loc1);
} // namespace Cevo
+41
View File
@@ -0,0 +1,41 @@
#pragma once
namespace Cevo {
// Indexed binary min-heap (decrease-key capable priority queue), ported from
// Pile.pas ("single instance priority queue; main parts contributed by
// Rassim Eminli"). The original was a single global instance reused across
// callers via Create()/Free(); this port lifts that restriction (each
// instance owns its storage) but keeps the same Create/Free/Empty/Put/
// TestPut/Get API so a port of ToolAI.pas's usage is mechanical.
class Pile {
public:
static constexpr int MaxSize = 9600;
// (Re)initializes the pile for items in [0, size). Must be called
// before put()/get().
void create(int size);
void free() {} // kept for API parity; nothing to release
void empty();
// Inserts/decreases the priority of `item` to `value`. Returns false
// (no change made) if `item` is already queued with a value <= `value`.
bool put(int item, int value);
// Like put(), without the side effect: would it actually change anything?
bool testPut(int item, int value) const;
// Removes and returns the lowest-value item. Returns false if empty.
bool get(int &item, int &value);
private:
struct HeapItem {
int item;
int value;
};
HeapItem bh_[MaxSize];
int ix_[MaxSize];
int n_ = 0;
int currentSize_ = 0;
};
} // namespace Cevo
File diff suppressed because it is too large. Load diff
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include "Cevo/CustomAI.h"
#include "Cevo/Pile.h"
#include <array>
#include <cstdint>
namespace Cevo {
// no-formation sentinel values (Formation[]/map analysis)
constexpr int nfUndiscovered = -1;
constexpr int nfPole = -2;
constexpr int nfPeace = -3;
// return codes of checkStep()
constexpr int csOk = 0; // step is valid, timeAfterStep has been calculated
constexpr int csForbiddenTile = 1; // unit can not move onto this tile
constexpr int csForbiddenStep = 2; // (ZoC unit only) unit can not do this step because of ZoC violation
constexpr int csCheckTerritory = 3; // move within other nation's territory shortly after peace
constexpr int mxAdjacent = 0x00000001; // unit_MoveEx option
struct GroupTransportPlan {
int LoadLoc = -1;
int uixTransport = 0;
int nLoad = 0;
int TurnsEmpty = 0;
int TurnsLoaded = 0;
int uixLoad[16] = {};
};
// Total number of prerequisites for each advance; computed once at process
// startup (mirrors ToolAI.pas's SetAdvancedness(), run from its
// `initialization` section).
extern const std::array<int, nAdv> Advancedness;
// C++ equivalent of ToolAI.pas's TToolAI: map analysis, job assignment,
// pathfinding and sea-transport planning helpers built on top of CustomAI's
// raw Server-call wrappers.
//
// Like the original, the scratch state below (formation/district/cityResult,
// job-assignment and sea-transport working buffers, the Pile instance) is
// process-shared (static), not per-nation: AI turn processing is strictly
// sequential (one nation's DoTurn() completes before another's starts), so
// the original reused unit-level globals instead of per-instance buffers.
class ToolAI : public CustomAI {
public:
using CustomAI::CustomAI;
protected:
int centerOfEmpire() const; // tile that is in the middle of all own cities
// Exact difference of income and maintenance cost for a single city;
// positive = income higher than maintenance. cityReport must have been
// prepared (city_GetReport/city_GetHypoReport) before calling this.
int cityTaxBalance(int cix, const TCityReport &cityReport) const;
// Exact total tax and science income; tax is reduced by maintenance (so
// might be negative). Luxury not supported.
void sumCities(int taxRate, int &taxSum, int &scienceSum) const;
void optimizeCityTiles() const; // obsolete; use city_OptimizeTiles instead
void getCityProdPotential(); // fills cityResult[cix] with production potential
void getCityTradePotential(); // fills cityResult[cix] with trade potential
// Settler job assignment: initialize, add jobs/units, then go; assigns
// each job to one settler, moves the settlers and makes them work.
void jobAssignment_Initialize();
void jobAssignment_AddJob(int loc, int job, int score);
void jobAssignment_AddUnit(int uix);
void jobAssignment_Go();
bool jobAssignment_GotJob(int uix) const;
void analyzeMap(); // calculates formations (continents/oceans) and districts
// Forecast a single unit move between adjacent tiles. fromTile/toTile
// must be Map[FromLoc]/Map[ToLoc] (not location codes). crossCorner=1 for
// long moves crossing the tile corner, 0 for short ones that don't.
int checkStep(int moveStyle, int timeBeforeStep, int crossCorner, int &timeAfterStep, int &recoverTurns,
std::uint32_t fromTile, std::uint32_t toTile, bool isCapture) const;
int getMyMoveStyle(int mix, int health) const;
int unit_MoveEx(int uix, int toLoc, int options = 0);
// Sea transport, obligatory call order: beginInitialize; [addLoad/
// addTransport/addDestination]*; endInitialize; [makeGroupPlan]*.
void seaTransport_BeginInitialize();
void seaTransport_EndInitialize();
void seaTransport_AddLoad(int uix);
void seaTransport_AddTransport(int uix);
void seaTransport_AddDestination(int loc);
bool seaTransport_MakeGroupPlan(GroupTransportPlan &transportPlan);
int currentMStrength(int domain) const;
static int nContinent, nOcean, nDistrict;
// water: ocean index, land: continent index, sorted by size; territory
// unpassable due to peace treaty divides a continent.
static std::array<int, lxmax * lymax> formation;
// index of coherent own territory, sorted by size.
static std::array<int, lxmax * lymax> district;
static std::array<int, nCmax> cityResult;
// Shared single-instance priority queue (mirrors Pile.pas being its own
// unit used directly by both ToolAI.pas and Barbarina.pas); protected so
// Barbarina can use it for its own pathfinding (attack/patrol scoring).
static Pile pile;
private:
// JobAssignment state
static int maxScore;
static std::array<std::uint8_t, lxmax * lymax> tileJob;
static std::array<std::uint8_t, lxmax * lymax> tileJobScore;
static std::array<int, nUmax> jobLocOfSettler; // ToAssign sentinel = find job
// SeaTransport state
static int transportMoveStyle, transportCapacity, nTransportLoad;
static bool initComplete, haveDestinations;
static std::array<int, nUmax> uixTransportLoad;
static std::array<int, nUmax> transportAvailable;
static std::array<std::int8_t, lxmax * lymax> turnsAfterLoad;
};
} // namespace Cevo