// This file is part of c-evo-evo. // // This software is governed by the CeCILL license under French law and // abiding by the rules of distribution of free software. You can use, // modify and/or redistribute the software under the terms of the CeCILL // license as circulated by CEA, CNRS and INRIA at the following URL // "http://www.cecill.info". // // As a counterpart to the access to the source code and rights to copy, // modify and redistribute granted by the license, users are provided only // with a limited warranty and the software's author, the holder of the // economic rights, and the successive licensors have only limited // liability. // // In this respect, the user's attention is drawn to the risks associated // with loading, using, modifying and/or developing or reproducing the // software by the user in light of its specific status of free software, // that may mean that it is complicated to manipulate, and that also // therefore means that it is reserved for developers and experienced // professionals having in-depth computer knowledge. Users are therefore // encouraged to load and test the software's suitability as regards their // requirements in conditions enabling the security of their systems and/or // data to be ensured and, more generally, to use and operate it in the // same conditions as regards security. // // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. #include "Cevo/CustomAI.h" #include "Cevo/Geometry.h" #include 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(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(nation)] && !unwantedNego[static_cast(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(nation)); opponent = nation; myAction = scContact; return; } } else { unwantedNego.set(static_cast(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(reinterpret_cast(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(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(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(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(advice.Tiles)); } // ---- negotiation ---- int CustomAI::nego_CheckMyAction() const { if (myAction == scDipOffer) return rawServerCall(myAction - sExecute, 0, const_cast(&myOffer)); return rawServerCall(myAction - sExecute, 0, nullptr); } } // namespace Cevo