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

+45
View File
@@ -0,0 +1,45 @@
# CevoAI: C++ port of the C-evo AI plugin protocol (AI Template/Protocol.pas
# + CustomAI.pas), used to load/host AI "brain" modules (StdAI, Capital AI,
# KIAI, SETI, Shah, Crystal, ...) and to write new ones. Deliberately has NO
# dependency on Qt (or any other framework): the original protocol is a plain
# C ABI (stdcall function pointers + C-aligned structs), and this port keeps
# it that way so existing precompiled AI .dll/.so files stay loadable and new
# AI modules can be built as plain, portable C++ shared libraries.
#
# Concrete AI "brain" implementations (StdAI, ...) live in their own
# subdirectory below this one (e.g. stdai/), each built as a separate
# shared-library plugin on top of this interface - see stdai/CMakeLists.txt.
set(CEVO_AI_HEADERS
include/Cevo/AiModule.h
include/Cevo/AiModuleHost.h
include/Cevo/CustomAI.h
include/Cevo/Geometry.h
include/Cevo/Pile.h
include/Cevo/Protocol.h
include/Cevo/ToolAI.h
)
set(CEVO_AI_SOURCES
src/AiModule.cpp
src/AiModuleHost.cpp
src/CustomAI.cpp
src/Geometry.cpp
src/Pile.cpp
src/Protocol.cpp
src/ToolAI.cpp
)
add_library(cevoai STATIC ${CEVO_AI_SOURCES} ${CEVO_AI_HEADERS})
target_include_directories(cevoai PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include
)
target_link_libraries(cevoai PUBLIC ${CMAKE_DL_LIBS})
set_target_properties(cevoai PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
POSITION_INDEPENDENT_CODE ON
)
+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
+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
+39
View File
@@ -0,0 +1,39 @@
# StdAI: concrete AI "brain" plugin built on top of ../ (the generic
# AiModule/AiModuleHost/CustomAI/ToolAI protocol layer). Ported from
# perso/cevo/AI/StdAI/{Barbarina.pas, AI.pas} - class Cevo::AI (TAI) derives
# from Cevo::Barbarina (TBarbarina) derives from Cevo::ToolAI.
#
# Built as its own shared library (not linked into the cevo-evo executable):
# like the original's StdAI.dll/.so, it is meant to be loaded dynamically at
# runtime (via Cevo::AiModule) alongside other precompiled AI modules.
set(STDAI_HEADERS
include/Cevo/AI.h
include/Cevo/Barbarina.h
)
set(STDAI_SOURCES
src/AI.cpp
src/Barbarina.cpp
src/StdAIModule.cpp
)
add_library(stdai SHARED ${STDAI_SOURCES} ${STDAI_HEADERS})
target_include_directories(stdai PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
)
target_link_libraries(stdai PRIVATE cevoai)
set_target_properties(stdai PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
PREFIX ""
)
include(GNUInstallDirs)
install(TARGETS stdai
LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR}
)
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include "Cevo/Barbarina.h"
#include <array>
namespace Cevo {
constexpr int nAIModelCat = 4;
constexpr int mctNone = -1;
constexpr int mctGroundDefender = 0;
constexpr int mctGroundAttacker = 1;
constexpr int mctTransport = 2;
constexpr int mctCruiser = 3;
constexpr int nRequestedTechs = 48;
enum class Suggestion { Contact, Peace, Friendly };
// Raw per-nation scratch memory the host allocates (rwDataSize bytes) and
// hands back via TPlayerContext::Data - reinterpreted in place, NOT
// constructed, so these fields must NOT rely on default member
// initializers (see setDataDefaults(), which is what actually initializes
// a fresh block on cmNewGame, mirroring the original's SetDataDefaults).
struct TPersistentData {
int LastResearchTech;
int BehaviorFlags;
int TheologyPartner;
std::int16_t RejectTurn[3][16]; // [Suggestion][0..15]
int RequestedTechs[nRequestedTechs]; // ad + p shl 8 + Turn shl 16
};
// C++ equivalent of AI.pas's TAI: the actual StdAI decision heuristics
// (research strategy, terraforming/settlers, production, combat/patrol,
// diplomacy), built on top of Barbarina's "barbarian mode" personality.
// This is the final/top-level AI class a StdAI plugin module instantiates.
class AI : public Barbarina {
public:
explicit AI(int nation);
void setDataDefaults() override;
protected:
TPersistentData *data = nullptr;
int warNations = 0, bombardingNations = 0;
int mixSettlers = 0, mixCaravan = 0, mixTownGuard = 0, mixSlaves = 0, mixMilitia = 0, mixCruiser = 0;
int oceanWithShip = 0;
enum class AINegoCause { Routine, CheckBarbarina };
AINegoCause negoCause = AINegoCause::Routine;
std::array<int, maxCOD> settlerSurplus{};
std::array<int, maxCOD> uixPatrol{};
// Hides Barbarina's own continentPresence/oceanPresence (same name
// collision as the original Pascal: TAI declares its own, separate from
// TBarbarina's private fields).
std::array<int, maxCOD> continentPresence{};
std::array<int, maxCOD> oceanPresence{};
std::array<std::array<int, mctGroundAttacker - mctGroundDefender + 1>, maxCOD> unitLack{};
std::array<int, nPl> totalPopulation{};
std::array<std::array<int, maxCOD>, nPl> continentPopulation{};
std::array<int, maxCOD> districtPopulation{};
std::array<int, nMmax> modelCat{};
std::array<int, nMmax> modelQuality{};
std::array<int, nAIModelCat> modelBestQuality{};
std::array<int, nAdv> advanceValue{};
bool advanceValuesSet = false;
void doTurn() override;
void doNegotiation() override;
int chooseResearchAdvance() override;
int chooseStealAdvance() override;
int chooseGovernment() override;
bool wantNegotiation(int nation, NegoTime negoTime) override;
bool onNegoRejected_CancelTreaty() override;
void findBestTrade(int nation, int &adWanted, int &adGiveAway);
void checkGender();
// Hides Barbarina::analyzeMap()/ToolAI::analyzeMap() - calls
// Barbarina::analyzeMap() first (matches the original's `inherited;`).
// NOTE: ToolAI::analyzeMap() (Formation[]/District[] computation) is
// NEVER called anywhere in the original class hierarchy either - see
// AI.cpp's comment on this for a confirmed-via-source-grep explanation
// (genuine dead code / latent bug in upstream StdAI, ported faithfully).
void analyzeMap();
void collectModelCatStat();
// Hides Barbarina::attackAndPatrol() - a completely different algorithm.
void attackAndPatrol();
void moveUnitsHome();
void checkAttack(int uix);
void patrol(int uix);
// Hides Barbarina::barbarina_SetCityProduction() (different method name,
// no actual collision, but still TAI's own top-level production logic).
void setCityProduction();
void setAdvanceValues();
bool havePort() const;
void rateModel(const TModelInfo &mi, int &category, int &quality) const;
void rateMyModel(int mix, int &category, int &quality) const;
bool isBetterModel(const TModelInfo &mi) const;
void tileWorkPlan(int loc, int cix, int &value, int &nextJob, int &totalWork);
void processSettlers();
int mostWanted(int nation, int adGiveAway) const;
};
} // namespace Cevo
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include "Cevo/ToolAI.h"
#include <array>
#include <cstdint>
namespace Cevo {
constexpr int nModelCategory = 4;
constexpr int ctGroundSlow = 0;
constexpr int ctGroundFast = 1;
constexpr int ctSeaTrans = 2;
constexpr int ctSeaArt = 3;
constexpr int maxCOD = 256;
constexpr int maxModern = 16;
// maximum number of modern resources of one type being managed (for
// designed maps only, number is 2 in standard game)
struct ColonyShipPlanPart {
int cixProducing = -1;
int LocResource[maxModern] = {};
int nLocResource = 0;
int LocFoundCity[maxModern] = {};
int nLocFoundCity = 0;
};
using TColonyShipPlan = std::array<ColonyShipPlanPart, nShipPart>;
// C++ equivalent of Barbarina.pas's TBarbarina: the "barbarian" AI
// personality StdAI's TAI is built directly on top of (required base class,
// not an optional/alternate mode).
class Barbarina : public ToolAI {
public:
explicit Barbarina(int nation);
protected:
TColonyShipPlan ColonyShipPlan;
bool barbarina_GoHidden() const; // whether we should prepare for barbarina mode
bool barbarina_Go() const; // whether we should switch to barbarina mode now
void barbarina_DoTurn();
void barbarina_SetCityProduction();
int barbarina_ChooseResearchAdvance();
bool barbarina_WantCheckNegotiation(int nation) const;
void barbarina_DoCheckNegotiation();
bool barbarina_WantNegotiation(int nation, NegoTime negoTime);
void barbarina_DoNegotiation();
void makeColonyShipPlan();
// Hides (not overrides) ToolAI::analyzeMap(), matching the original's
// method hiding - TBarbarina.AnalyzeMap computes continent/ocean
// *presence* given Formation/District already populated; its own
// `// inherited;` is commented out in the original too. Protected (not
// private) so AI::analyzeMap() can call Barbarina::analyzeMap()
// explicitly, mirroring the original's `inherited;`.
void analyzeMap();
private:
int turnOfMapAnalysis = -1;
int neighbours = 0;
std::array<int, maxCOD> continentPresence{};
std::array<int, maxCOD> oceanPresence{};
std::array<int, maxCOD> continentSize{};
std::array<int, maxCOD> oceanSize{};
std::array<int, nModelCategory> mixBest{};
enum class NegoCauseKind { CancelTreaty };
NegoCauseKind negoCause = NegoCauseKind::CancelTreaty;
bool isModelAvailable(int rmix) const;
void findBestModels();
void rateAttack(int uix);
bool doAttack(int uix, int attackLoc);
bool processMove(int uix);
void attackAndPatrol();
static constexpr int neumax = 4096;
static std::array<bool, nUmax> moved;
static std::array<std::uint8_t, lxmax * lymax> unitPresence;
static std::array<std::int16_t, lxmax * lymax> euixMap;
static std::array<std::int16_t, neumax> uixAttack;
static std::array<int, neumax> attackScore;
};
} // namespace Cevo
+2552
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
// Plugin entry point: exports the "client" C-ABI function a host (or this
// project's own cevo-evo, via AiModule) loads via dlopen/LoadLibrary to
// drive the StdAI brain. Mirrors StdAI.lpr's `exports client;` in the
// original Pascal project - everything else is implemented by the generic
// AiModuleHost (see ../../include/Cevo/AiModuleHost.h) plus Cevo::AI.
#include "Cevo/AI.h"
#include "Cevo/AiModuleHost.h"
#include <memory>
namespace {
Cevo::AiModuleHost host([](int nation) { return std::make_unique<Cevo::AI>(nation); },
sizeof(Cevo::TPersistentData));
} // namespace
CEVO_EXPORT_AI_CLIENT(host)