Files

524 lines
19 KiB
C++

// 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 "Term.h"
#include "Cevo/CmdList.h"
#include "Global.h"
#include "Help.h"
#include "IsoEngine.h"
#include "Tribes.h"
#include <QFile>
#include <algorithm>
#include <cstring>
namespace Cevo {
namespace Term {
PersistentData *myData = nullptr;
Dpi::Bitmap *smallImp = nullptr;
bool mainScreenNamesChecked = true;
Dpi::Bitmap buffer;
ClientTools::SaveOptions optionChecked = 0;
bool supervising = false;
std::array<DipMemEntry, nPl> dipMem{};
std::function<int(int)> mainScreenDipCall = [](int) { return eInvalid; };
std::function<bool(int, const QString &)> mainScreenContactRefused = [](int, const QString &) { return false; };
int roughCredibility(int credibility)
{
if (credibility <= 69)
return 0;
if (credibility <= 89)
return 1;
if (credibility <= 99)
return 2;
return 3;
}
QString turnToString(int turn)
{
if (!generateNames)
return QString::number(turn);
const int year = turnToYear(turn);
return phraseToQtFormat(phrases.lookup(year < 0 ? QStringLiteral("BC") : QStringLiteral("AD")))
.arg(std::abs(year));
}
void impImage(Dpi::Canvas &canvas, int x, int y, int iix, int government, bool isControl)
{
if (government < 0)
government = ClientTools::myRO->Government;
if (iix == imPalace && government != gAnarchy)
iix = government - 8;
if (!bigImp)
return;
frameImage(canvas, *bigImp, x, y, xSizeBig, ySizeBig, (iix + SystemIconLines * 7) % 7 * xSizeBig,
(iix + SystemIconLines * 7) / 7 * ySizeBig, isControl);
}
void chooseModelPicture(int p, int mix, int code, int hash, int turn, bool forceNew, bool final)
{
const auto player = static_cast<std::size_t>(p);
Tribes::ModelPictureInfo picture;
picture.trix = p;
picture.mix = mix;
bool isNew;
if (code == 74) { // use correct pictures for slaves
if (Tribes::tribe[player]->mixSlaves < 0) {
if (!tribeOriginal[player]) {
Tribes::tribe[player]->mixSlaves = mix;
} else {
int data = mix + (p << 16);
ClientTools::server(cSetSlaveIndex, 0, 0, &data);
}
}
picture.pix = toldSlavery == 1 ? pixSlaves : pixNoSlaves;
picture.hash = 0;
picture.grName = QStringLiteral("StdUnits");
isNew = true;
} else {
picture.hash = hash;
isNew = Tribes::tribe[player]->chooseModelPicture(picture, code, turn, forceNew);
}
if (final) {
if (!tribeOriginal[player]) {
Tribes::tribe[player]->setModelPicture(picture, isNew);
} else {
QByteArray data = packModelPictureInfo(picture);
ClientTools::server(commandWithData(isNew ? cSetNewModelPicture : cSetModelPicture,
picture.commandDataSize()),
0, 0, data.data());
}
} else {
Tribes::ModelPicture &mp = Tribes::tribe[player]->modelPictureAt(mix);
mp.hGr = loadGraphicSet(picture.grName);
mp.pix = picture.pix;
}
}
void initMyModel(int mix, bool final)
{
// special models (Kind >= $08) still get a picture: cSetModelPicture comes after tellNewModels()
if (gameMode == cMovie && ClientTools::myModel[mix].Kind < 0x08)
return;
TModelInfo mi{};
MakeModelInfo(ClientTools::me, mix, ClientTools::myModel[mix], mi);
chooseModelPicture(ClientTools::me, mix, Tribes::modelCode(mi), ClientTools::modelHash(mi),
ClientTools::myRO->Turn, false, final);
}
int gameMode = 0;
int age = 0;
std::uint32_t cityRepMask = ~static_cast<std::uint32_t>(chPopIncrease) & ~static_cast<std::uint32_t>(chCaptured) &
~static_cast<std::uint32_t>(chNoGrowthWarning);
std::array<int, nAdv> advIcon = [] {
std::array<int, nAdv> result;
result.fill(-1);
return result;
}();
void initAdvIcons()
{
for (int i = 0; i < nAdv; ++i) {
int &icon = advIcon[static_cast<std::size_t>(i)];
if (IsFutureTech(i)) {
icon = 96 + i - futResearchTechnology;
continue;
}
icon = -1;
for (int domain = 0; domain < nDomains; ++domain) {
for (int j = 0; j < nUpgrade; ++j) {
if (Upgrade[domain][j].Preq == i)
icon = icon >= 0 ? 85 : 86 + domain;
}
}
for (int j = 0; j < nFeature; ++j) {
if (Feature[j].Preq != i)
continue;
for (int domain = 0; domain < nDomains; ++domain) {
if (Feature[j].Domains & (1 << domain))
icon = (icon >= 0 && icon != 86 + domain) ? 85 : 86 + domain;
}
}
for (int j = nWonder; j < nImp; ++j) {
if (Imp[j].Preq == i)
icon = j;
}
for (int j = nWonder; j < nImp; ++j) {
if (Imp[j].Preq == i && Imp[j].Kind != ikCommon)
icon = j;
}
for (int j = 0; j < nJob; ++j) {
if (i == JobPreq[j])
icon = 84;
}
for (int j = 0; j < nWonder; ++j) {
if (Imp[j].Preq == i)
icon = j;
}
if (icon < 0)
icon = ClientTools::advValue[static_cast<std::size_t>(i)] < 1000
? -7
: 24 + ClientTools::advValue[static_cast<std::size_t>(i)] / 1000;
for (int j = 2; j < nGov; ++j) {
if (GovPreq[j] == i)
icon = j - 8;
}
}
advIcon[adConscription] = 86 + dGround;
}
std::array<int, nPl * nMmax> lostArmy{};
int nLostArmy = 0;
bool initEnemyModel(int emix)
{
if (gameMode == cMovie)
return false;
const TModelInfo &enemyModel = (*ClientTools::myRO->EnemyModel)[emix];
chooseModelPicture(enemyModel.Owner, enemyModel.mix, Tribes::modelCode(enemyModel),
ClientTools::modelHash(enemyModel), ClientTools::myRO->Turn, false, true);
return true;
}
void initAllEnemyModels()
{
for (int emix = 0; emix < ClientTools::myRO->nEnemyModel; ++emix) {
const TModelInfo &enemyModel = (*ClientTools::myRO->EnemyModel)[emix];
if (!Tribes::tribe[static_cast<std::size_t>(enemyModel.Owner)]->modelPictureAt(enemyModel.mix).hGr)
initEnemyModel(emix);
}
}
namespace {
void appendInt32(QByteArray &data, int value)
{
const auto v = static_cast<std::int32_t>(value);
data.append(reinterpret_cast<const char *>(&v), sizeof v);
}
// Pascal ShortString: length byte followed by the bytes.
void appendShortString(QByteArray &data, const QString &text)
{
QByteArray bytes = text.toUtf8();
bytes.truncate(255);
data.append(static_cast<char>(bytes.size()));
data.append(bytes);
}
std::uint8_t shortStringRecordSize(const QString &text)
{
return static_cast<std::uint8_t>(sizeof(std::int32_t) + 1 + std::min<qsizetype>(255, text.toUtf8().size()));
}
} // namespace
QByteArray TribeInfo::pack() const
{
QByteArray data;
appendInt32(data, trix);
appendShortString(data, fileName);
return data;
}
std::uint8_t TribeInfo::commandDataSize() const { return shortStringRecordSize(fileName); }
QByteArray CityNameInfo::pack() const
{
QByteArray data;
appendInt32(data, id);
appendShortString(data, newName);
return data;
}
std::uint8_t CityNameInfo::commandDataSize() const { return shortStringRecordSize(newName); }
QByteArray ModelNameInfo::pack() const
{
QByteArray data;
appendInt32(data, mix);
appendShortString(data, newName);
return data;
}
std::uint8_t ModelNameInfo::commandDataSize() const { return shortStringRecordSize(newName); }
QByteArray packModelPictureInfo(const Tribes::ModelPictureInfo &info)
{
QByteArray data;
appendInt32(data, info.trix);
appendInt32(data, info.mix);
appendInt32(data, info.pix);
appendInt32(data, info.hash);
appendShortString(data, info.grName);
return data;
}
TribeInfo unpackTribeInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
TribeInfo info;
std::int32_t trix;
std::memcpy(&trix, bytes, sizeof trix);
info.trix = trix;
info.fileName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof trix + 1), bytes[sizeof trix]);
return info;
}
CityNameInfo unpackCityNameInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
CityNameInfo info;
std::int32_t id;
std::memcpy(&id, bytes, sizeof id);
info.id = id;
info.newName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof id + 1), bytes[sizeof id]);
return info;
}
ModelNameInfo unpackModelNameInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
ModelNameInfo info;
std::int32_t mix;
std::memcpy(&mix, bytes, sizeof mix);
info.mix = mix;
info.newName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof mix + 1), bytes[sizeof mix]);
return info;
}
int clientMode = -1;
std::vector<TribeNameEntry> tribeNames;
void setClientMode(int value)
{
clientMode = value;
IsoEngine::clientMode = value;
}
ClientTools::MapOptions mapOptionChecked = 1u << ClientTools::moCityNames;
int unStartLoc = -1;
Tribes::ModelPictureInfo unpackModelPictureInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
std::int32_t fields[4];
std::memcpy(fields, bytes, sizeof fields);
Tribes::ModelPictureInfo info;
info.trix = fields[0];
info.mix = fields[1];
info.pix = fields[2];
info.hash = fields[3];
const unsigned char length = bytes[sizeof fields];
info.grName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof fields + 1), length);
return info;
}
std::array<bool, nPl> tribeOriginal{};
int toldSlavery = 0;
QString attackSound(int code)
{
return QStringLiteral("ATTACK_%1%2%3").arg(code / 100 % 10).arg(code / 10 % 10).arg(code % 10);
}
int alignUp(int value, int alignment) { return value | (alignment - 1); }
void initSmallImp()
{
static Dpi::Bitmap storage;
smallImp = &storage;
if (!bigImp)
return;
smallImp->setSize(bigImp->width() * xSizeSmall / xSizeBig, bigImp->height() * ySizeSmall / ySizeBig);
smallImp->canvas().stretchDraw(QRect(0, 0, smallImp->width(), smallImp->height()), bigImp->image());
}
void checkToldNoReturn(int uix)
{
// check whether aircraft survived low-fuel warning
Q_ASSERT(!supervising);
TUn &un = ClientTools::myUn[uix];
if ((un.Status & usToldNoReturn) &&
((ClientTools::myMap[un.Loc] & fCity) || (ClientTools::myMap[un.Loc] & fTerImp) == tiBase || un.Master >= 0))
un.Status &= ~usToldNoReturn;
}
bool createTribe(int p, QString fileName, bool original)
{
fileName = localizedFilePath(QStringLiteral("Tribes/") + fileName + QLatin1String(CevoTribeExt));
if (!QFile::exists(fileName))
return false;
const auto player = static_cast<std::size_t>(p);
tribeOriginal[player] = original;
Tribes::tribe[player] = std::make_unique<Tribes::Tribe>(fileName);
if (gameMode == cNewGame || !original) {
chooseModelPicture(p, 0, 10, 1, 0, true, true);
chooseModelPicture(p, 1, 40, 1, 0, true, true);
chooseModelPicture(p, 2, 41, 1, 0, true, true);
chooseModelPicture(p, -1, 17, 1, 0, true, true);
}
dipMem[player].pContact = -1;
return true;
}
void tellNewContacts()
{
if (supervising)
return;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != ClientTools::me && !(myData->toldContact & (1 << p1)) &&
(ClientTools::myRO->Alive & (1 << p1)) && ClientTools::myRO->Treaty[p1] > trNoContact) {
MessgEx::tribeMessage(p1, Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(QStringLiteral("FRNEWNATION")),
QString());
myData->toldContact |= 1 << p1;
}
}
}
void tellNewModels()
{
if (supervising)
return;
Tribes::Tribe &myTribe = *Tribes::tribe[static_cast<std::size_t>(ClientTools::me)];
while (myData->toldModels < ClientTools::myRO->nModel) { // new unit class available
const int told = myData->toldModels;
if (myTribe.modelPictureAt(told).hGr && ClientTools::myModel[told].Kind != mkSelfDeveloped) {
// save picture of DevModel
myTribe.modelPictureAt(told + 1) = myTribe.modelPictureAt(told);
myTribe.modelNameAt(told + 1) = myTribe.modelNameAt(told);
myTribe.modelPictureAt(told).hGr = nullptr;
}
if (!myTribe.modelPictureAt(told).hGr)
initMyModel(told, true);
// only run if no researched model
MessgEx::MessgExDlg *dlg = mainScreenMessgExDlg();
if (dlg) {
if (ClientTools::myModel[told].Kind == mkSelfDeveloped)
dlg->openSound = QStringLiteral("NEWMODEL_%1").arg(age);
// Phrases['MODELAVAILABLE']
dlg->messageText = phrases.lookup(QStringLiteral("MODELAVAILABLE"));
if (gameMode == cMovie) {
dlg->kind = MessageKind::OkHelp; // doesn't matter
dlg->messageText += QLatin1Char('\\') + myTribe.modelNameAt(told);
} else {
dlg->kind = MessageKind::Model;
dlg->setInputText(myTribe.modelNameAt(told));
}
dlg->iconKind = MessgEx::MessageIconKind::Model;
dlg->iconIndex = told;
dlg->showModal();
const QString newName = dlg->inputText();
if (!newName.isEmpty() && newName != myTribe.modelNameAt(told)) { // user renamed model
ModelNameInfo info;
info.mix = told;
info.newName = newName;
while (info.commandDataSize() > CommandDataMaxSize && !info.newName.isEmpty())
info.newName.chop(1);
QByteArray data = info.pack();
ClientTools::server(commandWithData(cSetModelName, info.commandDataSize()), ClientTools::me, 0,
data.data());
}
}
if (ClientTools::myModel[told].Kind == mkSettler) { // engineers make settlers obsolete
for (int mix = 0; mix < told; ++mix) {
if (ClientTools::myModel[mix].Kind == mkSettler)
ClientTools::myModel[mix].Status |= msObsolete;
}
}
++myData->toldModels;
}
}
const std::array<int, nCityEventPriority> CityEventPriority = {
chDisorder, chImprovementLost, chUnitLost, chAllImpsMade,
chProduction, chOldWonder, chNoSettlerProd, chPopDecrease,
chProductionSabotaged, chNoGrowthWarning, chPollution, chTypeDel,
chFounded, chSiege, chAfterCapture, chPopIncrease,
};
const std::array<QString, 16> CityEventSoundItem = {
QStringLiteral("CITY_DISORDER"), QStringLiteral(""),
QStringLiteral("CITY_POPPLUS"), QStringLiteral("CITY_POPMINUS"),
QStringLiteral("CITY_UNITLOST"), QStringLiteral("CITY_IMPLOST"),
QStringLiteral("CITY_SABOTAGE"), QStringLiteral("CITY_GROWTHNEEDSIMP"),
QStringLiteral("CITY_POLLUTION"), QStringLiteral("CITY_SIEGE"),
QStringLiteral("CITY_WONDEREX"), QStringLiteral("CITY_EMDELAY"),
QStringLiteral("CITY_FOUNDED"), QStringLiteral("CITY_FOUNDED"),
QStringLiteral(""), QStringLiteral("CITY_INVALIDTYPE"),
};
QString cityEventName(int i)
{
if (i == 14) // chAllImpsMade
return phrases2FallenBackToEnglish ? phrases.lookup(QStringLiteral("CITYEVENTS"), 1)
: phrases2.lookup(QStringLiteral("CITYEVENT_ALLIMPSMADE"));
return phrases.lookup(QStringLiteral("CITYEVENTS"), i);
}
void helpOnTerrain(int loc, WindowMode newMode)
{
auto *dlg = mainScreenHelpDlg();
if (!dlg)
return;
if (ClientTools::myMap[loc] & fDeadLands) {
dlg->showNewContent(newMode, Help::LinkCategory::Ter, 3 * 12);
} else if ((ClientTools::myMap[loc] & fTerrain) == fForest &&
IsoEngine::isJungle(loc / ClientTools::g.lx)) {
dlg->showNewContent(newMode, Help::LinkCategory::Ter, fJungle + (ClientTools::myMap[loc] >> 5 & 3) * 12);
} else {
dlg->showNewContent(newMode, Help::LinkCategory::Ter,
(ClientTools::myMap[loc] & fTerrain) + (ClientTools::myMap[loc] >> 5 & 3) * 12);
}
}
std::function<bool(int, bool, int)> mainScreenZoomToCity = [](int, bool, int) { return false; };
std::function<void(int, bool, bool)> mainScreenCityClosed = [](int, bool, bool) {};
std::function<void(bool)> mainScreenUpdateViews = [](bool) {};
std::function<void()> mainScreenRepaintAll = [] {};
std::function<int(int)> modalSelectDlgShowCityProject = [](int) { return -1; };
std::function<bool(int)> listDlgRenameCity = [](int) { return false; };
std::function<MessgEx::MessgExDlg *()> mainScreenMessgExDlg = [] { return static_cast<MessgEx::MessgExDlg *>(nullptr); };
std::function<Select::ListDlg *()> mainScreenModalSelectDlg = [] { return static_cast<Select::ListDlg *>(nullptr); };
std::function<NatStat::NatStatDlg *()> mainScreenNatStatDlg = [] { return static_cast<NatStat::NatStatDlg *>(nullptr); };
std::function<Help::HelpDlg *()> mainScreenHelpDlg = [] { return static_cast<Help::HelpDlg *>(nullptr); };
std::function<int(const TOffer &)> mainScreenOfferCall = [](const TOffer &) { return eInvalid; };
TOffer receivedOffer{};
int taxSum = 0;
int scienceSum = 0;
std::vector<UnusedTribe> unusedTribeFiles;
MainScreen *mainScreen = nullptr;
} // namespace Term
} // namespace Cevo