main window and many fixes

This commit is contained in:
Geoffray Levasseur committed 2026-11-04 17:35:34 +01:00
1 parent 80c329a697
commit 69700f8b65
18 files changed
+3280 -95

No files matched your search

+1
View File
@@ -171,6 +171,7 @@ void play(const QString &item)
CityDlg::CityDlg(QWidget *parent) : BufferedDrawDlg(parent), ui(new Ui::CityDlg)
{
ui->setupUi(this);
initButtons();
redTex.image(); // ensure Texture's lazily-constructed image exists
barTex.image();
noMap = std::make_unique<IsoEngine::IsoMap>();
+54 -36
View File
@@ -35,6 +35,7 @@
#include "Cevo/Protocol.h"
#include "ClientTools.h"
#include "Diagram.h"
#include "Global.h"
#include "Term.h"
#include "Tribes.h"
#include "UnitStat.h"
@@ -61,6 +62,7 @@ MessgExDlg *instance = nullptr;
MessgExDlg::MessgExDlg(QWidget *parent) : BaseMessgDlg(parent), ui(new Ui::MessgExDlg)
{
ui->setupUi(this);
initButtons();
iconKind = MessageIconKind::None;
centerTo = 0;
openSound.clear();
@@ -132,7 +134,14 @@ void MessgExDlg::keyPressEvent(QKeyEvent *event)
void MessgExDlg::showEvent(QShowEvent *event)
{
BaseMessgDlg::showEvent(event);
setWindowTitle(tr("Message"));
prepareLayout();
}
// Sizes and arranges the dialog for its content; also called before show() because some window systems
// ignore geometry changes made once the window is mapped.
void MessgExDlg::prepareLayout()
{
setWindowTitle(phrases.lookup(QStringLiteral("TITLE_MESSAGE")));
if (iconKind == MessageIconKind::EnemyArmy)
Term::initAllEnemyModels();
@@ -155,26 +164,24 @@ void MessgExDlg::showEvent(QShowEvent *event)
}
ui->removeBtn->move(width() - 38, ui->removeBtn->y());
// TODO: needs Phrases[] (StringTables.pas, not ported yet) - plain
// English literals until localization is ported.
switch (kind) {
case MessageKind::YesNo:
case MessageKind::YesNoCancel:
ui->button1->setCaption(tr("Yes"));
ui->button2->setCaption(tr("No"));
ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_YES")));
ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_NO")));
break;
case MessageKind::OkCancel:
case MessageKind::OkCancelRemove:
ui->button1->setCaption(tr("OK"));
ui->button2->setCaption(tr("Cancel"));
ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_OK")));
ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_CANCEL")));
break;
default:
ui->button1->setCaption(tr("OK"));
ui->button2->setCaption(tr("Info"));
ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_OK")));
ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_INFO")));
break;
}
ui->button3->setCaption(tr("Cancel"));
ui->removeBtn->setToolTip(tr("Delete saved game"));
ui->button3->setCaption(phrases.lookup(QStringLiteral("BTN_CANCEL")));
ui->removeBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_DELGAME")));
switch (iconKind) {
case MessageIconKind::Imp:
@@ -248,7 +255,7 @@ void MessgExDlg::showEvent(QShowEvent *event)
Dpi::ModalResult MessgExDlg::showModal()
{
setWindowTitle(tr("Message"));
prepareLayout();
if (Term::gameMode == cMovie) {
movieCancelled = false;
show();
@@ -514,49 +521,60 @@ void setInstance(MessgExDlg *dlg)
instance = dlg;
}
namespace {
MessgExDlg *current()
{
return instance ? instance : Term::mainScreenMessgExDlg();
}
} // namespace
void soundMessageEx(const QString &simpleText, const QString &soundItem)
{
if (!instance)
MessgExDlg *dlg = current();
if (!dlg)
return;
instance->messageText = simpleText;
instance->openSound = soundItem;
instance->kind = MessageKind::Ok;
instance->showModal();
dlg->messageText = simpleText;
dlg->openSound = soundItem;
dlg->kind = MessageKind::Ok;
dlg->showModal();
}
void tribeMessage(int p, const QString &simpleText, const QString &soundItem)
{
if (!instance)
MessgExDlg *dlg = current();
if (!dlg)
return;
instance->openSound = soundItem;
instance->messageText = simpleText;
instance->kind = MessageKind::Ok;
instance->iconKind = MessageIconKind::Tribe;
instance->iconIndex = p;
instance->showModal();
dlg->openSound = soundItem;
dlg->messageText = simpleText;
dlg->kind = MessageKind::Ok;
dlg->iconKind = MessageIconKind::Tribe;
dlg->iconIndex = p;
dlg->showModal();
}
Dpi::ModalResult simpleQuery(MessageKind queryKind, const QString &simpleText, const QString &soundItem)
{
if (!instance)
MessgExDlg *dlg = current();
if (!dlg)
return Dpi::ModalResult::None;
instance->messageText = simpleText;
instance->openSound = soundItem;
instance->kind = queryKind;
return instance->showModal();
dlg->messageText = simpleText;
dlg->openSound = soundItem;
dlg->kind = queryKind;
return dlg->showModal();
}
void contextMessage(const QString &simpleText, const QString &soundItem, Help::LinkCategory contextKind,
int contextNo)
{
if (!instance)
MessgExDlg *dlg = current();
if (!dlg)
return;
instance->messageText = simpleText;
instance->openSound = soundItem;
instance->kind = MessageKind::OkHelp;
instance->helpKind = contextKind;
instance->helpNo = contextNo;
instance->showModal();
dlg->messageText = simpleText;
dlg->openSound = soundItem;
dlg->kind = MessageKind::OkHelp;
dlg->helpKind = contextKind;
dlg->helpNo = contextNo;
dlg->showModal();
}
} // namespace MessgEx
+1
View File
@@ -88,6 +88,7 @@ protected:
void keyPressEvent(QKeyEvent *event) override;
private:
void prepareLayout();
void paintBook(Dpi::Canvas &canvas, int x, int y, QColor clPage, QColor clCover);
void paintMyArmy(Dpi::Canvas &canvas);
void paintEnemyArmy(Dpi::Canvas &canvas);
+43 -15
View File
@@ -31,16 +31,14 @@
//
// PORT STATUS: served so far - cDebugMessage, cShowNego, cInitModule,
// cReleaseModule, cHelpOnly/cStartHelp/cStartCredits, cNewGame/cLoadGame/
// cMovie/cNewMap, cGetReady/cReplay, cBreakGame, the pure message commands
// (cShowCancelTreaty*, cShowSupportAllianceAgainst, cShowPeaceViolation,
// cShowMissionResult, cShowShipChange, cShowGreatLibTech), cShowEndContact
// and the client exclusive commands. Still missing because they need
// InitTurn()/the main map and panel (not ported): cShowGame, cTurn/
// cResume/cContinue/cMovieTurn/cMovieEndTurn, cEditMap, scContact and
// scDipStart..scDipBreak, cShowUnitChanged/CityChanged/AfterMove/
// AfterAttack/Moving/Capturing/Attacking, cRefreshDebugMap. Screen-only
// side effects inside the served commands (button visibility, panel
// repaint, sounds) are marked TODO.
// cMovie/cNewMap, cGetReady/cReplay, cBreakGame, cShowGame, cShowTurnChange,
// cTurn/cResume/cContinue, cMovieTurn/cMovieEndTurn, cEditMap, scContact,
// scDipStart..scDipBreak, the pure message commands (cShowCancelTreaty*,
// cShowSupportAllianceAgainst, cShowPeaceViolation, cShowMissionResult,
// cShowShipChange, cShowGreatLibTech), cShowEndContact and the client
// exclusive commands. Still missing because they need MoveUnit/ShowMove
// (not ported): cShowUnitChanged/CityChanged/AfterMove/AfterAttack/Moving/
// Capturing/Attacking, cRefreshDebugMap.
#include "Term.MainScreen.h"
@@ -50,6 +48,7 @@
#include "Cevo/CmdList.h"
#include "Global.h"
#include "Messg.h"
#include "Sound.h"
#include "Tribes.h"
#include <QApplication>
@@ -137,7 +136,6 @@ void initPersistentData(PersistentData &data)
void MainScreen::client(int command, int newPlayer, void *data)
{
qWarning("TMPDEBUG client(%x, %d)", command, newPlayer);
TNewGameData &g = ClientTools::g;
const auto intData = [data] { return *static_cast<int *>(data); };
const auto isLocalSession = [] { return !ClientTools::isMultiPlayerGame(); };
@@ -302,7 +300,8 @@ void MainScreen::client(int command, int newPlayer, void *data)
return;
case cBreakGame:
// TODO: SaveSettings() needs the settings store (not ported).
saveSettings();
saveConfig();
if (m_cityDlg)
m_cityDlg->closeAction = CityScreen::CityCloseAction::None;
applyToVisibleForms(FormAction::Close);
@@ -339,7 +338,15 @@ void MainScreen::client(int command, int newPlayer, void *data)
canvas.brush().setStyle(Qt::NoBrush);
canvas.end();
}
show();
if (fullScreen) {
m_restoredBounds = termBounds;
m_formFullScreen = true;
showFullScreen();
} else {
m_formFullScreen = false;
setGeometry(termBounds);
show();
}
updateNow();
resizeControls();
m_repaintOnResize = true;
@@ -449,7 +456,6 @@ void MainScreen::client(int command, int newPlayer, void *data)
m_eot->setVisible(false);
helpDlg().difficulty = 0;
m_brushType = fGrass;
// TODO: UpdateInterface (mFillMap.Enabled) belongs to the menus, which are not ported.
m_brushLoc = -1;
m_edited = false;
IsoEngine::unFocus = -1;
@@ -502,13 +508,24 @@ void MainScreen::client(int command, int newPlayer, void *data)
receivedOffer = *static_cast<TOffer *>(data);
initAllEnemyModels();
}
// TODO: the sounds played for scDipStart/scDipCancelTreaty/scDipAccept (sound is not ported).
if (command == scDipStart)
Sound::play(QStringLiteral("CONTACT_%1").arg(ClientTools::myRO->Attitude[dipMem[static_cast<std::size_t>(newPlayer)].pContact]));
else if (command == scDipCancelTreaty)
Sound::play(QStringLiteral("CANCELTREATY"));
if (command == scDipAccept) { // remember delivered and received prices
DipMemEntry &mem = dipMem[static_cast<std::size_t>(ClientTools::me)];
for (int i = 0; i < mem.sentOffer.nDeliver; ++i)
mem.deliveredPrices.set(static_cast<std::size_t>(mem.sentOffer.Price[i] >> 24));
for (int i = 0; i < mem.sentOffer.nCost; ++i)
mem.receivedPrices.set(static_cast<std::size_t>(mem.sentOffer.Price[mem.sentOffer.nDeliver + i] >> 24));
bool isTreatyDeal = false;
for (int i = 0; i < receivedOffer.nDeliver + receivedOffer.nCost; ++i) {
if ((mem.sentOffer.Price[i] & opMask) == opTreaty) {
isTreatyDeal = true;
break;
}
}
Sound::play(isTreatyDeal ? QStringLiteral("NEWTREATY") : QStringLiteral("ACCEPTOFFER"));
}
negoDlg().start();
m_idle = true;
@@ -561,6 +578,17 @@ void MainScreen::client(int command, int newPlayer, void *data)
}
return;
case cShowUnitChanged:
case cShowCityChanged:
case cShowAfterMove:
case cShowAfterAttack:
case cShowMoving:
case cShowCapturing:
case cShowAttacking:
case cRefreshDebugMap:
clientShow(command, newPlayer, data);
return;
case cShowEndContact:
endNego();
return;
+725
View File
@@ -0,0 +1,725 @@
// TMainScreen's mouse and keyboard handling (Term.pas): MapBoxMouseDown,
// PanelBoxMouse*, FormMouse*, FormKeyDown/FormKeyUp and the buttons.
#include "Term.MainScreen.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Global.h"
#include "KeyBindings.h"
#include "Messg.h"
#include "Sound.h"
#include <QApplication>
#include <QKeyEvent>
#include <QMenu>
#include <QMouseEvent>
namespace Cevo {
namespace Term {
namespace {
QKeySequence keyOf(const QKeyEvent *event)
{
return QKeySequence(event->modifiers() | event->key());
}
} // namespace
bool MainScreen::isPanelPixel(int x, int y) const
{
return y >= TopBarHeight + m_mapHeight || (y >= height() - PanelHeight && (x < m_xMidPanel || x >= m_xRightPanel));
}
void MainScreen::mousePressEvent(QMouseEvent *event)
{
if (!m_idle)
return;
const QPoint pos = event->position().toPoint();
const int x = pos.x();
const int y = pos.y();
if (x < 40 && y < 40) {
if (gameMode != cMovie)
showPopup(PopupKind::Game, mapToGlobal(QPoint(0, TopBarHeight - 1)));
} else if (isPanelPixel(x, y)) {
panelMouseDown(event->button(), event->modifiers(), QPoint(x, y - (height() - PanelHeight)));
} else if (y >= TopBarHeight && x >= m_mapOffset && x < m_mapOffset + m_mapWidth) {
mapMouseDown(event->button(), event->modifiers(), QPoint(x - m_mapOffset, y - TopBarHeight));
}
}
void MainScreen::mouseMoveEvent(QMouseEvent *event)
{
if (!m_idle)
return;
const QPoint pos = event->position().toPoint();
if (isPanelPixel(pos.x(), pos.y()))
panelMouseMove(event->buttons(), QPoint(pos.x(), pos.y() - (height() - PanelHeight)));
else if (pos.y() >= TopBarHeight && pos.x() >= m_mapOffset && pos.x() < m_mapOffset + m_mapWidth)
mapMouseMove(event->buttons(), event->modifiers(), QPoint(pos.x() - m_mapOffset, pos.y() - TopBarHeight));
}
void MainScreen::mouseReleaseEvent(QMouseEvent *)
{
if (m_idle)
panelMouseUp();
}
void MainScreen::panelMouseMove(Qt::MouseButtons buttons, QPoint pos)
{
const int lx = ClientTools::g.lx;
const int ly = ClientTools::g.ly;
const int xxt = m_mainMap->xxt;
const int yyt = m_mainMap->yyt;
if (!(m_tracking && (buttons & Qt::LeftButton))) {
m_tracking = false;
return;
}
const int x = pos.x();
const int y = pos.y();
if (x >= m_xMini + 2 && y >= m_yMini + 2 && x < m_xMini + 2 + 2 * lx && y < m_yMini + 2 + ly) {
const int xCentre = (m_xwMini + (x - m_xMini - 2) / 2 + lx / 2 + m_mapWidth / (xxt * 4)) % lx;
const int yCentre = y - m_yMini - 2;
m_xw = (xCentre - m_mapWidth / (xxt * 4) + lx) % lx;
if (m_ywmax <= 0) {
m_yw = m_ywcenter;
} else {
m_yw = (yCentre - m_mapHeight / (yyt * 2) + 1) & ~1;
if (m_yw < 0)
m_yw = 0;
else if (m_yw > m_ywmax)
m_yw = m_ywmax;
}
// the mini map with the frame around the view being dragged
bitBltBitmap(m_panel, m_xMini + 2, m_yMini + 2, lx * 2, ly, m_miniMap->bitmap, 0, 0);
Dpi::Canvas &canvas = m_panel.canvas();
if (m_ywmax <= 0)
frame(canvas, x - m_mapWidth / (xxt * 2), m_yMini + 2, x + m_mapWidth / (xxt * 2) - 1, m_yMini + 2 + ly - 1,
MainTexture->colorMark, MainTexture->colorMark);
else
frame(canvas, x - m_mapWidth / (xxt * 2), m_yMini + 2 + m_yw, x + m_mapWidth / (xxt * 2) - 1,
m_yMini + 2 + m_yw + m_mapHeight / yyt - 2, MainTexture->colorMark, MainTexture->colorMark);
canvas.end();
mainOffscreenPaint();
invalidateMiniMap();
updateNow();
}
}
void MainScreen::panelMouseUp()
{
if (m_tracking) {
m_tracking = false;
m_xwMini = m_xw;
m_ywMini = m_yw;
miniMapPaint();
panelPaint();
}
}
void MainScreen::mapMouseMove(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, QPoint pos)
{
m_mouseX = pos.x();
m_mouseY = pos.y();
if (clientMode == cEditMap && (buttons & Qt::LeftButton) && !m_tracking) {
const int mouseLoc = locationOfScreenPixel(pos.x(), pos.y());
if (mouseLoc != m_brushLoc)
mapMouseDown(Qt::LeftButton, modifiers, pos);
}
}
void MainScreen::panelMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos)
{
using ClientTools::me;
using ClientTools::myMap;
using ClientTools::myRO;
using ClientTools::myUn;
const int lx = ClientTools::g.lx;
const int ly = ClientTools::g.ly;
const int x = pos.x();
const int y = pos.y();
if (gameMode == cMovie || button != Qt::LeftButton)
return;
const bool shift = modifiers & Qt::ShiftModifier;
if (x >= m_xMini + 2 && y >= m_yMini + 2 && x < m_xMini + 2 + 2 * lx && y < m_yMini + 2 + ly) {
if (shift) {
const int xMouse = (m_xwMini + (x - (m_xMini + 2) + m_mapWidth / (m_mainMap->xxt * 2) + lx) / 2) % lx;
const int mouseLoc = xMouse + lx * (y - (m_yMini + 2));
if ((myMap[mouseLoc] & fTerrain) != static_cast<std::uint32_t>(fUNKNOWN)) {
const int p1 = (*myRO->Territory)[mouseLoc];
if (p1 == me || (p1 >= 0 && myRO->Treaty[p1] >= trNone))
natStatDlg().showNewContent(WindowMode::Persistent, p1);
}
} else {
if (m_cityDlg && m_cityDlg->isVisible())
m_cityDlg->close();
if (m_unitStatDlg && m_unitStatDlg->isVisible())
m_unitStatDlg->close();
m_tracking = true;
panelMouseMove(Qt::LeftButton, pos);
}
} else if (clientMode != cEditMap && x >= width() - XPalace && y >= YPalace && x < width() - XPalace + xSizeBig
&& y < YPalace + ySizeBig) {
showPopup(PopupKind::Stat,
mapToGlobal(QPoint(width() - XPalace + 6, height() - PanelHeight + YPalace + ySizeBig + 3)));
} else if (x >= m_xTroop + 1 && y >= YTroop + 1 && x < m_xTroop + m_trRow * m_trPitch && y <= YTroop + 55) {
const int i = (x - m_xTroop - 1) / m_trPitch;
const int selected = m_trix[static_cast<std::size_t>(i)];
if (selected < 0)
return;
if (clientMode == cEditMap) {
m_brushType = static_cast<std::uint32_t>(selected);
panelPaint();
} else if (m_troopLoc >= 0) {
if ((myMap[m_troopLoc] & fOwned) != 0) {
if (shift) {
unitStatDlg().showNewContentOwnModel(WindowMode::Persistent, myUn[selected].mix);
} else if (!supervising && clientMode < scContact && x - m_xTroop - 1 - i * m_trPitch >= 60 - 20
&& y >= YTroop + 35
&& (myUn[selected].Job > jNone
|| (myUn[selected].Status & (IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usGoto)) != 0)) {
// wake up
myUn[selected].Status = (myUn[selected].Status
& (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto
- IsoEngine::usEnhance))
| usWaiting;
if (myUn[selected].Job > jNone)
ClientTools::server(sStartJob + (jNone << 4), me, selected, nullptr);
if (IsoEngine::unFocus < 0 && !(m_cityDlg && m_cityDlg->isVisible())) {
setUnFocus(selected);
setTroopLoc(myUn[selected].Loc);
focusOnLoc(m_troopLoc, flRepaintPanel);
} else {
if (m_cityDlg && m_cityDlg->isVisible() && m_cityDlg->restoreUnFocus < 0)
m_cityDlg->restoreUnFocus = selected;
panelPaint();
}
} else if (clientMode < scContact) {
if (supervising) {
unitStatDlg().showNewContentOwnUnit(WindowMode::Persistent, selected);
} else if (m_cityDlg && m_cityDlg->isVisible()) {
m_cityDlg->closeAction = CityScreen::CityCloseAction::None;
m_cityDlg->close();
ClientTools::sumCities(taxSum, scienceSum);
setUnFocus(selected);
} else {
IsoEngine::destinationMarkOn = false;
paintDestination();
IsoEngine::unFocus = selected;
unStartLoc = m_troopLoc;
m_blinkTime = 0;
IsoEngine::blinkOn = false;
paintLoc(m_troopLoc);
}
if (IsoEngine::unFocus >= 0) {
m_unitInfoBtn->setVisible(true);
m_unitBtn->setVisible(true);
m_turnComplete = false;
m_eot->setButtonIndex(eotGray);
}
checkTerrainBtnVisible();
panelPaint();
}
} else if (ClientTools::server(sGetUnits, me, m_troopLoc, &m_trCnt) >= rExecuted) {
if (shift)
unitStatDlg().showNewContentEnemyModel(WindowMode::Persistent,
(*myRO->EnemyUn)[myRO->nEnemyUn + selected].emix); // model info
else
unitStatDlg().showNewContentEnemyUnit(WindowMode::Persistent, myRO->nEnemyUn + selected); // unit info
}
}
}
}
void MainScreen::mapMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos)
{
using ClientTools::me;
using ClientTools::myMap;
using ClientTools::myModel;
using ClientTools::myRO;
using ClientTools::myUn;
using ClientTools::server;
const int lx = ClientTools::g.lx;
const int ly = ClientTools::g.ly;
const bool shift = modifiers & Qt::ShiftModifier;
const bool ctrl = modifiers & Qt::ControlModifier;
if (gameMode == cMovie)
return;
if (m_cityDlg && m_cityDlg->isVisible())
m_cityDlg->close();
if (m_unitStatDlg && m_unitStatDlg->isVisible())
m_unitStatDlg->close();
const int mouseLoc = locationOfScreenPixel(pos.x(), pos.y());
if (mouseLoc < 0 || mouseLoc >= lx * ly)
return;
if (button == Qt::LeftButton && !shift) {
bool doCenter = true;
if (clientMode == cEditMap) {
doCenter = false;
TEditTileData editTileData;
editTileData.Loc = mouseLoc;
const std::uint32_t tile = myMap[mouseLoc];
const std::uint32_t brush = m_brushType;
std::uint32_t newTile;
if (ctrl) { // toggle special resource
const std::uint32_t special = (((tile >> 5) & 3) + 1);
switch (tile & fTerrain) {
case fOcean: newTile = tile; break;
case fGrass:
case fArctic: newTile = (tile & ~static_cast<std::uint32_t>(fSpecial)) | ((special % 2) << 5); break;
default: newTile = (tile & ~static_cast<std::uint32_t>(fSpecial)) | ((special % 3) << 5); break;
}
} else if (brush <= static_cast<std::uint32_t>(fTerrain)) {
newTile = (tile & ~static_cast<std::uint32_t>(fTerrain)) | fSpecial | brush;
} else if ((brush & fDeadLands) != 0) {
if ((tile & (fDeadLands | fModern)) == (brush & (fDeadLands | fModern)))
newTile = tile & ~static_cast<std::uint32_t>(fDeadLands | fModern);
else
newTile = (tile & ~static_cast<std::uint32_t>(fDeadLands | fModern)) | brush;
} else if ((brush & fTerImp) != 0) {
if ((tile & fTerImp) == brush)
newTile = tile & ~static_cast<std::uint32_t>(fTerImp);
else
newTile = (tile & ~static_cast<std::uint32_t>(fTerImp)) | brush;
} else if ((brush & (fPrefStartPos | fStartPos)) != 0) {
if ((tile & (fPrefStartPos | fStartPos)) == (brush & (fPrefStartPos | fStartPos)))
newTile = tile & ~static_cast<std::uint32_t>(fPrefStartPos | fStartPos);
else
newTile = (tile & ~static_cast<std::uint32_t>(fPrefStartPos | fStartPos)) | brush;
} else {
newTile = tile ^ brush;
}
editTileData.NewTile = static_cast<std::int32_t>(newTile);
server(sEditTile, me, 0, &editTileData);
m_edited = true;
m_brushLoc = mouseLoc;
paintLoc(mouseLoc, 2);
miniMapPaint();
copyMiniToPanel();
m_panel.canvas().end();
invalidateMiniMap();
} else if ((myMap[mouseLoc] & fCity) != 0) { // city clicked
if ((myMap[mouseLoc] & (fOwned | fSpiedOut)) != 0) {
zoomToCity(mouseLoc);
doCenter = false;
} else {
unitStatDlg().showNewContentEnemyCity(WindowMode::Persistent, mouseLoc);
doCenter = false;
}
} else if ((myMap[mouseLoc] & fUnit) != 0) { // unit clicked
if ((myMap[mouseLoc] & fOwned) != 0) {
doCenter = false;
if (!supervising && clientMode < scContact) { // not in negotiation mode
int uix;
if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Loc == mouseLoc) { // rotate
uix = (IsoEngine::unFocus + 1) % myRO->nUn;
int i = myRO->nUn - 1;
while (i > 0) {
if (myUn[uix].Loc == mouseLoc && myUn[uix].Job == jNone
&& (myUn[uix].Status & (IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usEnhance | usWaiting))
== usWaiting)
break;
--i;
uix = (uix + 1) % myRO->nUn;
}
if (i == 0)
uix = IsoEngine::unFocus;
} else {
server(sGetDefender, me, mouseLoc, &uix);
}
if (uix != IsoEngine::unFocus)
setUnFocus(uix);
m_turnComplete = false;
m_eot->setButtonIndex(eotGray);
}
setTroopLoc(mouseLoc);
panelPaint();
} else if ((myMap[mouseLoc] & fSpiedOut) != 0 && !ctrl) {
doCenter = false;
setTroopLoc(mouseLoc);
panelPaint();
} else {
doCenter = false;
unitStatDlg().showNewContentEnemyLoc(WindowMode::Persistent, mouseLoc);
}
}
if (doCenter) {
centre(mouseLoc);
paintAllMaps();
}
} else if (clientMode != cEditMap && button == Qt::RightButton && !shift) {
if (supervising) {
m_editLoc = mouseLoc;
server(sGetModels, me, 0, nullptr);
QMenu *createUnit = createUnitMenu();
int createLoc = mouseLoc;
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & myRO->Alive) == 0)
continue;
QMenu *playerMenu = createUnit->addMenu(Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(QStringLiteral("SHORTNAME")));
for (int emix = myRO->nEnemyModel - 1; emix >= 0; --emix) {
const TModelInfo &model = (*myRO->EnemyModel)[emix];
if (model.Owner == p1
&& server(sCreateUnit - sExecute + (p1 << 4), me, model.mix, &createLoc) >= rExecuted) {
if (!Tribes::tribe[static_cast<std::size_t>(p1)]->modelPictureAt(model.mix).hGr)
initEnemyModel(emix);
QAction *action = playerMenu->addAction(
Tribes::tribe[static_cast<std::size_t>(p1)]->modelNameAt(model.mix));
const int mix = model.mix;
connect(action, &QAction::triggered, this, [this, p1, mix] {
int loc = m_editLoc;
if (ClientTools::server(sCreateUnit + (p1 << 4), ClientTools::me, mix, &loc) >= rExecuted)
paintLoc(m_editLoc);
});
}
}
playerMenu->menuAction()->setVisible(!playerMenu->isEmpty());
}
showPopup(PopupKind::Edit, mapToGlobal(QPoint(pos.x() + m_mapOffset, pos.y() + TopBarHeight)));
} else if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Loc != mouseLoc) {
TUn &un = myUn[IsoEngine::unFocus];
const int dx = ((mouseLoc % lx * 2 + ((mouseLoc / lx) & 1)) - (un.Loc % lx * 2 + ((un.Loc / lx) & 1)) + 3 * lx)
% (2 * lx)
- lx;
const int dy = mouseLoc / lx - un.Loc / lx;
TMoveAdviceData moveAdviceData;
if (std::abs(dx) + std::abs(dy) < 3) {
IsoEngine::destinationMarkOn = false;
paintDestination();
un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance))
| usWaiting;
moveUnit(dx, dy, muAutoNext); // simple move
} else if (ClientTools::getMoveAdvice(IsoEngine::unFocus, mouseLoc, moveAdviceData) >= rExecuted) {
if ((myMap[mouseLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit)) {
// check for suicide mission before movement
Battle::BattleDlg &battle = battleDlg();
battle.forecast.pAtt = me;
battle.forecast.mixAtt = un.mix;
battle.forecast.HealthAtt = un.Health;
battle.forecast.ExpAtt = un.Exp;
battle.forecast.FlagsAtt = static_cast<std::int32_t>(un.Flags);
battle.forecast.Movement = un.Movement;
if (server(sGetBattleForecastEx, me, mouseLoc, &battle.forecast) >= rExecuted
&& battle.forecast.EndHealthAtt <= 0) {
battle.uix = IsoEngine::unFocus;
battle.toLoc = mouseLoc;
battle.isSuicideQuery = true;
if (battle.showModal() != Dpi::ModalResult::Ok)
return;
}
}
IsoEngine::destinationMarkOn = false;
paintDestination();
un.Status = (un.Status & ~(IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usEnhance)) | usWaiting;
moveToLoc(mouseLoc, false); // goto
}
}
} else if (button == Qt::MiddleButton && IsoEngine::unFocus >= 0
&& (myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSettler
|| myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSlaves)) {
IsoEngine::destinationMarkOn = false;
paintDestination();
myUn[IsoEngine::unFocus].Status = (myUn[IsoEngine::unFocus].Status
& (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto))
| IsoEngine::usEnhance;
const int uix = IsoEngine::unFocus;
if (mouseLoc != myUn[uix].Loc)
moveToLoc(mouseLoc, true); // goto
if (IsoEngine::unFocus == uix && myUn[uix].Loc == mouseLoc)
triggerMenu(MenuCommand::Enhance);
} else if (button == Qt::LeftButton && shift && (myMap[mouseLoc] & fTerrain) != static_cast<std::uint32_t>(fUNKNOWN)) {
helpOnTerrain(mouseLoc, WindowMode::Persistent);
} else if (clientMode <= cContinue && button == Qt::RightButton && shift && IsoEngine::unFocus >= 0
&& (myMap[mouseLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit)) { // battle forecast
TUn &un = myUn[IsoEngine::unFocus];
Battle::BattleDlg &battle = battleDlg();
battle.forecast.pAtt = me;
battle.forecast.mixAtt = un.mix;
battle.forecast.HealthAtt = un.Health;
battle.forecast.ExpAtt = un.Exp;
battle.forecast.FlagsAtt = static_cast<std::int32_t>(un.Flags);
battle.forecast.Movement = un.Movement;
if (server(sGetBattleForecastEx, me, mouseLoc, &battle.forecast) >= rExecuted) {
battle.uix = IsoEngine::unFocus;
battle.toLoc = mouseLoc;
const QPoint global = mapToGlobal(QPoint(pos.x() + m_mapOffset, pos.y() + TopBarHeight));
const QRect desktop = Dpi::Screen::primaryMonitor().boundsRect();
int left = global.x() - battle.width() / 2;
left = std::clamp(left, desktop.left(), std::max(desktop.left(), desktop.right() - battle.width()));
int top = global.y() - battle.height() / 2;
top = std::clamp(top, desktop.top(), std::max(desktop.top(), desktop.bottom() - battle.height()));
battle.move(left, top);
battle.isSuicideQuery = false;
battle.show();
}
}
Q_UNUSED(m_dragStartLoc);
}
void MainScreen::mapButtonClicked(ButtonC *button)
{
const int bit = button->property("tag").toInt() >> 8;
mapOptionChecked ^= 1u << bit;
setMapOptions();
button->setButtonIndex(static_cast<int>((mapOptionChecked >> bit) & 1) + 2);
if (button == m_mapBtn0) { // update mini map only
miniMapPaint();
panelPaint();
} else { // update main map
m_mapValid = false;
paintAllMaps();
}
}
void MainScreen::mapOptionButtonChanged(ButtonC *button, int option)
{
if (button->down()) {
mapOptionChecked |= 1u << option;
button->setToolTip(QString());
} else {
mapOptionChecked &= ~(1u << option);
button->setToolTip(phrases.lookup(QStringLiteral("CONTROLS"), (button->property("tag").toInt() & 0xFF) - 1));
}
setMapOptions();
m_mapValid = false;
paintAllMaps();
}
void MainScreen::panelButtonClicked(ButtonB *button)
{
if (IsoEngine::unFocus < 0)
return;
showPopup(button == m_unitBtn ? PopupKind::Unit : PopupKind::Terrain, mapToGlobal(button->pos()));
}
void MainScreen::wireControls()
{
m_unitBtn->onClick = [this] { panelButtonClicked(m_unitBtn); };
m_terrainBtn->onClick = [this] { panelButtonClicked(m_terrainBtn); };
m_unitInfoBtn->onClick = [this] {
if (IsoEngine::unFocus >= 0)
unitStatDlg().showNewContentOwnModel(WindowMode::Persistent, ClientTools::myUn[IsoEngine::unFocus].mix);
};
for (ButtonC *button : { m_mapBtn0, m_mapBtn1, m_mapBtn5 })
button->onClick = [this, button] { mapButtonClicked(button); };
m_mapBtn4->onDownChanged = [this] { mapOptionButtonChanged(m_mapBtn4, ClientTools::moGreatWall); };
m_mapBtn6->onDownChanged = [this] { mapOptionButtonChanged(m_mapBtn6, ClientTools::moBareTerrain); };
for (ButtonB *button : m_movieSpeedBtn) {
button->onClick = [this, button] {
m_movieSpeed = button->property("tag").toInt() >> 8;
checkMovieSpeedBtnState();
};
}
m_eot->onClick = [this] {
if (gameMode == cMovie) {
messgExDlg().cancelMovie();
ClientTools::server(sBreak, ClientTools::me, 0, nullptr);
} else if (clientMode < 0) {
m_skipped = true;
} else if (clientMode >= scContact) {
negoDlg().showNewContent(WindowMode::Persistent);
} else if (m_jump[static_cast<std::size_t>(m_pTurn)] > 0) {
m_jump[static_cast<std::size_t>(m_pTurn)] = 0;
m_startRunning = false;
} else {
endTurn();
}
};
}
void MainScreen::keyReleaseEvent(QKeyEvent *event)
{
if (m_keyboardDisabled)
return;
if (m_idle && event->key() == Qt::Key_Menu) // the menu key calls the game menu
showPopup(PopupKind::Game, mapToGlobal(QPoint(0, TopBarHeight - 1)));
}
void MainScreen::keyPressEvent(QKeyEvent *event)
{
using namespace KeyBindings;
using ClientTools::myUn;
if (m_keyboardDisabled)
return;
const QKeySequence key = keyOf(event);
if (bFullScreen->test(key))
setFullScreen(!fullScreen);
if (gameMode == cMovie) {
if (bScienceStat->test(key))
menuClickChecked(PopupKind::Stat, MenuCommand::ScienceStat);
else if (bDiagram->test(key))
menuClickChecked(PopupKind::Stat, MenuCommand::Diagram);
else if (bWonders->test(key))
menuClickChecked(PopupKind::Stat, MenuCommand::Wonders);
else if (bShips->test(key))
menuClickChecked(PopupKind::Stat, MenuCommand::Ships);
return;
}
if (!m_idle)
return;
// map move
const auto moveMap = [this](int x, int y) {
const int speed = ClientTools::hasSaveOption(optionChecked, ClientTools::soScrollFast) ? 2 : 1;
if (x != 0 || y != 0)
scroll(x * speed, y * speed);
};
if (bMapMoveLeftDown->test(key)) moveMap(-1, 1);
else if (bMapMoveDown->test(key)) moveMap(0, 2);
else if (bMapMoveRightDown->test(key)) moveMap(1, 1);
else if (bMapMoveLeft->test(key)) moveMap(-2, 0);
else if (bMapMoveRight->test(key)) moveMap(2, 0);
else if (bMapMoveLeftUp->test(key)) moveMap(-1, -1);
else if (bMapMoveUp->test(key)) moveMap(0, -2);
else if (bMapMoveRightUp->test(key)) moveMap(1, -1);
if (clientMode == cEditMap) {
if (bResign->test(key)) triggerMenu(MenuCommand::Resign);
else if (bRandomMap->test(key)) triggerMenu(MenuCommand::RandomMap);
else if (bFillMap->test(key)) triggerMenu(MenuCommand::FillMap);
else if (bHelp->test(key)) triggerMenu(MenuCommand::Help);
return;
}
if (bEndTurn->test(key)) endTurn();
else if (bHelp->test(key)) triggerMenu(MenuCommand::Help);
else if (bUnitStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::UnitStat);
else if (bCityStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::CityStat);
else if (bScienceStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::ScienceStat);
else if (bEUnitStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::EUnitStat);
else if (bDiagram->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Diagram);
else if (bWonders->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Wonders);
else if (bShips->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Ships);
else if (bNations->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Nations);
else if (bEmpire->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Empire);
else if (bSetDebugMap0->test(key)) setDebugMap(-1);
else if (bSetDebugMap1->test(key)) setDebugMap(1);
else if (bSetDebugMap2->test(key)) setDebugMap(2);
else if (bSetDebugMap3->test(key)) setDebugMap(3);
else if (bSetDebugMap4->test(key)) setDebugMap(4);
else if (bSetDebugMap5->test(key)) setDebugMap(5);
else if (bSetDebugMap6->test(key)) setDebugMap(6);
else if (bSetDebugMap7->test(key)) setDebugMap(7);
else if (bSetDebugMap8->test(key)) setDebugMap(8);
else if (bSetDebugMap9->test(key)) setDebugMap(9);
else if (bJump->test(key)) triggerMenu(MenuCommand::Jump);
else if (bLocCodes->test(key)) triggerMenu(MenuCommand::LocCodes);
else if (bLogDlg->test(key)) {
if (logDlg().isVisible())
logDlg().close();
else
logDlg().show();
} else if (bNames->test(key)) triggerMenu(MenuCommand::Names);
else if (bResign->test(key)) menuClickChecked(PopupKind::Game, MenuCommand::Resign);
else if (bRun->test(key)) triggerMenu(MenuCommand::Run);
else if (bTestMapRepaint->test(key)) { // test map repaint time
QElapsedTimer timer;
timer.start();
m_mapValid = false;
mainOffscreenPaint();
simpleMessage(QStringLiteral("Map repaint time: %1 ms").arg(timer.nsecsElapsed() / 1e6, 0, 'f', 3));
} else if (bSetViewpoint0->test(key)) setViewpoint(0);
else if (bSetViewpoint1->test(key)) setViewpoint(1);
else if (bSetViewpoint2->test(key)) setViewpoint(2);
else if (bSetViewpoint3->test(key)) setViewpoint(3);
else if (bSetViewpoint4->test(key)) setViewpoint(4);
else if (bSetViewpoint5->test(key)) setViewpoint(5);
else if (bSetViewpoint6->test(key)) setViewpoint(6);
else if (bSetViewpoint7->test(key)) setViewpoint(7);
else if (bSetViewpoint8->test(key)) setViewpoint(8);
else if (bSetViewpoint9->test(key)) setViewpoint(9);
else if (bMapBtn0->test(key)) mapButtonClicked(m_mapBtn0);
else if (bMapBtn1->test(key)) mapButtonClicked(m_mapBtn1);
else if (bMapBtn4->test(key)) mapButtonClicked(m_mapBtn4);
else if (bMapBtn5->test(key)) mapButtonClicked(m_mapBtn5);
else if (bMapBtn6->test(key)) mapButtonClicked(m_mapBtn6);
else if (bTechTree->test(key)) triggerMenu(MenuCommand::TechTree);
else if (bWait->test(key)) triggerMenu(MenuCommand::Wait);
if (IsoEngine::unFocus >= 0) {
const auto doMoveUnit = [this](int x, int y) {
IsoEngine::destinationMarkOn = false;
paintDestination();
TUn &un = ClientTools::myUn[IsoEngine::unFocus];
un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance))
| usWaiting;
moveUnit(x, y, muAutoNext);
};
using Cmd = MenuCommand;
const auto test = [](int job) {
return ClientTools::jobTest(IsoEngine::unFocus, job, 1ull << eTreaty);
};
if (bDisbandUnit->test(key)) triggerMenu(Cmd::Disband);
else if (bFortify->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Fort);
else if (bCenterUnit->test(key)) triggerMenu(Cmd::Centre);
else if (bStay->test(key)) triggerMenu(Cmd::Stay);
else if (bNoOrders->test(key)) triggerMenu(Cmd::NoOrders);
else if (bPrevUnit->test(key)) triggerMenu(Cmd::PrevUnit);
else if (bNextUnit->test(key)) triggerMenu(Cmd::NextUnit);
else if (bCancel->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Cancel);
else if (bPillage->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Pillage);
else if (bSelectTransport->test(key)) menuClickChecked(PopupKind::Unit, Cmd::SelectTransport);
else if (bAirBase->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::AirBase);
else if (bBuildCity->test(key)) menuClickChecked(PopupKind::Unit, Cmd::City);
else if (bEnhance->test(key)) {
initPopup(PopupKind::Terrain);
if (menuItemUsable(Cmd::Enhance))
triggerMenu(Cmd::Enhance);
else
triggerMenu(Cmd::EnhanceDef);
} else if (bGoOn->test(key)) menuClickChecked(PopupKind::Unit, Cmd::GoOn);
else if (bHome->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Home);
else if (bFarmClearIrrigation->test(key)) {
if (test(jFarm)) triggerMenu(Cmd::Farm);
else if (test(jClear)) triggerMenu(Cmd::Clear);
else menuClickChecked(PopupKind::Terrain, Cmd::Irrigation);
} else if (bLoad->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Load);
else if (bAfforestMine->test(key)) {
if (test(jAfforest)) triggerMenu(Cmd::Afforest);
else menuClickChecked(PopupKind::Terrain, Cmd::Mine);
} else if (bCanal->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Canal);
else if (bTrans->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Trans);
else if (bPollution->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Pollution);
else if (bRailRoad->test(key)) {
if (test(jRR)) triggerMenu(Cmd::RailRoad);
else menuClickChecked(PopupKind::Terrain, Cmd::Road);
} else if (bUnload->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Unload);
else if (bRecover->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Recover);
else if (bUtilize->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Utilize);
// unit move
else if (bUnitMoveLeftDown->test(key)) doMoveUnit(-1, 1);
else if (bUnitMoveDown->test(key)) doMoveUnit(0, 2);
else if (bUnitMoveRightDown->test(key)) doMoveUnit(1, 1);
else if (bUnitMoveLeft->test(key)) doMoveUnit(-2, 0);
else if (bUnitMoveRight->test(key)) doMoveUnit(2, 0);
else if (bUnitMoveLeftUp->test(key)) doMoveUnit(-1, -1);
else if (bUnitMoveUp->test(key)) doMoveUnit(0, -2);
else if (bUnitMoveRightUp->test(key)) doMoveUnit(1, -1);
}
Q_UNUSED(myUn);
}
void MainScreen::setFullScreen(bool active)
{
fullScreen = active;
if (active) {
if (!m_formFullScreen && !isFullScreen())
m_restoredBounds = geometry();
m_formFullScreen = true;
showFullScreen();
} else {
m_formFullScreen = false;
showNormal();
if (m_restoredBounds.isValid())
setGeometry(m_restoredBounds);
}
}
} // namespace Term
} // namespace Cevo
File diff suppressed because it is too large. Load diff
+83
View File
@@ -0,0 +1,83 @@
// 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.
#pragma once
// Private definition of TMainScreen's popup menus (see Term.MainScreen.Menus.cpp).
#include "Term.MainScreen.h"
#include <QActionGroup>
#include <QMenu>
#include <array>
#include <map>
#include <vector>
namespace Cevo {
namespace Term {
struct MainScreen::Menus {
QMenu *game = nullptr;
QMenu *unit = nullptr;
QMenu *stat = nullptr;
QMenu *terrain = nullptr;
QMenu *edit = nullptr;
QMenu *options = nullptr;
QMenu *ownMovement = nullptr;
QMenu *allyMovement = nullptr;
QMenu *enemyMovement = nullptr;
QMenu *rep = nullptr;
QMenu *scrolling = nullptr;
QMenu *tileSize = nullptr;
QMenu *sound = nullptr;
QMenu *music = nullptr;
QMenu *test = nullptr;
QMenu *manip = nullptr;
QMenu *macro = nullptr;
QMenu *viewpoint = nullptr;
QMenu *debugMap = nullptr;
QMenu *createUnit = nullptr;
QAction *waitTurn = nullptr;
QAction *repList = nullptr;
QAction *repScreens = nullptr;
QAction *locCodes = nullptr;
std::map<MenuCommand, QAction *> action;
std::array<QAction *, nTestFlags> manipItem{};
std::array<QAction *, 16> repItem{};
QActionGroup *tileGroup = nullptr;
QActionGroup *soundGroup = nullptr;
QActionGroup *musicGroup = nullptr;
QAction *names = nullptr;
std::vector<std::pair<QAction *, ClientTools::SaveOption>> optionItems;
QAction *act(MenuCommand command) const { return action.at(command); }
};
} // namespace Term
} // namespace Cevo
+670
View File
@@ -0,0 +1,670 @@
// TMainScreen.MoveUnit, MoveToLoc and MoveOnScreen (Term.pas): moving the
// focused unit, path finding and the unit move animation.
//
// The animation draws the moving unit into m_moveTile (a copy of the map
// rectangle it travels through), which paintEvent() puts on top of the map
// layer; the original blitted the same buffer directly onto the screen.
#include "Term.MainScreen.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Global.h"
#include "Messg.h"
#include "Sound.h"
#include <QApplication>
#include <QElapsedTimer>
#include <QThread>
#include <cstdlib>
namespace Cevo {
namespace Term {
namespace {
constexpr int MoveTime = 300; // time for moving a unit, in ms
QString movementPhrase(int movement)
{
return movementToString(movement);
}
} // namespace
int MainScreen::moveUnit(int dx, int dy, int options)
{
using ClientTools::me;
using ClientTools::myCity;
using ClientTools::myMap;
using ClientTools::myModel;
using ClientTools::myRO;
using ClientTools::myUn;
using ClientTools::server;
const int lx = ClientTools::g.lx;
const int ly = ClientTools::g.ly;
int result = eInvalid;
const int unFocus0 = IsoEngine::unFocus;
const int fromLoc = myUn[IsoEngine::unFocus].Loc;
const int toLoc = ClientTools::dLoc(fromLoc, dx, dy);
if (toLoc < 0 || toLoc >= lx * ly)
return eInvalid;
if (myMap[toLoc] & fStealthUnit) {
soundMessage(phrases[QStringLiteral("ATTACKSTEALTH")], QString());
return result;
}
if (myMap[toLoc] & fHiddenUnit) {
soundMessage(phrases[QStringLiteral("ATTACKSUB")], QString());
return result;
}
int euix = -1;
if ((myMap[toLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit)) { // attack -- search enemy unit
const TUn &un = myUn[IsoEngine::unFocus];
if (myModel[un.mix].Attack == 0 && !(myModel[un.mix].Cap[mcBombs] > 0 && (un.Flags & unBombsLoaded) != 0)) {
soundMessage(phrases[QStringLiteral("NOATTACKER")], QString());
return result;
}
euix = myRO->nEnemyUn - 1;
while (euix >= 0 && (*myRO->EnemyUn)[euix].Loc != toLoc)
--euix;
}
const int dirCode = ((dx & 7) << 4) + ((dy & 7) << 7);
result = server(sMoveUnit - sExecute + dirCode, me, IsoEngine::unFocus, nullptr);
if (result < rExecuted && myUn[IsoEngine::unFocus].Job > jNone)
server(sStartJob + (jNone << 4), me, IsoEngine::unFocus, nullptr);
if (result < rExecuted && result != eNoTime_Move) {
const TUn &un = myUn[IsoEngine::unFocus];
switch (result) {
case eNoTime_Load:
if (myModel[un.mix].Domain == dAir)
soundMessage(phrases[QStringLiteral("NOTIMELOADAIR")], QStringLiteral("NOMOVE_TIME"));
else
soundMessage(formatPhrase(QStringLiteral("NOTIMELOADGROUND"), { movementPhrase(myModel[un.mix].Speed) }),
QStringLiteral("NOMOVE_TIME"));
break;
case eNoTime_Bombard:
soundMessage(phrases[QStringLiteral("NOTIMEBOMBARD")], QStringLiteral("NOMOVE_TIME"));
break;
case eNoTime_Expel:
soundMessage(phrases[QStringLiteral("NOTIMEEXPEL")], QStringLiteral("NOMOVE_TIME"));
break;
case eNoRoad:
soundMessage(phrases[QStringLiteral("NOROAD")], QStringLiteral("NOMOVE_DEFAULT"));
break;
case eNoNav:
soundMessage(phrases[QStringLiteral("NONAV")], QStringLiteral("NOMOVE_DEFAULT"));
break;
case eNoCapturer:
soundMessage(phrases[QStringLiteral("NOCAPTURER")], QStringLiteral("NOMOVE_DEFAULT"));
break;
case eNoBombarder:
soundMessage(phrases[QStringLiteral("NOBOMBARDER")], QStringLiteral("NOMOVE_DEFAULT"));
break;
case eZOC:
MessgEx::contextMessage(phrases[QStringLiteral("ZOC")], QStringLiteral("NOMOVE_ZOC"),
Help::LinkCategory::Text, helpDlg().textIndex(QStringLiteral("MOVEMENT")));
break;
case eTreaty:
if ((myMap[toLoc] & (fUnit | fOwned)) != static_cast<std::uint32_t>(fUnit)) // no enemy unit -- move
soundMessage(Tribes::tribe[static_cast<std::size_t>((*myRO->Territory)[toLoc])]->tPhrase(
QStringLiteral("PEACE_NOMOVE")),
QStringLiteral("NOMOVE_TREATY"));
else
soundMessage(Tribes::tribe[static_cast<std::size_t>((*myRO->EnemyUn)[euix].Owner)]->tPhrase(
QStringLiteral("PEACE_NOATTACK")),
QStringLiteral("NOMOVE_TREATY"));
break;
case eDomainMismatch:
if (myModel[un.mix].Domain < dSea && (myMap[toLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit | fOwned)) {
// false load attempt
bool toShip = false;
bool toTransport = false;
for (int uix = 0; uix < myRO->nUn; ++uix) {
if (myUn[uix].Loc == toLoc && myModel[myUn[uix].mix].Domain == dSea) {
toShip = true;
if (myModel[myUn[uix].mix].Cap[mcSeaTrans] > 0)
toTransport = true;
}
}
if (toTransport)
soundMessage(phrases[QStringLiteral("FULLTRANSPORT")], QStringLiteral("NOMOVE_DEFAULT"));
else if (toShip)
soundMessage(phrases[QStringLiteral("NOTRANSPORT")], QStringLiteral("NOMOVE_DEFAULT"));
else
Sound::play(QStringLiteral("NOMOVE_DOMAIN"));
} else {
Sound::play(QStringLiteral("NOMOVE_DOMAIN"));
}
break;
default:
Sound::play(QStringLiteral("NOMOVE_DEFAULT"));
break;
}
return result;
}
if ((result == eWon || result == eLost || result == eBloody) && myUn[IsoEngine::unFocus].Movement < 100
&& myModel[myUn[IsoEngine::unFocus].mix].Cap[mcWill] == 0) {
if (MessgEx::simpleQuery(MessageKind::YesNo,
formatPhrase(QStringLiteral("FASTATTACK"),
{ QString::number(myUn[IsoEngine::unFocus].Movement) }),
QStringLiteral("NOMOVE_TIME"))
!= Dpi::ModalResult::Ok)
return eInvalid;
updateNow(); // remove message box from screen
}
bool oldUnrest = false;
bool newUnrest = false;
if (result >= rExecuted && (result & rUnitRemoved) == 0
&& (myMap[toLoc] & (fUnit | fOwned)) != static_cast<std::uint32_t>(fUnit)) {
oldUnrest = ClientTools::unrestAtLoc(IsoEngine::unFocus, fromLoc);
newUnrest = ClientTools::unrestAtLoc(IsoEngine::unFocus, toLoc);
if (newUnrest > oldUnrest) {
QString queryItem;
int p1;
if (myRO->Government == gDemocracy) {
queryItem = QStringLiteral("UNREST_NOTOWN");
p1 = me;
} else {
queryItem = QStringLiteral("UNREST_FOREIGN");
p1 = (*myRO->Territory)[toLoc];
}
MessgEx::MessgExDlg &dlg = messgExDlg();
dlg.messageText = Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(queryItem).arg(
phrases.lookup(QStringLiteral("GOVERNMENT"), myRO->Government));
dlg.kind = MessageKind::YesNo;
dlg.iconKind = MessgEx::MessageIconKind::Imp;
dlg.iconIndex = imPalace;
if (dlg.showModal() != Dpi::ModalResult::Ok)
return eInvalid;
updateNow(); // remove message box from screen
}
}
if (result >= rExecuted && myModel[myUn[IsoEngine::unFocus].mix].Domain == dAir
&& (myUn[IsoEngine::unFocus].Status & usToldNoReturn) == 0) { // can plane return?
TPlaneReturnData planeReturnData;
planeReturnData.Fuel = myUn[IsoEngine::unFocus].Fuel;
if ((myMap[toLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit)
|| (myMap[toLoc] & (fCity | fOwned)) == static_cast<std::uint32_t>(fCity)) {
// attack/expel/bombard -> 100MP
planeReturnData.Loc = fromLoc;
planeReturnData.Movement = std::max(0, myUn[IsoEngine::unFocus].Movement - 100);
} else { // move
planeReturnData.Loc = toLoc;
planeReturnData.Movement = myUn[IsoEngine::unFocus].Movement - ((dx & 1) != 0 ? 100 : 150);
}
if (server(sGetPlaneReturn, me, IsoEngine::unFocus, &planeReturnData) == eNoWay) {
const QString queryItem = myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSpecial_Glider
? QStringLiteral("LOWFUEL_GLIDER")
: QStringLiteral("LOWFUEL");
if (MessgEx::simpleQuery(MessageKind::YesNo, phrases[queryItem], QStringLiteral("WARNING_LOWSUPPORT"))
!= Dpi::ModalResult::Ok)
return eInvalid;
updateNow(); // remove message box from screen
myUn[IsoEngine::unFocus].Status |= usToldNoReturn;
}
}
int mission = -1;
if (result == eMissionDone) {
modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::Mission);
updateNow(); // dialog still on screen
mission = modalSelectDlg().result;
if (mission < 0)
return result;
server(sSetSpyMission + (mission << 4), me, 0, nullptr);
}
bool cityCaptured = false;
bool needEcoUpdate = false;
bool needRepaintPanel = false;
bool isAttack = false;
if (result == eNoTime_Move) {
Sound::play(QStringLiteral("NOMOVE_TIME"));
} else {
IsoEngine::destinationMarkOn = false;
paintDestination();
if ((result & rUnitRemoved) != 0)
ClientTools::cityOptimizer_BeforeRemoveUnit(IsoEngine::unFocus);
isAttack = result == eBombarded
|| (result != eMissionDone && (myMap[toLoc] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit));
if (!isAttack) { // move
int cix = myRO->nCity - 1; // look for own city at dest location
while (cix >= 0 && myCity[cix].Loc != toLoc)
--cix;
if (result != eMissionDone && (myMap[toLoc] & fCity) != 0 && cix < 0)
cityCaptured = true;
result = server(sMoveUnit + dirCode, me, IsoEngine::unFocus, nullptr);
if (result == eHiddenUnit) {
Sound::play(QStringLiteral("NOMOVE_SUBMARINE"));
paintLoc(toLoc);
} else if (result == eStealthUnit) {
Sound::play(QStringLiteral("NOMOVE_STEALTH"));
paintLoc(toLoc);
} else if (result == eZOC_EnemySpotted) {
Sound::play(QStringLiteral("NOMOVE_ZOC"));
paintLoc(toLoc, 1);
} else if (result >= rExecuted) {
if ((result & rUnitRemoved) != 0) {
IsoEngine::unFocus = -1; // unit died
} else {
Q_ASSERT(IsoEngine::unFocus >= 0);
TUn &un = myUn[IsoEngine::unFocus];
un.Status &= ~(IsoEngine::usStay | IsoEngine::usRecover);
for (int uix = 0; uix < myRO->nUn; ++uix) {
if (myUn[uix].Master == IsoEngine::unFocus)
myUn[uix].Status &= ~usWaiting;
}
const bool democratic =
myRO->Government == gRepublic || myRO->Government == gDemocracy || myRO->Government == gFuture;
if (cityCaptured && democratic) {
// borders have moved, unrest might have changed in any city
ClientTools::cityOptimizer_BeginOfTurn();
needEcoUpdate = true;
} else {
if (oldUnrest != newUnrest) {
ClientTools::cityOptimizer_CityChange(un.Home);
for (int uix = 0; uix < myRO->nUn; ++uix) {
if (myUn[uix].Master == IsoEngine::unFocus)
ClientTools::cityOptimizer_CityChange(myUn[uix].Home);
}
needEcoUpdate = true;
}
if (myRO->Government == gDespotism && myModel[un.mix].Kind == mkSpecial_TownGuard) {
const auto reoptimizeCityAt = [&](int loc) {
int cixChanged = myRO->nCity - 1;
while (cixChanged >= 0 && myCity[cixChanged].Loc != loc)
--cixChanged;
Q_ASSERT(cixChanged >= 0);
if (cixChanged >= 0) {
ClientTools::cityOptimizer_CityChange(cixChanged);
needEcoUpdate = true;
}
};
// town guard moved out of / into a city in despotism -- reoptimize!
if ((myMap[fromLoc] & fCity) != 0)
reoptimizeCityAt(fromLoc);
if ((myMap[toLoc] & fCity) != 0 && !cityCaptured)
reoptimizeCityAt(toLoc);
}
}
}
} else {
Q_ASSERT(false);
}
setTroopLoc(toLoc);
} else { // enemy unit -- attack
int defender;
if (result == eBombarded)
defender = (*myRO->Territory)[toLoc];
else
defender = (*myRO->EnemyUn)[euix].Owner;
if ((options & muNoSuicideCheck) == 0 && (result & rUnitRemoved) != 0 && result != eMissionDone) {
// suicide query
Battle::BattleDlg &battle = battleDlg();
const TUn &un = myUn[IsoEngine::unFocus];
battle.forecast.pAtt = me;
battle.forecast.mixAtt = un.mix;
battle.forecast.HealthAtt = un.Health;
battle.forecast.ExpAtt = un.Exp;
battle.forecast.FlagsAtt = static_cast<std::int32_t>(un.Flags);
battle.forecast.Movement = un.Movement;
server(sGetBattleForecastEx, me, toLoc, &battle.forecast);
battle.uix = IsoEngine::unFocus;
battle.toLoc = toLoc;
battle.isSuicideQuery = true;
if (battle.showModal() != Dpi::ModalResult::Ok)
return result;
}
int cixChanged = -1;
if ((result & rUnitRemoved) != 0 && myRO->Government == gDespotism
&& myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSpecial_TownGuard && (myMap[fromLoc] & fCity) != 0) {
// town guard died in city in despotism -- reoptimize!
cixChanged = myRO->nCity - 1;
while (cixChanged >= 0 && myCity[cixChanged].Loc != fromLoc)
--cixChanged;
Q_ASSERT(cixChanged >= 0);
}
for (int i = 0; i < myRO->nEnemyModel; ++i)
lostArmy[static_cast<std::size_t>(i)] = (*myRO->EnemyModel)[i].Lost;
const std::uint32_t oldToTile = myMap[toLoc];
result = server(sMoveUnit + dirCode, me, IsoEngine::unFocus, nullptr);
nLostArmy = 0;
for (int i = 0; i < myRO->nEnemyModel; ++i) {
lostArmy[static_cast<std::size_t>(i)] = (*myRO->EnemyModel)[i].Lost - lostArmy[static_cast<std::size_t>(i)];
nLostArmy += lostArmy[static_cast<std::size_t>(i)];
}
if ((result & rUnitRemoved) != 0) {
IsoEngine::unFocus = -1;
setTroopLoc(fromLoc);
}
const bool democratic =
myRO->Government == gRepublic || myRO->Government == gDemocracy || myRO->Government == gFuture;
if ((oldToTile & ~myMap[toLoc] & fCity) != 0 && democratic) {
// city was destroyed, borders have moved, unrest might have changed in any city
ClientTools::cityOptimizer_BeginOfTurn();
needEcoUpdate = true;
} else {
if (cixChanged >= 0) {
ClientTools::cityOptimizer_CityChange(cixChanged);
needEcoUpdate = true;
}
if (result == eWon || result == eBloody || result == eExpelled) {
ClientTools::cityOptimizer_TileBecomesAvailable(toLoc);
needEcoUpdate = true;
}
}
if (nLostArmy > 1) {
MessgEx::MessgExDlg &dlg = messgExDlg();
dlg.kind = MessageKind::Ok;
dlg.iconKind = MessgEx::MessageIconKind::EnemyArmy;
dlg.messageText = Tribes::tribe[static_cast<std::size_t>(defender)]->tString(
phraseToQtFormat(phrases.lookup(QStringLiteral("ARMYLOST"),
(*myRO->EnemyModel)[(*myRO->EnemyUn)[euix].emix].Domain)));
dlg.showModal();
}
}
if ((result & rUnitRemoved) != 0) {
ClientTools::cityOptimizer_AfterRemoveUnit();
listDlg().removeUnit();
needEcoUpdate = true;
}
if (needEcoUpdate) {
updateViews(true);
updateNow();
}
}
if (result == eMissionDone) {
const int p1 = (*myRO->Territory)[toLoc];
switch (mission) {
case smStealMap:
m_mapValid = false;
paintAllMaps();
break;
case smStealCivilReport:
MessgEx::tribeMessage(p1, Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(QStringLiteral("DOSSIER_PREPARED")),
QString());
break;
case smStealMilReport:
listDlg().showNewContentMilReport(WindowMode::Persistent, p1);
break;
default:
break;
}
}
if (IsoEngine::unFocus >= 0)
checkToldNoReturn(IsoEngine::unFocus);
if (result >= rExecuted) {
if (cityCaptured && (myMap[toLoc] & fCity) == 0) { // city destroyed
for (int i = 0; i < nWonder; ++i) { // tell about destroyed wonders
if (myRO->Wonder[i].CityID == WonderDestroyed && myData->toldWonders[static_cast<std::size_t>(i)].CityID != WonderDestroyed) {
MessgEx::MessgExDlg &dlg = messgExDlg();
if (m_wondersDlg && m_wondersDlg->isVisible())
m_wondersDlg->smartUpdateContent(false);
dlg.openSound = QStringLiteral("WONDER_DESTROYED");
dlg.messageText = formatPhrase(QStringLiteral("WONDERDEST"),
{ phrases.lookup(QStringLiteral("IMPROVEMENTS"), i) });
dlg.kind = MessageKind::OkHelp;
dlg.helpKind = Help::LinkCategory::Imp;
dlg.helpNo = i;
dlg.iconKind = MessgEx::MessageIconKind::Imp;
dlg.iconIndex = i;
dlg.showModal();
std::memcpy(&myData->toldWonders[static_cast<std::size_t>(i)], &myRO->Wonder[i], sizeof(myRO->Wonder[i]));
}
}
}
if (cityCaptured && (myMap[toLoc] & fCity) != 0) { // city captured
listDlg().addCity();
for (int i = 0; i < nWonder; ++i) { // tell about capture of wonders
if (myCity[myRO->nCity - 1].Built[i] > 0) {
MessgEx::MessgExDlg &dlg = messgExDlg();
if (m_wondersDlg && m_wondersDlg->isVisible())
m_wondersDlg->smartUpdateContent(false);
dlg.openSound = QStringLiteral("WONDER_CAPTURED");
dlg.messageText = Tribes::tribe[static_cast<std::size_t>(me)]->tPhrase(QStringLiteral("WONDERCAPTOWN"))
.arg(phrases.lookup(QStringLiteral("IMPROVEMENTS"), i));
dlg.kind = MessageKind::OkHelp;
dlg.helpKind = Help::LinkCategory::Imp;
dlg.helpNo = i;
dlg.iconKind = MessgEx::MessageIconKind::Imp;
dlg.iconIndex = i;
dlg.showModal();
}
}
if ((myRO->Happened & phStealTech) != 0) { // Temple of Zeus -- choose advance to steal
modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::StealTech);
server(sStealTech, me, modalSelectDlg().result, nullptr);
}
tellNewModels();
int cix = myRO->nCity - 1;
while (cix >= 0 && myCity[cix].Loc != toLoc)
--cix;
Q_ASSERT(cix >= 0);
myCity[cix].Status = (myCity[cix].Status & ~csResourceWeightsMask) | (3 << 4);
// captured city, set to maximum growth
int newTiles = 1 << 13; // exploit central tile only
server(sSetCityTiles, me, cix, &newTiles);
} else {
needRepaintPanel = true;
}
}
tellNewContacts();
if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Master >= 0) {
TUn &master = myUn[myUn[IsoEngine::unFocus].Master];
if ((master.Status & IsoEngine::usStay) != 0) {
master.Status &= ~IsoEngine::usStay;
if (master.Movement >= 100 && (master.Status & (IsoEngine::usRecover | IsoEngine::usGoto)) == 0)
master.Status |= usWaiting;
}
}
if ((options & (muAutoNoWait | muAutoNext)) != 0) {
if (IsoEngine::unFocus >= 0
&& (result == eNoTime_Move || ClientTools::unitExhausted(IsoEngine::unFocus)
|| myUn[IsoEngine::unFocus].Master >= 0
|| (myModel[myUn[IsoEngine::unFocus].mix].Domain == dAir
&& ((myMap[myUn[IsoEngine::unFocus].Loc] & fCity) != 0
|| (myMap[myUn[IsoEngine::unFocus].Loc] & fTerImp) == static_cast<std::uint32_t>(tiBase))))) {
// aircrafts stop in cities
myUn[IsoEngine::unFocus].Status &= ~usWaiting;
if ((options & muAutoNext) != 0) {
if (cityCaptured && (myMap[toLoc] & fCity) != 0) {
IsoEngine::unFocus = -1;
paintLoc(toLoc); // don't show unit in city if not selected
} else {
nextUnit(unStartLoc, true);
}
}
} else if (IsoEngine::unFocus < 0 && (options & muAutoNext) != 0) {
nextUnit(unStartLoc, result != eMissionDone);
}
}
if (needRepaintPanel && IsoEngine::unFocus == unFocus0) {
if (isAttack) {
panelPaint();
} else {
Q_ASSERT(result != eMissionDone);
checkTerrainBtnVisible();
focusOnLoc(toLoc, flRepaintPanel | flImmUpdate);
}
}
if (result >= rExecuted && cityCaptured && (myMap[toLoc] & fCity) != 0)
zoomToCity(toLoc, IsoEngine::unFocus < 0, chCaptured); // show captured city
return result;
}
void MainScreen::moveToLoc(int loc, bool checkSuicide)
{
using ClientTools::myMap;
using ClientTools::myRO;
using ClientTools::myUn;
enum class StopReason { None, Arrived, Dead, NoTime, EnemySpotted, MoveError };
if (myUn[IsoEngine::unFocus].Job > jNone)
ClientTools::server(sStartJob + (jNone << 4), ClientTools::me, IsoEngine::unFocus, nullptr);
TMoveAdviceData moveAdviceData;
if (ClientTools::getMoveAdvice(IsoEngine::unFocus, loc, moveAdviceData) < rExecuted)
return;
const int uix = IsoEngine::unFocus;
StopReason stopReason = StopReason::None;
for (;;) {
for (int i = 0; i < moveAdviceData.nStep; ++i) {
int moveOptions = i == moveAdviceData.nStep - 1 ? muAutoNext : 0;
const int nextLoc = ClientTools::dLoc(myUn[uix].Loc, moveAdviceData.dx[i], moveAdviceData.dy[i]);
if (nextLoc == loc || (loc == maNextCity && (myMap[nextLoc] & fCity) != 0))
stopReason = StopReason::Arrived;
if (!checkSuicide && nextLoc == loc)
moveOptions |= muNoSuicideCheck;
const int moveResult = moveUnit(moveAdviceData.dx[i], moveAdviceData.dy[i], moveOptions);
if (moveResult < rExecuted)
stopReason = StopReason::MoveError;
else if ((moveResult & rUnitRemoved) != 0)
stopReason = StopReason::Dead;
else if (stopReason == StopReason::None && (moveResult & rEnemySpotted) != 0)
stopReason = StopReason::EnemySpotted;
if (stopReason != StopReason::None)
break;
}
if (stopReason == StopReason::None && (moveAdviceData.nStep < 25 || myRO->Wonder[woShinkansen].EffectiveOwner != ClientTools::me))
stopReason = StopReason::NoTime;
if (stopReason != StopReason::None)
break;
if (ClientTools::getMoveAdvice(IsoEngine::unFocus, loc, moveAdviceData) < rExecuted) {
Q_ASSERT(false);
break;
}
}
switch (stopReason) {
case StopReason::None:
Q_ASSERT(false);
break;
case StopReason::Arrived:
myUn[uix].Status &= 0xFFFF - IsoEngine::usGoto;
break;
case StopReason::Dead:
if (IsoEngine::unFocus < 0)
nextUnit(unStartLoc, false);
break;
default: // multi-turn goto
myUn[uix].Status = (myUn[uix].Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover)) | IsoEngine::usGoto
| ((loc == maNextCity ? 0x7FFF : loc) << 16);
paintLoc(myUn[uix].Loc);
if (stopReason == StopReason::NoTime && IsoEngine::unFocus == uix) {
myUn[uix].Status &= ~usWaiting;
nextUnit(unStartLoc, true);
}
break;
}
}
void MainScreen::moveOnScreen(const TShowMove &showMove, int step0, int step1, int nStep, bool restore)
{
const int lx = ClientTools::g.lx;
const int xxt = m_mainMap->xxt;
const int yyt = m_mainMap->yyt;
m_timer->stop();
TUnitInfo unitInfo{};
unitInfo.Owner = static_cast<std::uint8_t>(showMove.Owner);
unitInfo.mix = static_cast<std::int16_t>(showMove.mix);
unitInfo.Health = static_cast<std::int8_t>(showMove.Health);
unitInfo.Job = jNone;
unitInfo.Flags = static_cast<std::uint16_t>(showMove.Flags);
if (showMove.Owner != ClientTools::me)
unitInfo.emix = static_cast<std::int16_t>(showMove.emix);
const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy);
int xToLoc = toLoc % lx;
const int yToLoc = toLoc / lx;
const int xFromLoc = showMove.FromLoc % lx;
const int yFromLoc = showMove.FromLoc / lx;
if (xToLoc > xFromLoc + 2)
xToLoc -= lx;
else if (xToLoc < xFromLoc - 2)
xToLoc += lx;
int xw1 = m_xw + lx;
// ((xFromLoc-xw1)*2+yFromLoc and 1+1)*xxt+dx*xxt/2-MapWidth/2 -> min
while (std::abs(((xFromLoc - xw1 + lx) * 2 + (yFromLoc & 1) + 1) * xxt * 2 + showMove.dx * xxt - m_mapWidth)
< std::abs(((xFromLoc - xw1) * 2 + (yFromLoc & 1) + 1) * xxt * 2 + showMove.dx * xxt - m_mapWidth))
xw1 -= lx;
const int xTo = (xToLoc - xw1) * (xxt * 2) + (yToLoc & 1) * xxt + (xxt - IsoEngine::xxu);
const int yTo = (yToLoc - m_yw) * yyt + (yyt - IsoEngine::yyuAnchor);
const int xFrom = (xFromLoc - xw1) * (xxt * 2) + (yFromLoc & 1) * xxt + (xxt - IsoEngine::xxu);
const int yFrom = (yFromLoc - m_yw) * yyt + (yyt - IsoEngine::yyuAnchor);
const int xMin = std::min(xFrom, xTo);
const int yMin = std::min(yFrom, yTo);
const int xRange = std::abs(xTo - xFrom) + xxt * 2;
const int yRange = std::abs(yTo - yFrom) + yyt * 3;
mainOffscreenPaint();
if (m_moveTile.width() != xRange || m_moveTile.height() != yRange)
m_moveTile.setSize(xRange, yRange);
m_noMap->setOutput(&m_moveTile);
m_noMap->setPaintBounds(0, 0, xRange, yRange);
m_moveTilePos = QPoint(xMin, yMin);
const QRect area(xMin, yMin, xRange, yRange);
const int steps = std::abs(step1 - step0);
QElapsedTimer clock;
for (int step = 0; step <= steps; ++step) {
// the map rectangle the unit moves through, then the unit on top
m_moveTile.image() = m_offscreen.image().copy(area).convertToFormat(QImage::Format_ARGB32);
m_moveTile.canvas().setDevice(&m_moveTile.image());
int xMoving = xFrom;
int yMoving = yFrom;
if (step1 != step0) {
const int pos = step0 + step * (step1 - step0) / std::abs(step1 - step0);
xMoving = xFrom + static_cast<int>(std::lround(pos * static_cast<double>(xTo - xFrom) / nStep));
yMoving = yFrom + static_cast<int>(std::lround(pos * static_cast<double>(yTo - yFrom) / nStep));
}
m_noMap->paintUnit(xMoving - xMin, yMoving - yMin, unitInfo, 0);
m_moveTile.canvas().end();
m_moveTileValid = true;
invalidateRect(m_mapOffset + xMin, TopBarHeight + yMin, m_mapOffset + xMin + xRange, TopBarHeight + yMin + yRange);
updateNow();
// wait for MoveTime/12 ms per step, keeping the application responsive
clock.start();
const qint64 stepTime = MoveTime / 12;
do {
if (!m_idle || gameMode == cMovie)
processEventsWithDisabledKeyboard();
QThread::msleep(1);
} while (clock.elapsed() < stepTime);
}
if (restore) {
m_moveTileValid = false;
invalidateRect(m_mapOffset + xMin, TopBarHeight + yMin, m_mapOffset + xMin + xRange, TopBarHeight + yMin + yRange);
updateNow();
}
m_blinkTime = -1;
m_timer->start();
}
void MainScreen::processEventsWithDisabledKeyboard()
{
m_keyboardDisabled = true;
QCoreApplication::processEvents();
m_keyboardDisabled = false;
}
} // namespace Term
} // namespace Cevo
+316
View File
@@ -0,0 +1,316 @@
// TMainScreen.Client() branches that show what happens on the map
// (Term.pas): cShowUnitChanged/CityChanged/AfterMove/AfterAttack,
// cShowMoving/cShowCapturing, cShowAttacking and cRefreshDebugMap.
#include "Term.MainScreen.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Global.h"
#include "Messg.h"
#include "Sound.h"
#include <QThread>
namespace Cevo {
namespace Term {
namespace {
constexpr int MoveTime = 300;
constexpr int WaitAfterShowMove = 32;
bool option(ClientTools::SaveOption so)
{
return ClientTools::hasSaveOption(optionChecked, so);
}
} // namespace
void MainScreen::clientShow(int command, int newPlayer, void *data)
{
using ClientTools::me;
using ClientTools::myCity;
using ClientTools::myMap;
using ClientTools::myModel;
using ClientTools::myRO;
const int lx = ClientTools::g.lx;
const bool movieFast = gameMode == cMovie && m_movieSpeed == 4;
const auto intData = [data] { return *static_cast<int *>(data); };
CurrentMoveInfo &info = m_currentMoveInfo;
if (command == cRefreshDebugMap) {
if (intData() == m_mainMap->pDebugMap) {
m_mapValid = false;
mainOffscreenPaint();
updateNow();
}
return;
}
if (command == cShowUnitChanged || command == cShowCityChanged || command == cShowAfterMove
|| command == cShowAfterAttack) {
if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped)) || movieFast)
return;
Q_ASSERT(newPlayer == me);
if (!m_idle || gameMode == cMovie)
QCoreApplication::processEvents();
if (command == cShowCityChanged) {
if (m_idle)
info.doShow = true;
else if (info.isAlly)
info.doShow = !option(ClientTools::soAlNoMoves);
else
info.doShow = !option(ClientTools::soEnNoMoves);
} else if (command == cShowUnitChanged) {
if (m_idle)
info.doShow = !option(ClientTools::soEffectiveMovesOnly);
else if (info.isAlly)
info.doShow = !(option(ClientTools::soAlNoMoves) || option(ClientTools::soAlEffectiveMovesOnly));
else
info.doShow = !(option(ClientTools::soEnNoMoves) || option(ClientTools::soEnAttacks));
} // else keep doShow from cShowMove/cShowAttack
if (info.doShow) {
if (command == cShowCityChanged)
m_mapValid = false;
focusOnLoc(intData(), flImmUpdate);
if (command == cShowAfterMove)
paintLoc(intData(), info.afterMovePaintRadius); // show discovered areas
else
paintLoc(intData(), 1);
if (command == cShowAfterAttack && info.afterAttackExpeller >= 0) {
MessgEx::soundMessageEx(Tribes::tribe[static_cast<std::size_t>(info.afterAttackExpeller)]->tPhrase(
QStringLiteral("EXPEL")),
QString());
info.afterAttackExpeller = -1;
updateNow(); // remove message box from screen
} else if (!m_idle) {
if (command == cShowCityChanged)
QThread::msleep(static_cast<unsigned long>(MoveTime * WaitAfterShowMove / 16));
else if (command == cShowUnitChanged && (myMap[intData()] & fUnit) != 0)
QThread::msleep(static_cast<unsigned long>(MoveTime * WaitAfterShowMove / 32));
}
} else {
m_mapValid = false;
}
return;
}
auto &showMove = *static_cast<TShowMove *>(data);
if (command == cShowMoving || command == cShowCapturing) {
if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped && showMove.emix != 0xFFFF)) || movieFast)
return;
Q_ASSERT(newPlayer == me);
if (!m_idle || gameMode == cMovie)
QCoreApplication::processEvents();
info.doShow = false;
if (!m_idle && !Tribes::tribe[static_cast<std::size_t>(showMove.Owner)]->modelPictureAt(showMove.mix).hGr)
initEnemyModel(showMove.emix);
const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy);
int animationSpeed = 16;
int showMoveDomain = dGround;
bool isAlpine = false;
const auto movieSpeedAnimation = [this]() {
if (m_movieSpeed == 3)
return 4;
if (m_movieSpeed == 2)
return 8;
return 16;
};
if (m_idle) { // own unit -- make discovered land visible
Q_ASSERT(showMove.Owner == me); // no foreign moves during my turn!
info.doShow = !option(ClientTools::soEffectiveMovesOnly) || command == cShowCapturing;
if (info.doShow) {
if (gameMode == cMovie)
animationSpeed = movieSpeedAnimation();
else if (option(ClientTools::soVeryFastMoves))
animationSpeed = 4;
else if (option(ClientTools::soFastMoves))
animationSpeed = 8;
else
animationSpeed = 16;
const TModel &model = myModel[showMove.mix];
if (model.Kind == mkDiplomat || model.Domain == dAir
|| model.Cap[mcRadar] + model.Cap[mcCarrier] + model.Cap[mcAcademy] > 0
|| (myMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains)
|| (myMap[toLoc] & fTerImp) == static_cast<std::uint32_t>(tiFort)
|| (myMap[toLoc] & fTerImp) == static_cast<std::uint32_t>(tiBase))
info.afterMovePaintRadius = 2;
else
info.afterMovePaintRadius = 1;
if (myRO->Wonder[woShinkansen].EffectiveOwner == me && model.Domain == dGround
&& (myMap[showMove.FromLoc] & (fRR | fCity)) != 0 && (myMap[toLoc] & (fRR | fCity)) != 0
&& (showMove.Flags & umPlaneUnloading) == 0)
animationSpeed = 4;
showMoveDomain = model.Domain;
isAlpine = model.Cap[mcAlpine] > 0;
}
} else {
info.isAlly = myRO->Treaty[showMove.Owner] == trAlliance;
if (gameMode == cMovie)
info.doShow = true;
else if (info.isAlly)
info.doShow = !option(ClientTools::soAlNoMoves)
&& !(option(ClientTools::soAlEffectiveMovesOnly) && command != cShowCapturing);
else
info.doShow = !option(ClientTools::soEnNoMoves)
&& !(option(ClientTools::soEnAttacks) && command != cShowCapturing);
if (info.doShow) {
const TModelInfo &emodel = (*myRO->EnemyModel)[showMove.emix];
if (command == cShowCapturing) { // show capture message
QString cityName;
if ((myMap[toLoc] & fOwned) != 0) { // own city, search
int cix = myRO->nCity - 1;
while (cix >= 0 && myCity[cix].Loc != toLoc)
--cix;
cityName = Tribes::cityName(myCity[cix].ID);
} else { // foreign city, search
int ecix = myRO->nEnemyCity - 1;
while (ecix >= 0 && (*myRO->EnemyCity)[ecix].Loc != toLoc)
--ecix;
cityName = Tribes::cityName((*myRO->EnemyCity)[ecix].ID);
}
MessgEx::tribeMessage(showMove.Owner,
Tribes::tribe[static_cast<std::size_t>(showMove.Owner)]->tPhrase(
QStringLiteral("CAPTURE")).arg(cityName),
QString());
updateNow(); // remove message box from screen
}
if (info.isAlly) { // allied unit -- make discovered land visible
animationSpeed = option(ClientTools::soAlFastMoves) ? 8 : 16;
if (emodel.Kind == mkDiplomat || emodel.Domain == dAir || emodel.ATrans_Fuel > 0
|| (emodel.Cap & ((1u << (mcRadar - mcFirstNonCap)) | (1u << (mcAcademy - mcFirstNonCap)))) != 0
|| (myMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains)
|| (myMap[toLoc] & fTerImp) == static_cast<std::uint32_t>(tiFort)
|| (myMap[toLoc] & fTerImp) == static_cast<std::uint32_t>(tiBase))
info.afterMovePaintRadius = 2;
else
info.afterMovePaintRadius = 1;
} else {
animationSpeed = option(ClientTools::soEnFastMoves) ? 8 : 16;
info.afterMovePaintRadius = 0; // enemy unit, nothing discovered
}
if (gameMode == cMovie)
animationSpeed = movieSpeedAnimation();
showMoveDomain = emodel.Domain;
isAlpine = (emodel.Cap & (1u << (mcAlpine - mcFirstNonCap))) != 0;
}
}
if (info.doShow) {
using Sound::play;
const int flags = showMove.Flags;
if (command == cShowCapturing)
play(QStringLiteral("MOVE_CAPTURE"));
else if (showMove.EndHealth <= 0)
play(QStringLiteral("MOVE_DIE"));
else if (flags & umSpyMission)
play(QStringLiteral("MOVE_COVERT"));
else if (flags & umShipLoading)
play(showMoveDomain == dAir ? QStringLiteral("MOVE_PLANELANDING") : QStringLiteral("MOVE_LOAD"));
else if (flags & umPlaneLoading)
play(QStringLiteral("MOVE_LOAD"));
else if (flags & umShipUnloading)
play(showMoveDomain == dAir ? QStringLiteral("MOVE_PLANESTART") : QStringLiteral("MOVE_UNLOAD"));
else if (flags & umPlaneUnloading)
play((myMap[showMove.FromLoc] & fCity) == 0
&& (myMap[showMove.FromLoc] & fTerImp) != static_cast<std::uint32_t>(tiBase)
? QStringLiteral("MOVE_PARACHUTE")
: QStringLiteral("MOVE_UNLOAD"));
else if (showMoveDomain == dGround && !isAlpine
&& (myMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains)
&& ((myMap[showMove.FromLoc] & (fRoad | fRR | fCity)) == 0
|| (myMap[toLoc] & (fRoad | fRR | fCity)) == 0))
play(QStringLiteral("MOVE_MOUNTAIN"));
focusOnLoc(showMove.FromLoc, flImmUpdate);
paintLocBeforeMove(showMove.FromLoc);
if (command == cShowCapturing)
moveOnScreen(showMove, 1, 32, 32);
else
moveOnScreen(showMove, 1, animationSpeed, animationSpeed);
} else {
m_mapValid = false;
}
Q_UNUSED(lx);
return;
}
if (command == cShowAttacking) {
if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped && showMove.emix != 0xFFFF)) || movieFast)
return;
Q_ASSERT(newPlayer == me);
if (!m_idle || gameMode == cMovie)
QCoreApplication::processEvents();
info.afterAttackExpeller = -1;
info.doShow = false;
if (m_idle) {
info.doShow = true; // own unit -- always show attacks
} else {
info.isAlly = myRO->Treaty[showMove.Owner] == trAlliance;
info.doShow = info.isAlly ? !option(ClientTools::soAlNoMoves) : !option(ClientTools::soEnNoMoves);
}
if (!info.doShow) {
m_mapValid = false;
return;
}
const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy);
if (!Tribes::tribe[static_cast<std::size_t>(showMove.Owner)]->modelPictureAt(showMove.mix).hGr)
initEnemyModel(showMove.emix);
if ((myMap[toLoc] & (fCity | fUnit | fOwned)) == static_cast<std::uint32_t>(fCity | fOwned)) {
// tell about bombardment
int cix = myRO->nCity - 1;
while (cix >= 0 && myCity[cix].Loc != toLoc)
--cix;
if ((myCity[cix].Status & csToldBombard) == 0) {
if (!supervising)
myCity[cix].Status |= csToldBombard;
MessgEx::soundMessageEx(Tribes::tribe[static_cast<std::size_t>(showMove.Owner)]->tPhrase(
QStringLiteral("BOMBARD")).arg(Tribes::cityName(myCity[cix].ID)),
QString());
updateNow(); // remove message box from screen
}
} else if (showMove.Flags & umExpelling) {
info.afterAttackExpeller = showMove.Owner;
}
if (showMove.Flags & umExpelling) {
Sound::play(QStringLiteral("MOVE_EXPEL"));
} else if (showMove.Owner == me) {
TModelInfo mi{};
MakeModelInfo(me, showMove.mix, myModel[showMove.mix], mi);
Sound::play(attackSound(Tribes::modelCode(mi)));
} else {
Sound::play(attackSound(Tribes::modelCode((*myRO->EnemyModel)[showMove.emix])));
}
focusOnLoc(showMove.FromLoc, flImmUpdate);
// before combat
m_mainMap->attackBegin(showMove);
if ((myMap[toLoc] & fCity) != 0)
paintLoc(toLoc);
paintLoc(showMove.FromLoc);
moveOnScreen(showMove, 1, 9, 16);
moveOnScreen(showMove, 17, 12, 32);
moveOnScreen(showMove, 7, 11, 16);
// after combat
m_mainMap->attackEffect(showMove);
paintLoc(toLoc);
if (showMove.EndHealth > 0) {
showMove.Health = showMove.EndHealth;
moveOnScreen(showMove, 10, 0, 16);
} else if (!m_idle) {
QThread::msleep(static_cast<unsigned long>(MoveTime / 2));
}
m_mainMap->attackEnd();
}
}
} // namespace Term
} // namespace Cevo
+61 -4
View File
@@ -13,6 +13,7 @@
#include "Cevo/CevoTexture.h"
#include "Global.h"
#include "Messg.h"
#include "Sound.h"
#include <QApplication>
#include <QTimer>
@@ -141,7 +142,7 @@ void MainScreen::initTurn(int newPlayer)
MainTexture->setAge(-1);
m_eot->setButtonIndex(clientMode == cMovieTurn ? eotCancel : eotBlinkOn);
}
// TODO: InitCityMark(MainTexture) - the city mark sprite is not ported.
initCityMark(*MainTexture);
if (m_cityDlg)
m_cityDlg->checkAge();
if (m_natStatDlg)
@@ -624,8 +625,63 @@ void MainScreen::initTurn(int newPlayer)
else
un.Status |= usWaiting;
checkToldNoReturn(uix);
// TODO: continuing multi-turn goto (GetMoveAdvice + MoveUnit) and terrain enhancement
// (ProcessEnhancement) needs MoveUnit, which is not ported yet.
if ((un.Status & IsoEngine::usGoto) != 0) { // continue multi-turn goto
setUnFocus(uix);
setTroopLoc(un.Loc);
focusOnLoc(m_troopLoc, flRepaintPanel | flImmUpdate);
TMoveAdviceData moveAdviceData;
int moveResult;
if ((un.Status >> 16) == 0x7FFF)
moveResult = ClientTools::getMoveAdvice(IsoEngine::unFocus, maNextCity, moveAdviceData);
else
moveResult = ClientTools::getMoveAdvice(IsoEngine::unFocus, un.Status >> 16, moveAdviceData);
bool stop;
if (moveResult >= rExecuted) { // !!! Shinkansen
moveResult = eOK;
bool ok = true;
for (int i = 0; i < moveAdviceData.nStep; ++i) {
const int loc1 = ClientTools::dLoc(un.Loc, moveAdviceData.dx[i], moveAdviceData.dy[i]);
if ((ClientTools::myMap[loc1] & (fCity | fOwned)) == static_cast<std::uint32_t>(fCity)
// don't capture cities during auto move
|| (ClientTools::myMap[loc1] & (fUnit | fOwned)) == static_cast<std::uint32_t>(fUnit)) {
// don't attack during auto move
ok = false;
break;
}
const int moveOptions = loc1 == moveAdviceData.ToLoc
|| (moveAdviceData.ToLoc == maNextCity
&& (ClientTools::myMap[loc1] & fCity) != 0)
? muAutoNoWait
: 0;
moveResult = moveUnit(moveAdviceData.dx[i], moveAdviceData.dy[i], moveOptions);
if (moveResult < rExecuted || moveResult == eEnemySpotted) {
ok = false;
break;
}
}
stop = !ok || un.Loc == moveAdviceData.ToLoc
|| (moveAdviceData.ToLoc == maNextCity && (ClientTools::myMap[un.Loc] & fCity) != 0);
} else {
moveResult = eOK;
stop = true;
}
if (moveResult != eDied) {
if (stop)
un.Status &= 0xFFFF - IsoEngine::usGoto;
else
un.Status &= ~usWaiting;
}
}
if ((un.Status & (IsoEngine::usEnhance | IsoEngine::usGoto)) == IsoEngine::usEnhance) {
// continue terrain enhancement
const int moveResult = ClientTools::processEnhancement(uix, myData->enhancementJobs);
if (moveResult != eDied) {
if (moveResult == eJobDone)
un.Status &= ~IsoEngine::usEnhance;
else
un.Status &= ~usWaiting;
}
}
}
}
}
@@ -701,7 +757,8 @@ void MainScreen::nextUnit(int nearLoc, bool autoTurn)
setTroopLoc(-1);
QTimer::singleShot(0, this, [this] { endTurn(); });
} else {
// TODO: Play('TURNEND') when the turn becomes complete (sound is not ported).
if (!m_turnComplete && m_eot->isVisible())
Sound::play(QStringLiteral("TURNEND"));
m_turnComplete = true;
setUnFocus(-1);
setTroopLoc(-1);
+11 -1
View File
@@ -45,6 +45,7 @@
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Cevo/Music.h"
#include "Global.h"
#include <QApplication>
@@ -249,7 +250,10 @@ void MainScreen::closeEvent(QCloseEvent *event)
DrawDlg::closeEvent(event);
if (!event->isAccepted())
return;
termBounds = fullScreen ? m_restoredBounds : geometry();
m_timer->stop();
if (musicPlayer.playing())
musicPlayer.stop();
}
// ---- painting ----
@@ -310,6 +314,8 @@ void MainScreen::paintEvent(QPaintEvent *)
blit(m_mapOffset, TopBarHeight, m_offscreen, 0, 0, m_mapWidth, m_mapHeight);
if (m_blinkTileValid)
painter.drawImage(m_blinkTilePos + QPoint(m_mapOffset, TopBarHeight), m_blinkTile.image());
if (m_moveTileValid)
painter.drawImage(m_moveTilePos + QPoint(m_mapOffset, TopBarHeight), m_moveTile.image());
painter.restore();
blit(0, 0, m_topBar, 0, 0, cw, TopBarHeight);
@@ -390,7 +396,11 @@ void MainScreen::copyMiniToPanel()
bitBltBitmap(m_panel, m_xMini + 2, m_yMini + 2, lx * 2, ly, m_miniMap->bitmap, 0, 0);
Dpi::Canvas &canvas = m_panel.canvas();
if (m_markCityLoc >= 0) {
// TODO: the city mark sprite (InitCityMark/CityMark2) is not ported yet.
if (const GraphicSetItem *mark = HGrSystem->searchByName(QStringLiteral("CityMark2")))
sprite(canvas, *HGrSystem,
m_xMini - 2 + (4 * lx + 2 * (m_markCityLoc % lx) + (lx - m_mapWidth / (xxt * 2)) - 2 * m_xwd) % (2 * lx)
+ ((m_markCityLoc / lx) & 1),
m_yMini - 3 + m_markCityLoc / lx, mark->width, mark->height, mark->left, mark->top);
} else if (m_ywmax <= 0) {
frame(canvas, m_xMini + 2 + lx - m_mapWidth / (xxt * 2), m_yMini + 2, m_xMini + 1 + lx + m_mapWidth / (xxt * 2),
m_yMini + 2 + ly - 1, MainTexture->colorMark, MainTexture->colorMark);
+33 -19
View File
@@ -27,10 +27,12 @@
// knowledge of the CeCILL license and that you accept its terms.
#include "Term.MainScreen.h"
#include "Term.MainScreen.Menus.h"
#include "Cevo/Database.h"
#include "ClientTools.h"
#include "Global.h"
#include "Sound.h"
#include "Tribes.h"
#include <QApplication>
@@ -54,7 +56,8 @@ MainScreen::MainScreen(QWidget *parent) : DrawDlg(parent)
resize(800, 480);
setAttribute(Qt::WA_OpaquePaintEvent);
onCloseQuery = [this] {
// TODO: when not closable, idle and playing, the original resigns (mResign.Click).
if (!m_closable && m_idle && ClientTools::me == 0 && clientMode < scContact)
menuCommand(MenuCommand::Resign);
return m_closable;
};
@@ -66,7 +69,9 @@ MainScreen::MainScreen(QWidget *parent) : DrawDlg(parent)
m_topBar.canvas().font().assign(UniFont[static_cast<std::size_t>(FontType::Normal)]);
m_offscreen.canvas().font().assign(UniFont[static_cast<std::size_t>(FontType::Small)]);
createControls();
loadSettings();
createMenus();
wireControls();
mainScreenZoomToCity = [this](int loc, bool nextUnitOnClose, int showEvent) {
return zoomToCity(loc, nextUnitOnClose, showEvent);
};
@@ -381,14 +386,21 @@ int MainScreen::dipCall(int command)
mem.sentCommand = command;
mem.formerTreaty = ClientTools::myRO->Treaty[mem.pContact];
if (command == scDipCancelTreaty) {
// TODO: Sound.pas not ported.
Sound::play(QStringLiteral("CANCELTREATY"));
} else if (command == scDipAccept) {
for (int i = 0; i < receivedOffer.nDeliver; ++i)
mem.receivedPrices.set(static_cast<std::size_t>(receivedOffer.Price[i] >> 24));
for (int i = 0; i < receivedOffer.nCost; ++i)
mem.deliveredPrices.set(
static_cast<std::size_t>(receivedOffer.Price[receivedOffer.nDeliver + i] >> 24));
// TODO: Sound.pas not ported (NEWTREATY/ACCEPTOFFER distinction).
bool isTreatyDeal = false;
for (int i = 0; i < receivedOffer.nDeliver + receivedOffer.nCost; ++i) {
if ((receivedOffer.Price[i] & opMask) == opTreaty) {
isTreatyDeal = true;
break;
}
}
Sound::play(isTreatyDeal ? QStringLiteral("NEWTREATY") : QStringLiteral("ACCEPTOFFER"));
}
cityDlg().closeAction = CityScreen::CityCloseAction::None;
closeDialogsForNextPlayer(*this);
@@ -440,25 +452,27 @@ void MainScreen::setAIName(int p, const QString &name)
bool MainScreen::contactRefused(int p, const QString &item)
{
Q_ASSERT(ClientTools::myRO->Treaty[p] >= trPeace);
const QString s = Tribes::tribe[static_cast<std::size_t>(p)]->tPhrase(item);
QString s = Tribes::tribe[static_cast<std::size_t>(p)]->tPhrase(item);
if (ClientTools::myRO->Turn < ClientTools::myRO->LastCancelTreaty[p] + CancelTreatyTurns) {
// TODO: Phrases/SimpleMessage dialog not shown - needs Messg.pas's
// simpleMessage() wired through an injection point if ever needed
// from here; the important part (refusing the cancel) still works.
simpleMessage(s);
return false;
}
const Dpi::ModalResult result =
MessgEx::simpleQuery(MessageKind::YesNo, s, QStringLiteral("NEGO_REJECTED"));
if (result == Dpi::ModalResult::Ok) {
// TODO: Sound.pas not ported.
int dummy = 0;
ClientTools::server(sCancelTreaty, ClientTools::me, 0, &dummy);
if (ClientTools::myRO->Treaty[p] == trNone)
ClientTools::cityOptimizer_BeginOfTurn();
// TODO: needs the real main map (not ported yet) to repaint.
return true;
switch (ClientTools::myRO->Treaty[p]) {
case trPeace: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_PEACE")]; break;
case trFriendlyContact: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_FRIENDLY")]; break;
case trAlliance: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_ALLIANCE")]; break;
default: break;
}
return false;
if (MessgEx::simpleQuery(MessageKind::YesNo, s, QStringLiteral("NEGO_REJECTED")) != Dpi::ModalResult::Ok)
return false;
Sound::play(QStringLiteral("CANCELTREATY"));
ClientTools::server(sCancelTreaty, ClientTools::me, 0, nullptr);
if (ClientTools::myRO->Treaty[p] == trNone)
ClientTools::cityOptimizer_BeginOfTurn();
// peace treaty was cancelled -- use formerly forbidden tiles
m_mapValid = false;
paintAllMaps();
return true;
}
void MainScreen::getTribeList()
+84 -14
View File
@@ -28,20 +28,14 @@
#pragma once
// TMainScreen equivalent - PARTIAL PORT (session 1 of what will be a many-
// session effort, see /memories/repo/cevo-evo-game.md for the full 183-
// method inventory + proposed 10-file split). This slice only covers: the
// 17 lazy dialog accessors, arrangeDialog()/arrangeDialogs(), and the
// handful of small cross-dialog methods (dipCall/offerCall/
// contactRefused/updateViews/setAIName/rememberPeaceViolation) that every
// other LocalPlayer dialog already has a `Term::mainScreenXxx`
// std::function injection point standing in for - this class's
// constructor wires all of those through to real methods below. The full
// map/panel/menu system (MainOffscreenPaint/PanelPaint/Client() etc.) is
// NOT part of this slice and remains future work - this header is kept
// SEPARATE from the widely-included Term.h specifically so consumers that
// only need the `Term::mainScreen` pointer don't have to transitively
// include all 17 dialog headers below.
// TMainScreen equivalent - PARTIAL PORT. Ported so far: the window layer and
// paint pipeline (Term.MainScreen.Window.cpp), PanelPaint (…Panel.cpp),
// InitTurn/NextUnit/EndTurn/ZoomToCity (…Turn.cpp), most of Client()
// (…Client.cpp) and the 17 lazy dialog accessors with the small cross-dialog
// methods in Term.MainScreen.cpp. Still missing: the menus, mouse/keyboard
// input, MoveUnit/ShowMove and sound. This header is kept SEPARATE from the
// widely-included Term.h so consumers that only need the `Term::mainScreen`
// pointer don't have to transitively include all the dialog headers below.
#include "Battle.h"
#include "Cevo/CevoArea.h"
@@ -157,6 +151,64 @@ public:
void panelPaint();
void setUnFocus(int uix);
void focusOnLoc(int loc, int options = 0);
// Moves the focused unit to an adjacent tile (Term.pas's MoveUnit).
int moveUnit(int dx, int dy, int options = 0);
// Path finder: moves the focused unit to loc, starts a multi-turn goto if too far.
void moveToLoc(int loc, bool checkSuicide);
// Animates a unit moving from step0 to step1 of nStep.
void moveOnScreen(const TShowMove &showMove, int step0, int step1, int nStep, bool restore = true);
void processEventsWithDisabledKeyboard();
// Client() branches that animate what happens on the map.
void clientShow(int command, int newPlayer, void *data);
// ---- Menus, settings and input (Term.MainScreen.Menus.cpp / Input.cpp) ----
void loadSettings();
void saveSettings();
void updateMusic();
void setDebugMap(int p);
void setViewpoint(int p);
void focusNextUnit(int dir = 1);
int doJob(int job);
void setFullScreen(bool active);
protected:
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *event) override;
private:
enum class MenuCommand {
Help, TechTree, Jump, Run, Names, LocCodes, Log, EnhanceDef, CityTypes, RandomMap, FillMap, Website, Resign,
Disband, Utilize, City, Pillage, Home, Load, Unload, SelectTransport, GoOn, Cancel, Recover, Wait, NoOrders, Stay,
Centre, PrevUnit, NextUnit, UnitStat, CityStat, ScienceStat, EUnitStat, Diagram, Wonders, Ships, Nations, Empire,
Revolution, Trans, Afforest, Clear, Fort, AirBase, Canal, Mine, Farm, Irrigation, RailRoad, Road, Pollution,
Enhance, TileSmall, TileNormal, TileBig, SoundOn, SoundOnAlt, SoundOff, MusicOn, MusicOff
};
enum class PopupKind { Game, Unit, Stat, Terrain, Edit };
struct Menus;
void createMenus();
void initPopup(PopupKind kind);
void showPopup(PopupKind kind, const QPoint &globalPos);
void menuCommand(MenuCommand command);
// Triggers a menu item if it is visible and enabled (MenuClick_Check of FormKeyDown).
void menuClickChecked(PopupKind kind, MenuCommand command);
void mapMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos);
void mapMouseMove(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, QPoint pos);
void panelMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos);
void panelMouseMove(Qt::MouseButtons buttons, QPoint pos);
void panelMouseUp();
bool isPanelPixel(int x, int y) const;
void mapButtonClicked(ButtonC *button);
void mapOptionButtonChanged(ButtonC *button, int option);
void panelButtonClicked(ButtonB *button);
void disbandOrUtilize(bool utilize);
void setTroopLocAndPanel(int loc);
void wireControls();
QMenu *createUnitMenu();
void triggerMenu(MenuCommand command);
bool menuItemUsable(MenuCommand command) const;
void setTileSize(IsoEngine::TileSize tileSize, int loc, QPoint mapPos);
void setTileSizeCenter(IsoEngine::TileSize tileSize);
void checkTerrainBtnVisible();
@@ -245,10 +297,28 @@ private:
Dpi::Bitmap m_blinkTile;
QPoint m_blinkTilePos;
bool m_blinkTileValid = false;
// The map rectangle a moving unit travels through (see moveOnScreen).
Dpi::Bitmap m_moveTile;
QPoint m_moveTilePos;
bool m_moveTileValid = false;
bool m_keyboardDisabled = false;
struct CurrentMoveInfo {
int afterMovePaintRadius = 0;
int afterAttackExpeller = -1;
bool doShow = false;
bool isAlly = false;
} m_currentMoveInfo;
std::unique_ptr<IsoEngine::IsoMap> m_mainMap;
std::unique_ptr<IsoEngine::IsoMap> m_noMap;
std::unique_ptr<IsoEngine::IsoMap> m_noMapPanel;
std::unique_ptr<MiniMap> m_miniMap;
std::unique_ptr<Menus> m_menus;
int m_editLoc = -1;
int m_mouseX = 0;
int m_mouseY = 0;
int m_dragStartLoc = -1;
QRect m_restoredBounds;
bool m_formFullScreen = false;
std::unique_ptr<PVScrollBar> m_verticalScrollBar;
ButtonB *m_unitBtn = nullptr;
ButtonB *m_unitInfoBtn = nullptr;
+4 -4
View File
@@ -382,10 +382,10 @@ bool createTribe(int p, QString fileName, bool original)
tribeOriginal[player] = original;
Tribes::tribe[player] = std::make_unique<Tribes::Tribe>(fileName);
if (gameMode == cNewGame || !original) {
chooseModelPicture(p, 0, 010, 1, 0, true, true);
chooseModelPicture(p, 1, 040, 1, 0, true, true);
chooseModelPicture(p, 2, 041, 1, 0, true, true);
chooseModelPicture(p, -1, 017, 1, 0, true, true);
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;
+5
View File
@@ -224,6 +224,11 @@ constexpr int prPaint = 0x0001;
constexpr int prAutoBounds = 0x0002;
constexpr int prInvalidate = 0x0004;
// MoveUnit options.
constexpr int muAutoNoWait = 0x0001;
constexpr int muAutoNext = 0x0002;
constexpr int muNoSuicideCheck = 0x0004;
enum class PaintLocTempStyle { Normal, Blink };
// Terrain brushes of the map editor.