ManaPlus
Public Member Functions | Static Public Member Functions | Private Member Functions | Private Attributes | Static Private Attributes
Game Class Reference

#include <game.h>

Public Member Functions

 Game ()
 
 ~Game ()
 
void logic ()
 
void slowLogic ()
 
void handleInput ()
 
void handleMove ()
 
void changeMap (const std::string &mapName)
 
void updateFrameRate (int fpsLimit)
 
Map * getCurrentMap () const
 
const std::string & getCurrentMapName () const
 
void setValidSpeed ()
 
void adjustPerfomance ()
 
void resetAdjustLevel ()
 
void setAdjustLevel (const int n)
 
bool getValidSpeed () const
 
void updateHistory (const SDL_Event &event)
 
void checkKeys ()
 

Static Public Member Functions

static Game * instance ()
 
static void clearInstance ()
 
static void videoResized (const int width, const int height)
 
static void moveInDirection (const unsigned char direction)
 
static bool createScreenshot (const std::string &prefix)
 
static void addWatermark ()
 
static bool saveScreenshot (SDL_Surface *const screenshot, const std::string &prefix)
 

Private Member Functions

void clearKeysArray ()
 

Private Attributes

Map * mCurrentMap
 
std::string mMapName
 
bool mValidSpeed
 
LastKey mLastKeys [MAX_LASTKEYS]
 
time_t mNextAdjustTime
 
int mAdjustLevel
 
bool mAdjustPerfomance
 
int mLowerCounter
 
int mPing
 
time_t mTime
 
time_t mTime2
 

Static Private Attributes

static Game * mInstance = 0
 

Detailed Description

The main class responsible for running the game. The game starts after you have selected your character.

Definition at line 63 of file game.h.

Constructor & Destructor Documentation

◆ Game()

Game::Game ( )

Constructs the game, creating all the managers, handlers, engines and GUI windows that make up the game.

Definition at line 405 of file game.cpp.

405  :
406  mCurrentMap(nullptr),
407  mMapName(""),
408  mValidSpeed(true),
410  mAdjustLevel(0),
411  mAdjustPerfomance(config.getBoolValue("adjustPerfomance")),
412  mLowerCounter(0),
413  mPing(0),
414  mTime(cur_time + 1),
415  mTime2(cur_time + 10)
416 {
417  touchManager.setInGame(true);
418 
419 // assert(!mInstance);
420  if (mInstance != nullptr)
421  logger->log("error: double game creation");
422  mInstance = this;
423 
424  config.incValue("gamecount");
425 
426  disconnectedDialog = nullptr;
427 
428  // Create the viewport
429  viewport = new Viewport;
432 
434 
435  BasicContainer2 *const top = static_cast<BasicContainer2*>(gui->getTop());
436  if (top != nullptr)
437  top->add(viewport);
439 
442  config.getBoolValue("enableDelayedAnimations"));
443 
445  config.getBoolValue("enableCompoundSpriteDelay"));
446 
448  windowMenu = new WindowMenu(nullptr);
449 
450  if (windowContainer != nullptr)
452 
453 #ifdef USE_OPENGL
455 #endif // USE_OPENGL
456 
457  initEngines();
458 
461 
462  // Initialize beings
463  if (actorManager != nullptr)
465 
467 
468  if (setupWindow != nullptr)
469  setupWindow->setInGame(true);
470  clearKeysArray();
471 
472 #ifdef TMWA_SUPPORT
473  if (guildManager != nullptr && GuildManager::getEnableGuildBot())
475 #endif // TMWA_SUPPORT
476 
478  "disableLoggingInGame");
479 }
ActorManager * actorManager
volatile time_t cur_time
Definition: timer.cpp:58
BeingSlot * emptyBeingSlot
Definition: beingslot.cpp:26
ChatWindow * chatWindow
Definition: chatwindow.cpp:94
void setPlayer(LocalPlayer *const player)
static void setEnableCache(const bool b)
virtual void add(Widget *const widget)
void postConnection()
static void setEnableDelay(bool b)
bool getBoolValue(const std::string &key) const
void incValue(const std::string &key)
Map * mCurrentMap
Definition: game.h:143
int mLowerCounter
Definition: game.h:150
std::string mMapName
Definition: game.h:144
time_t mNextAdjustTime
Definition: game.h:147
bool mAdjustPerfomance
Definition: game.h:149
int mPing
Definition: game.h:151
bool mValidSpeed
Definition: game.h:145
time_t mTime2
Definition: game.h:153
int mAdjustLevel
Definition: game.h:148
static Game * mInstance
Definition: game.h:155
void clearKeysArray()
Definition: game.cpp:1279
time_t mTime
Definition: game.h:152
int mWidth
Definition: graphics.h:484
RenderType getOpenGL() const
Definition: graphics.h:308
int mHeight
Definition: graphics.h:485
Widget * getTop() const
Definition: gui.h:248
static bool getEnableGuildBot()
Definition: guildmanager.h:56
void requestGuildInfo()
void log(const char *const log_text,...)
Definition: logger.cpp:269
void postConnection()
Definition: mailwindow.cpp:347
static void loadEmptyAtlas()
Definition: mapreader.cpp:1319
virtual void ping(const int tick) const =0
bool disableLoggingInGame
Definition: settings.h:161
void setInGame(const bool inGame)
void setInGame(const bool b)
void setSize(const int width, const int height)
Definition: widget.cpp:367
virtual void requestMoveToBottom()
Definition: widget.cpp:219
Configuration config
Viewport * viewport
Definition: viewport.cpp:36
const time_t adjustDelay
Definition: game.cpp:162
static void initEngines()
Definition: game.cpp:167
static void createGuiWindows()
Definition: game.cpp:195
Window * disconnectedDialog
Definition: game.cpp:159
Net::GameHandler * gameHandler
Definition: net.cpp:91
Graphics * mainGraphics
Definition: graphics.cpp:109
const Image *restrict const top
Gui * gui
Definition: gui.cpp:111
GuildManager * guildManager
LocalPlayer * localPlayer
Logger * logger
Definition: logger.cpp:89
MailWindow * mailWindow
Definition: mailwindow.cpp:54
volatile int tick_time
Definition: timer.cpp:53
void clear()
Definition: playerinfo.cpp:452
@ RENDER_SOFTWARE
Definition: rendertype.h:27
Settings settings
Definition: settings.cpp:32
SetupWindow * setupWindow
Definition: setupwindow.cpp:64
TouchManager touchManager
WindowContainer * windowContainer
WindowMenu * windowMenu
Definition: windowmenu.cpp:51

References actorManager, BasicContainer2::add(), chatWindow, PlayerInfo::clear(), clearKeysArray(), config, createGuiWindows(), Settings::disableLoggingInGame, disconnectedDialog, emptyBeingSlot, gameHandler, Configuration::getBoolValue(), GuildManager::getEnableGuildBot(), Graphics::getOpenGL(), Gui::getTop(), gui, guildManager, Configuration::incValue(), initEngines(), MapReader::loadEmptyAtlas(), localPlayer, Logger::log(), logger, mailWindow, mainGraphics, Graphics::mHeight, mInstance, Graphics::mWidth, Net::GameHandler::ping(), ChatWindow::postConnection(), MailWindow::postConnection(), RENDER_SOFTWARE, GuildManager::requestGuildInfo(), Widget::requestMoveToBottom(), AnimatedSprite::setEnableCache(), CompoundSprite::setEnableDelay(), TouchManager::setInGame(), SetupWindow::setInGame(), ActorManager::setPlayer(), Widget::setSize(), settings, setupWindow, tick_time, top, touchManager, viewport, windowContainer, and windowMenu.

◆ ~Game()

Game::~Game ( )

Destructor, cleans up the game.

Definition at line 481 of file game.cpp.

482 {
483 #ifdef USE_OPENGL
485 #endif // USE_OPENGL
486 
488  touchManager.setInGame(false);
489  config.write();
493 
495 
499  if (effectManager != nullptr)
500  effectManager->clear();
505 #ifdef TMWA_SUPPORT
507 #endif // TMWA_SUPPORT
508 #ifdef USE_MUMBLE
509  delete2(mumbleManager)
510 #endif // USE_MUMBLE
511 
514 
516  mInstance = nullptr;
518 }
static void clearCache()
Definition: being.cpp:4719
StateT getState() const
Definition: client.h:69
void resetAdjustLevel()
Definition: game.cpp:889
static void unloadEmptyAtlas()
Definition: mapreader.cpp:1335
Configuration serverConfig
CrazyMoves * crazyMoves
Definition: crazymoves.cpp:47
#define delete2(var)
Definition: delete2.h:25
Client * client
Definition: client.cpp:118
EffectManager * effectManager
static void destroyGuiWindows()
Definition: game.cpp:349
void gameDestroyed()
Definition: playerinfo.cpp:463
@ CHANGE_MAP
Definition: state.h:50
ParticleEngine * particleEngine

References actorManager, State::CHANGE_MAP, EffectManager::clear(), Being::clearCache(), client, config, crazyMoves, delete2, destroyGuiWindows(), Settings::disableLoggingInGame, effectManager, emptyBeingSlot, PlayerInfo::gameDestroyed(), Client::getState(), guildManager, localPlayer, mCurrentMap, mInstance, particleEngine, resetAdjustLevel(), serverConfig, AnimatedSprite::setEnableCache(), TouchManager::setInGame(), settings, touchManager, MapReader::unloadEmptyAtlas(), viewport, and Configuration::write().

Member Function Documentation

◆ addWatermark()

void Game::addWatermark ( )
static

Definition at line 520 of file game.cpp.

521 {
522  if ((boldFont == nullptr) || !config.getBoolValue("addwatermark"))
523  return;
524 
525  const Color &color1 = theme->getColor(ThemeColorId::TEXT, 255);
526  const Color &color2 = theme->getColor(ThemeColorId::TEXT_OUTLINE, 255);
527 
529  color1,
530  color2,
532  100, 50);
533 }
Definition: color.h:76
void drawString(Graphics *const graphics, Color col, const Color &col2, const std::string &text, const int x, const int y)
Definition: font.cpp:254
std::string serverName
Definition: settings.h:114
const Color & getColor(const ThemeColorIdT type, const unsigned int alpha)
Definition: theme.h:136
Font * boldFont
Definition: gui.cpp:112
Theme * theme
Definition: theme.cpp:62

References boldFont, config, Font::drawString(), Configuration::getBoolValue(), Theme::getColor(), mainGraphics, Settings::serverName, settings, QuestType::TEXT, and theme.

Referenced by createScreenshot().

◆ adjustPerfomance()

void Game::adjustPerfomance ( )

Definition at line 782 of file game.cpp.

783 {
784  FUNC_BLOCK("Game::adjustPerfomance", 1)
785  const time_t time = cur_time;
787  {
788  mNextAdjustTime = time + adjustDelay;
789  }
790  else if (mNextAdjustTime < time)
791  {
792  mNextAdjustTime = time + adjustDelay;
793 
794  if (mAdjustLevel > 3 ||
795  localPlayer == nullptr ||
798  {
799  return;
800  }
801 
802  int maxFps = WindowManager::getFramerate();
803  if (maxFps != config.getIntValue("fpslimit"))
804  return;
805 
806  if (maxFps == 0)
807  maxFps = 30;
808  else if (maxFps < 10)
809  return;
810 
811  if (fps < maxFps - 10)
812  {
813  if (mLowerCounter < 2)
814  {
815  mLowerCounter ++;
817  return;
818  }
819  mLowerCounter = 0;
820  mAdjustLevel ++;
821  switch (mAdjustLevel)
822  {
823  case 1:
824  {
825  if (config.getBoolValue("beingopacity"))
826  {
827  config.setValue("beingopacity", false);
828  config.setSilent("beingopacity", true);
829  if (localChatTab != nullptr)
830  {
832  // TRANSLATORS: auto adjust settings message
833  _("Auto disable Show beings transparency"),
837  }
838  }
839  else
840  {
841  mNextAdjustTime = time + 1;
842  mLowerCounter = 2;
843  }
844  break;
845  }
846  case 2:
848  {
850  if (localChatTab != nullptr)
851  {
853  // TRANSLATORS: auto adjust settings message
854  _("Auto lower Particle effects"),
858  }
859  }
860  else
861  {
862  mNextAdjustTime = time + 1;
863  mLowerCounter = 2;
864  }
865  break;
866  case 3:
867  if (!config.getBoolValue("alphaCache"))
868  {
869  config.setValue("alphaCache", true);
870  config.setSilent("alphaCache", false);
871  if (localChatTab != nullptr)
872  {
874  // TRANSLATORS: auto adjust settings message
875  _("Auto enable opacity cache"),
879  }
880  }
881  break;
882  default:
883  break;
884  }
885  }
886  }
887 }
ChatTab * localChatTab
Definition: chattab.cpp:62
void chatLog(std::string line, ChatMsgTypeT own, const IgnoreRecord ignoreRecord, const TryRemoveColors tryRemoveColors)
Definition: chattab.cpp:111
void setValue(const std::string &key, const std::string &value)
void setSilent(const std::string &key, const std::string &value)
int getIntValue(const std::string &key) const
bool getHalfAway() const
Definition: localplayer.h:239
static int emitterSkip
bool awayMode
Definition: settings.h:158
#define _(s)
Definition: gettext.h:35
if(!vert) return
const bool IgnoreRecord_false
Definition: ignorerecord.h:30
#define FUNC_BLOCK(name, id)
Definition: perfomance.h:81
volatile int fps
Definition: timer.cpp:54
const bool TryRemoveColors_true

References _, adjustDelay, Settings::awayMode, ChatMsgType::BY_SERVER, ChatTab::chatLog(), config, cur_time, ParticleEngine::emitterSkip, fps, FUNC_BLOCK, Configuration::getBoolValue(), WindowManager::getFramerate(), LocalPlayer::getHalfAway(), Configuration::getIntValue(), IgnoreRecord_false, localChatTab, localPlayer, mAdjustLevel, mLowerCounter, mNextAdjustTime, Configuration::setSilent(), settings, Configuration::setValue(), and TryRemoveColors_true.

Referenced by slowLogic().

◆ changeMap()

void Game::changeMap ( const std::string &  mapPath)

Changes the currently active map. Should only be called while the game is running.

Definition at line 1093 of file game.cpp.

1094 {
1095  BLOCK_START("Game::changeMap")
1096 
1097  skipPerfFrames = 3;
1098  resetAdjustLevel();
1100 
1101  PopupManager::clearPopup();
1102  PopupManager::closePopupMenu();
1103 
1104  // Clean up floor items, beings and particles
1105  if (actorManager != nullptr)
1106  actorManager->clear();
1107 
1108  // Close the popup menu on map change so that invalid options can't be
1109  // executed.
1110  if (viewport != nullptr)
1111  viewport->cleanHoverItems();
1112 
1113  // Unset the map of the player so that its particles are cleared before
1114  // being deleted in the next step
1115  if (localPlayer != nullptr)
1116  localPlayer->setMap(nullptr);
1117 
1118  if (particleEngine != nullptr)
1119  particleEngine->clear();
1120 
1121  mMapName = mapPath;
1122 
1123  std::string fullMap = pathJoin(paths.getValue("maps", "maps/"),
1124  mMapName).append(".tmx");
1125  std::string realFullMap = pathJoin(paths.getValue("maps", "maps/"),
1126  MapDB::getMapName(mMapName)).append(".tmx");
1127 
1128  if (!VirtFs::exists(realFullMap))
1129  realFullMap.append(".gz");
1130 
1131  // Attempt to load the new map
1132  Map *const newMap = MapReader::readMap(fullMap, realFullMap);
1133 
1134  if (mCurrentMap != nullptr)
1135  mCurrentMap->saveExtraLayer();
1136 
1137  if (newMap != nullptr)
1138  newMap->addExtraLayer();
1139 
1140  if (socialWindow != nullptr)
1141  socialWindow->setMap(newMap);
1142 
1143  // Notify the minimap and actorManager about the map change
1144  if (minimap != nullptr)
1145  minimap->setMap(newMap);
1146  if (actorManager != nullptr)
1147  actorManager->setMap(newMap);
1148  if (particleEngine != nullptr)
1149  particleEngine->setMap(newMap);
1150  if (viewport != nullptr)
1151  viewport->setMap(newMap);
1152 
1153  // Initialize map-based particle effects
1154  if (newMap != nullptr)
1155  newMap->initializeParticleEffects();
1156 
1157  // Start playing new music file when necessary
1158  const std::string oldMusic = mCurrentMap != nullptr
1159  ? mCurrentMap->getMusicFile() : "";
1160  const std::string newMusic = newMap != nullptr ?
1161  newMap->getMusicFile() : "";
1162  if (newMusic != oldMusic)
1163  {
1164  if (newMusic.empty())
1165  soundManager.fadeOutMusic(1000);
1166  else
1167  soundManager.fadeOutAndPlayMusic(newMusic, 1000);
1168  }
1169 
1170  if (mCurrentMap != nullptr)
1172 
1173  delete mCurrentMap;
1174  mCurrentMap = newMap;
1175 
1176  if (questsWindow != nullptr)
1178 
1179 #ifdef USE_MUMBLE
1180  if (mumbleManager)
1181  mumbleManager->setMap(mapPath);
1182 #endif // USE_MUMBLE
1183 
1184  if (localPlayer != nullptr)
1186 
1188  Perf::init();
1189  BLOCK_END("Game::changeMap")
1190 }
void recreateItemParticles()
Definition: being.cpp:5163
Definition: map.h:75
void saveExtraLayer() const
Definition: map.cpp:1226
virtual void mapLoadedEvent() const =0
void setMap(const Map *const map)
void fadeOutAndPlayMusic(const std::string &fileName, const int ms)
void fadeOutMusic(const int ms)
Configuration paths
Minimap * minimap
Definition: minimap.cpp:62
Definition: mapdb.cpp:42
const std::string getMapName(const std::string &name)
Definition: mapdb.cpp:204
void readMap(xmlNode *const node)
Definition: mapdb.cpp:105
void init()
Definition: perfstat.cpp:41
bool exists(std::string name)
Definition: fs.cpp:124
#define BLOCK_END(name)
Definition: perfomance.h:80
#define BLOCK_START(name)
Definition: perfomance.h:79
int skipPerfFrames
Definition: perfstat.cpp:37
QuestsWindow * questsWindow
SocialWindow * socialWindow
SoundManager soundManager
std::string pathJoin(std::string str1, const std::string &str2)

References actorManager, Map::addExtraLayer(), BLOCK_END, BLOCK_START, Viewport::cleanHoverItems(), ResourceManager::cleanProtected(), ActorManager::clear(), ParticleEngine::clear(), PopupManager::clearPopup(), PopupManager::closePopupMenu(), VirtFs::exists(), SoundManager::fadeOutAndPlayMusic(), SoundManager::fadeOutMusic(), gameHandler, MapDB::getMapName(), Map::getMusicFile(), ConfigurationObject::getValue(), Perf::init(), Map::initializeParticleEffects(), localPlayer, Net::GameHandler::mapLoadedEvent(), mCurrentMap, minimap, mMapName, particleEngine, pathJoin(), paths, questsWindow, MapReader::readMap(), Being::recreateItemParticles(), resetAdjustLevel(), Map::saveExtraLayer(), Minimap::setMap(), QuestsWindow::setMap(), ActorManager::setMap(), LocalPlayer::setMap(), SocialWindow::setMap(), ParticleEngine::setMap(), Viewport::setMap(), skipPerfFrames, socialWindow, soundManager, and viewport.

Referenced by Ea::GameHandler::initEngines(), and Ea::PlayerRecv::processPlayerWarp().

◆ checkKeys()

void Game::checkKeys ( )

Definition at line 1249 of file game.cpp.

1250 {
1251  const int timeRange = 120;
1252  const int cntInTime = 130;
1253 
1254  if ((localPlayer == nullptr) || (settings.attackType == 0U))
1255  return;
1256 
1257  const time_t time = cur_time;
1258  for (int f = 0; f < MAX_LASTKEYS; f ++)
1259  {
1260  LastKey &lastKey = mLastKeys[f];
1261  if (lastKey.key != InputAction::NO_VALUE)
1262  {
1263  if (lastKey.time + timeRange < time)
1264  {
1265  if (lastKey.cnt > cntInTime)
1266  mValidSpeed = false;
1267  lastKey.key = InputAction::NO_VALUE;
1268  }
1269  }
1270  }
1271 }
LastKey mLastKeys[MAX_LASTKEYS]
Definition: game.h:146
unsigned int attackType
Definition: settings.h:138
static const int MAX_LASTKEYS
Definition: game.h:38
Definition: game.h:45
InputActionT key
Definition: game.h:55
int cnt
Definition: game.h:56
time_t time
Definition: game.h:54

References Settings::attackType, LastKey::cnt, cur_time, LastKey::key, localPlayer, MAX_LASTKEYS, mLastKeys, mValidSpeed, InputAction::NO_VALUE, settings, and LastKey::time.

◆ clearInstance()

static void Game::clearInstance ( )
inlinestatic

Definition at line 85 of file game.h.

86  { mInstance = nullptr; }

References mInstance.

◆ clearKeysArray()

void Game::clearKeysArray ( )
private

Definition at line 1279 of file game.cpp.

1280 {
1281  for (int f = 0; f < MAX_LASTKEYS; f ++)
1282  {
1283  mLastKeys[f].time = 0;
1285  mLastKeys[f].cnt = 0;
1286  }
1287 }

References LastKey::cnt, LastKey::key, MAX_LASTKEYS, mLastKeys, InputAction::NO_VALUE, and LastKey::time.

Referenced by Game(), and setValidSpeed().

◆ createScreenshot()

bool Game::createScreenshot ( const std::string &  prefix)
static

Definition at line 535 of file game.cpp.

536 {
537  if ((mainGraphics == nullptr) || (screenshortHelper == nullptr))
538  return false;
539 
540  SDL_Surface *screenshot = nullptr;
541 
542  if (!config.getBoolValue("showip") && (gui != nullptr))
543  {
544  mainGraphics->setSecure(true);
546  gui->draw();
547  addWatermark();
549  mainGraphics->setSecure(false);
550  }
551  else
552  {
553  addWatermark();
555  }
556 
557  if (screenshot == nullptr)
558  return false;
559 
560  return saveScreenshot(screenshot, prefix);
561 }
static void addWatermark()
Definition: game.cpp:520
static bool saveScreenshot(SDL_Surface *const screenshot, const std::string &prefix)
Definition: game.cpp:563
void setSecure(const bool n)
Definition: graphics.h:290
void draw()
Definition: gui.cpp:470
virtual SDL_Surface * getScreenshot()=0
virtual void prepare()=0
ScreenshotHelper * screenshortHelper
bool screenshot(InputEvent &event)
Definition: actions.cpp:51

References addWatermark(), config, Gui::draw(), Configuration::getBoolValue(), ScreenshotHelper::getScreenshot(), gui, mainGraphics, ScreenshotHelper::prepare(), saveScreenshot(), screenshortHelper, Actions::screenshot(), and Graphics::setSecure().

Referenced by TradeWindow::completeTrade().

◆ getCurrentMap()

Map* Game::getCurrentMap ( ) const
inline

◆ getCurrentMapName()

const std::string& Game::getCurrentMapName ( ) const
inline

Definition at line 110 of file game.h.

111  { return mMapName; }

References mMapName.

Referenced by Ea::PlayerRecv::processPlayerWarp().

◆ getValidSpeed()

bool Game::getValidSpeed ( ) const
inline

Definition at line 124 of file game.h.

125  { return mValidSpeed; }

References mValidSpeed.

◆ handleInput()

void Game::handleInput ( )

The huge input handling method.

Definition at line 1060 of file game.cpp.

1061 {
1062  BLOCK_START("Game::handleInput 1")
1063  if (joystick != nullptr)
1064  joystick->logic();
1065 
1066  eventsManager.handleGameEvents();
1067 
1068  // If the user is configuring the keys then don't respond.
1069  if (!keyboard.isEnabled() || settings.awayMode)
1070  {
1071  BLOCK_END("Game::handleInput 1")
1072  return;
1073  }
1074 
1075  // If pressed outfits keys, stop processing keys.
1076  if (inputManager.isActionActive(InputAction::WEAR_OUTFIT)
1077  || inputManager.isActionActive(InputAction::COPY_OUTFIT)
1078  || ((setupWindow != nullptr) && setupWindow->isWindowVisible()))
1079  {
1080  BLOCK_END("Game::handleInput 1")
1081  return;
1082  }
1083 
1084  handleMove();
1085  InputManager::handleRepeat();
1086  BLOCK_END("Game::handleInput 1")
1087 }
Definition: game.h:64
void handleMove()
Definition: game.cpp:920
void handleInput()
Definition: game.cpp:1060
void logic()
Definition: game.cpp:663
EventsManager eventsManager
InputManager inputManager
Joystick * joystick
Definition: joystick.cpp:43
KeyboardConfig keyboard

References Settings::awayMode, BLOCK_END, BLOCK_START, InputAction::COPY_OUTFIT, eventsManager, EventsManager::handleGameEvents(), handleMove(), InputManager::handleRepeat(), inputManager, InputManager::isActionActive(), KeyboardConfig::isEnabled(), Window::isWindowVisible(), joystick, keyboard, Joystick::logic(), settings, setupWindow, and InputAction::WEAR_OUTFIT.

Referenced by EventsManager::handleEvents(), and logic().

◆ handleMove()

void Game::handleMove ( )

Definition at line 920 of file game.cpp.

921 {
922  BLOCK_START("Game::handleMove")
923  if (localPlayer == nullptr)
924  {
925  BLOCK_END("Game::handleMove")
926  return;
927  }
928 
929  // Moving player around
930  if ((chatWindow != nullptr) &&
931  (quitDialog == nullptr) &&
932  localPlayer->canMove() &&
933  !chatWindow->isInputFocused() &&
934  !InventoryWindow::isAnyInputFocused() &&
935  !popupMenu->isPopupVisible())
936  {
937  NpcDialog *const dialog = NpcDialog::getActive();
938  if (dialog != nullptr)
939  {
940  BLOCK_END("Game::handleMove")
941  return;
942  }
943 
944  // Ignore input if either "ignore" key is pressed
945  // Stops the character moving about if the user's window manager
946  // uses "ignore+arrow key" to switch virtual desktops.
947  if (inputManager.isActionActive(InputAction::IGNORE_INPUT_1) ||
948  inputManager.isActionActive(InputAction::IGNORE_INPUT_2))
949  {
950  BLOCK_END("Game::handleMove")
951  return;
952  }
953 
954  unsigned char direction = 0;
955 
956  // Translate pressed keys to movement and direction
957  if (inputManager.isActionActive(InputAction::MOVE_UP) ||
958  ((joystick != nullptr) && joystick->isUp()))
959  {
960  direction |= BeingDirection::UP;
961  setValidSpeed();
963  }
965  ((joystick != nullptr) && joystick->isDown()))
966  {
967  direction |= BeingDirection::DOWN;
968  setValidSpeed();
970  }
971 
973  ((joystick != nullptr) && joystick->isLeft()))
974  {
975  direction |= BeingDirection::LEFT;
976  setValidSpeed();
978  }
980  ((joystick != nullptr) && joystick->isRight()))
981  {
982  direction |= BeingDirection::RIGHT;
983  setValidSpeed();
985  }
987  {
988  direction = localPlayer->getDirection();
989  setValidSpeed();
991  }
992 
997  || direction == 0)
998  {
999  moveInDirection(direction);
1000  }
1001  }
1002  BLOCK_END("Game::handleMove")
1003 }
uint8_t getDirection() const
Definition: being.h:494
static void moveInDirection(const unsigned char direction)
Definition: game.cpp:1005
void setValidSpeed()
Definition: game.cpp:1273
bool isActionActive(const InputActionT index) const
bool isRight() const
Definition: joystick.h:114
bool isDown() const
Definition: joystick.h:108
bool isLeft() const
Definition: joystick.h:111
void cancelFollow()
static NpcDialog * getActive()
Definition: npcdialog.cpp:852
QuitDialog * quitDialog
Definition: game.cpp:158
PopupMenu * popupMenu
Definition: popupmenu.cpp:103

References BLOCK_END, BLOCK_START, LocalPlayer::cancelFollow(), LocalPlayer::canMove(), chatWindow, BeingDirection::DOWN, InputAction::EMOTE, NpcDialog::getActive(), Being::getDirection(), InputAction::HOMUN_EMOTE, InputAction::IGNORE_INPUT_1, InputAction::IGNORE_INPUT_2, inputManager, InputManager::isActionActive(), InventoryWindow::isAnyInputFocused(), Joystick::isDown(), ChatWindow::isInputFocused(), Joystick::isLeft(), Popup::isPopupVisible(), Joystick::isRight(), Joystick::isUp(), joystick, BeingDirection::LEFT, localPlayer, InputAction::MOVE_DOWN, InputAction::MOVE_FORWARD, InputAction::MOVE_LEFT, InputAction::MOVE_RIGHT, InputAction::MOVE_UP, moveInDirection(), InputAction::PET_EMOTE, popupMenu, quitDialog, BeingDirection::RIGHT, setValidSpeed(), InputAction::STOP_ATTACK, and BeingDirection::UP.

Referenced by handleInput().

◆ instance()

static Game* Game::instance ( )
inlinestatic

◆ logic()

void Game::logic ( )

This method takes the game a small step further. It is called 100 times per second.

Definition at line 663 of file game.cpp.

664 {
665  BLOCK_START("Game::logic")
666  handleInput();
667 
668  // Handle all necessary game logic
669  if (actorManager != nullptr)
670  actorManager->logic();
671  if (particleEngine != nullptr)
673  if (mCurrentMap != nullptr)
674  mCurrentMap->update(1);
675 
676  BLOCK_END("Game::logic")
677 }
void update()
Definition: useragent.cpp:32

References actorManager, BLOCK_END, BLOCK_START, handleInput(), ActorManager::logic(), mCurrentMap, particleEngine, ParticleEngine::update(), and Map::update().

◆ moveInDirection()

void Game::moveInDirection ( const unsigned char  direction)
static

Definition at line 1005 of file game.cpp.

1006 {
1007  if (viewport == nullptr)
1008  return;
1009 
1010  if (settings.cameraMode == 0U)
1011  {
1012  if (localPlayer != nullptr)
1013  localPlayer->specialMove(direction);
1014  }
1015  else
1016  {
1017  int dx = 0;
1018  int dy = 0;
1019  if ((direction & BeingDirection::LEFT) != 0)
1020  dx = -5;
1021  else if ((direction & BeingDirection::RIGHT) != 0)
1022  dx = 5;
1023 
1024  if ((direction & BeingDirection::UP) != 0)
1025  dy = -5;
1026  else if ((direction & BeingDirection::DOWN) != 0)
1027  dy = 5;
1028  viewport->moveCamera(dx, dy);
1029  }
1030 }
void specialMove(const unsigned char direction)
unsigned int cameraMode
Definition: settings.h:144
void moveCamera(const int dx, const int dy)
Definition: viewport.cpp:1070

References Settings::cameraMode, BeingDirection::DOWN, BeingDirection::LEFT, localPlayer, Viewport::moveCamera(), BeingDirection::RIGHT, settings, LocalPlayer::specialMove(), BeingDirection::UP, and viewport.

Referenced by handleMove().

◆ resetAdjustLevel()

void Game::resetAdjustLevel ( )

Definition at line 889 of file game.cpp.

890 {
891  if (!mAdjustPerfomance)
892  return;
893 
895  switch (mAdjustLevel)
896  {
897  case 1:
898  config.setValue("beingopacity",
899  config.getBoolValue("beingopacity"));
900  break;
901  case 2:
902  config.setValue("beingopacity",
903  config.getBoolValue("beingopacity"));
905  "particleEmitterSkip") + 1;
906  break;
907  default:
908  case 3:
909  config.setValue("beingopacity",
910  config.getBoolValue("beingopacity"));
912  "particleEmitterSkip") + 1;
913  config.setValue("alphaCache",
914  config.getBoolValue("alphaCache"));
915  break;
916  }
917  mAdjustLevel = 0;
918 }

References adjustDelay, config, cur_time, ParticleEngine::emitterSkip, Configuration::getBoolValue(), Configuration::getIntValue(), mAdjustLevel, mAdjustPerfomance, mNextAdjustTime, and Configuration::setValue().

Referenced by SetupWindow::action(), changeMap(), and ~Game().

◆ saveScreenshot()

bool Game::saveScreenshot ( SDL_Surface *const  screenshot,
const std::string &  prefix 
)
static

Definition at line 563 of file game.cpp.

565 {
566  std::string screenshotDirectory = settings.screenshotDir;
567  if (mkdir_r(screenshotDirectory.c_str()) != 0)
568  {
569  logger->log("Directory %s doesn't exist and can't be created! "
570  "Setting screenshot directory to home.",
571  screenshotDirectory.c_str());
572  screenshotDirectory = std::string(VirtFs::getUserDir());
573  }
574 
575  // Search for an unused screenshot name
576  std::stringstream filename;
577  std::fstream testExists;
578 
579  time_t rawtime;
580  char buffer [100];
581  time(&rawtime);
582  tm *const timeinfo = localtime(&rawtime);
583  strftime(buffer, 99, "%Y-%m-%d_%H-%M-%S", timeinfo);
584 
585  const std::string serverName = settings.serverName;
586  std::string screenShortStr;
587  if (prefix.empty())
588  {
589  if (serverName.empty())
590  {
591  screenShortStr = strprintf("%s_Screenshot_%s_",
592  branding.getValue("appName", "ManaPlus").c_str(),
593  buffer);
594  }
595  else
596  {
597  screenShortStr = strprintf("%s_Screenshot_%s_%s_",
598  branding.getValue("appName", "ManaPlus").c_str(),
599  serverName.c_str(), buffer);
600  }
601 
602  bool found = false;
603  static unsigned int screenshotCount = 0;
604  do
605  {
606  screenshotCount++;
607  filename.str("");
608  filename << screenshotDirectory << "/";
609  filename << screenShortStr << screenshotCount << ".png";
610  testExists.open(filename.str().c_str(), std::ios::in);
611  found = !testExists.is_open();
612  testExists.close();
613  }
614  while (!found);
615  }
616  else
617  {
618  screenShortStr = prefix;
619  filename.str("");
620  filename << screenshotDirectory << "/";
621  filename << screenShortStr;
622  }
623 
624  const std::string fileNameStr = filename.str();
625  const bool success = PngLib::writePNG(screenshot, fileNameStr);
626 #ifdef __native_client__
627  std::string nacScreenshotlDir = fileNameStr;
628  cutFirst(nacScreenshotlDir, "/persistent");
629  naclPostMessage("copy-from-persistent", nacScreenshotlDir);
630  logger->log("nacl screenshot path: " + nacScreenshotlDir);
631 #endif // __native_client__
632 
633  if (success)
634  {
635  if (localChatTab != nullptr)
636  {
637  // TRANSLATORS: save file message
638  std::string str = strprintf(_("Screenshot saved as %s"),
639  fileNameStr.c_str());
640  localChatTab->chatLog(str,
644  }
645  }
646  else
647  {
648  if (localChatTab != nullptr)
649  {
650  // TRANSLATORS: save file message
651  localChatTab->chatLog(_("Saving screenshot failed!"),
655  }
656  logger->log1("Error: could not save screenshot.");
657  }
658 
660  return success;
661 }
std::string getValue(const std::string &key, const std::string &deflt) const
void log1(const char *const log_text)
Definition: logger.cpp:238
std::string screenshotDir
Definition: settings.h:115
Configuration branding
#define MSDL_FreeSurface(surface)
Definition: debug.h:54
int mkdir_r(const char *const pathname)
Create a directory, making leading components first if necessary.
Definition: mkdir.cpp:109
bool writePNG(SDL_Surface *const surface, const std::string &filename)
Definition: pnglib.cpp:37
const char * getUserDir()
Definition: fs.cpp:84
void cutFirst(std::string &str1, const std::string &str2)
std::string strprintf(const char *const format,...)

References _, branding, ChatMsgType::BY_SERVER, ChatTab::chatLog(), cutFirst(), VirtFs::getUserDir(), ConfigurationObject::getValue(), IgnoreRecord_false, localChatTab, Logger::log(), Logger::log1(), logger, mkdir_r(), MSDL_FreeSurface, Actions::screenshot(), Settings::screenshotDir, Settings::serverName, settings, strprintf(), TryRemoveColors_true, and PngLib::writePNG().

Referenced by createScreenshot().

◆ setAdjustLevel()

void Game::setAdjustLevel ( const int  n)
inline

Definition at line 119 of file game.h.

120  { mAdjustLevel = n; }

References mAdjustLevel.

◆ setValidSpeed()

void Game::setValidSpeed ( )

Definition at line 1273 of file game.cpp.

1274 {
1275  clearKeysArray();
1276  mValidSpeed = true;
1277 }

References clearKeysArray(), and mValidSpeed.

Referenced by OutfitWindow::action(), ChatWindow::chatInput(), handleMove(), and Viewport::validateSpeed().

◆ slowLogic()

void Game::slowLogic ( )

Definition at line 679 of file game.cpp.

680 {
681  BLOCK_START("Game::slowLogic")
682  if (localPlayer != nullptr)
684  const time_t time = cur_time;
685  if (mTime != time)
686  {
687  if (valTest(Updated))
688  mValidSpeed = false;
689 
690  mTime = time + 1;
691  if (debugWindow != nullptr)
693  if (killStats != nullptr)
694  killStats->update();
695  if (socialWindow != nullptr)
697  if (whoIsOnline != nullptr)
700  if (killStats != nullptr)
702 
703  if (time > mTime2 || mTime2 - time > 10)
704  {
705  mTime2 = time + 10;
708  }
709  if (effectManager != nullptr)
710  effectManager->logic();
711  }
712 
715 
716 #ifdef TMWA_SUPPORT
717  if (shopWindow != nullptr)
719  if (guildManager != nullptr)
721 #endif // TMWA_SUPPORT
722 
723  if (skillDialog != nullptr)
725 
727 
728  // Handle network stuff
729  if (!gameHandler->isConnected())
730  {
732  return; // Not a problem here
733 
734  if (client->getState() != State::ERROR)
735  {
736  if (disconnectedDialog == nullptr)
737  {
738  // TRANSLATORS: error message text
739  errorMessage = _("The connection to the server was lost.");
741  // TRANSLATORS: error message header
742  _("Network Error"),
743  errorMessage,
744  Modal_false);
747  }
748  }
749 
750  if ((viewport != nullptr) && !errorMessage.empty())
751  {
752  const Map *const map = viewport->getMap();
753  if (map != nullptr)
754  map->saveExtraLayer();
755  }
759  if (client->getState() != State::ERROR)
760  errorMessage.clear();
761  }
762  else
763  {
764  if (gameHandler->mustPing()
765  && get_elapsed_time1(mPing) > 3000)
766  {
767  mPing = tick_time;
769  }
770 
771  if (mAdjustPerfomance)
773  if (disconnectedDialog != nullptr)
774  {
776  disconnectedDialog = nullptr;
777  }
778  }
779  BLOCK_END("Game::slowLogic")
780 }
static void reReadConfig()
Definition: being.cpp:3431
void slowLogic()
static void delayedLoad()
static Window * openErrorDialog(const std::string &header, const std::string &message, const Modal modal)
static void closeDialogs()
void adjustPerfomance()
Definition: game.cpp:782
void slowLogic()
Definition: game.cpp:679
void update()
Definition: killstats.cpp:365
void recalcStats()
Definition: killstats.cpp:311
virtual bool isConnected() const =0
virtual bool mustPing() const =0
static void update()
void updateTimes()
void slowLogic()
Map * getMap() const
Definition: viewport.h:135
void slowLogic()
virtual void requestMoveToTop()
Definition: widget.cpp:213
void addActionListener(ActionListener *const actionListener)
Definition: widget.cpp:252
virtual void scheduleDelete()
Definition: window.cpp:831
#define valTest(num)
DebugWindow * debugWindow
Definition: debugwindow.cpp:43
std::string errorMessage
Definition: client.cpp:116
ErrorListener errorListener
KillStats * killStats
Definition: killstats.cpp:45
const bool Modal_false
Definition: modal.h:30
@ ERROR
Definition: state.h:35
void setFramerate(const unsigned int fpsLimit)
ShopWindow * shopWindow
Definition: shopwindow.cpp:101
SkillDialog * skillDialog
Definition: skilldialog.cpp:66
int get_elapsed_time1(const int startTime)
Definition: timer.cpp:105
WhoIsOnline * whoIsOnline
Definition: whoisonline.cpp:82

References _, Widget::addActionListener(), adjustDelay, adjustPerfomance(), BLOCK_END, BLOCK_START, State::CHANGE_MAP, client, DialogsManager::closeDialogs(), config, cur_time, debugWindow, DelayedManager::delayedLoad(), disconnectedDialog, effectManager, State::ERROR, errorListener, errorMessage, gameHandler, get_elapsed_time1(), Configuration::getIntValue(), Viewport::getMap(), Graphics::getOpenGL(), Client::getState(), guildManager, Net::GameHandler::isConnected(), killStats, localPlayer, EffectManager::logic(), mAdjustPerfomance, mainGraphics, mNextAdjustTime, Modal_false, mPing, mTime, mTime2, Net::GameHandler::mustPing(), mValidSpeed, DialogsManager::openErrorDialog(), Net::GameHandler::ping(), KillStats::recalcStats(), RENDER_SOFTWARE, Widget::requestMoveToTop(), Being::reReadConfig(), Map::saveExtraLayer(), Window::scheduleDelete(), serverConfig, WindowManager::setFramerate(), shopWindow, skillDialog, LocalPlayer::slowLogic(), DebugWindow::slowLogic(), SkillDialog::slowLogic(), SocialWindow::slowLogic(), WhoIsOnline::slowLogic(), GuildManager::slowLogic(), socialWindow, tick_time, KillStats::update(), PacketCounters::update(), ShopWindow::updateTimes(), valTest, viewport, whoIsOnline, and Configuration::writeUpdated().

◆ updateFrameRate()

void Game::updateFrameRate ( int  fpsLimit)

Definition at line 1032 of file game.cpp.

1033 {
1034  if (fpsLimit == 0)
1035  {
1036  if (settings.awayMode)
1037  {
1040  {
1041  fpsLimit = config.getIntValue("fpslimit");
1042  }
1043  else
1044  {
1045  fpsLimit = config.getIntValue("altfpslimit");
1046  }
1047  }
1048  else
1049  {
1050  fpsLimit = config.getIntValue("fpslimit");
1051  }
1052  }
1053  WindowManager::setFramerate(fpsLimit);
1055 }
bool mouseFocused
Definition: settings.h:156
KeyboardFocusT inputFocused
Definition: settings.h:155

References adjustDelay, Settings::awayMode, config, cur_time, Configuration::getIntValue(), Settings::inputFocused, mNextAdjustTime, Settings::mouseFocused, WindowManager::setFramerate(), settings, and KeyboardFocus::Unfocused.

Referenced by GameModifiers::changeAwayMode(), and EventsManager::handleActive().

◆ updateHistory()

void Game::updateHistory ( const SDL_Event &  event)

Definition at line 1192 of file game.cpp.

1193 {
1194  if ((localPlayer == nullptr) || (settings.attackType == 0U))
1195  return;
1196 
1197  if (CAST_S32(event.key.keysym.sym) != -1)
1198  {
1199  bool old = false;
1200 
1201  const InputActionT key = KeyboardConfig::getKeyIndex(event, 1);
1202  const time_t time = cur_time;
1203  int idx = -1;
1204  for (int f = 0; f < MAX_LASTKEYS; f ++)
1205  {
1206  LastKey &lastKey = mLastKeys[f];
1207  if (lastKey.key == key)
1208  {
1209  idx = f;
1210  old = true;
1211  break;
1212  }
1213  else if (idx >= 0 && lastKey.time < mLastKeys[idx].time)
1214  {
1215  idx = f;
1216  }
1217  }
1218  if (idx < 0)
1219  {
1220  idx = 0;
1221  for (int f = 0; f < MAX_LASTKEYS; f ++)
1222  {
1223  LastKey &lastKey = mLastKeys[f];
1224  if (lastKey.key == InputAction::NO_VALUE ||
1225  lastKey.time < mLastKeys[idx].time)
1226  {
1227  idx = f;
1228  }
1229  }
1230  }
1231 
1232  if (idx < 0)
1233  idx = 0;
1234 
1235  LastKey &keyIdx = mLastKeys[idx];
1236  if (!old)
1237  {
1238  keyIdx.time = time;
1239  keyIdx.key = key;
1240  keyIdx.cnt = 0;
1241  }
1242  else
1243  {
1244  keyIdx.cnt++;
1245  }
1246  }
1247 }
#define CAST_S32
Definition: cast.h:30
static InputActionT getKeyIndex(const SDL_Event &event, const int grp)
InputAction ::T InputActionT
Definition: inputaction.h:717

References Settings::attackType, CAST_S32, LastKey::cnt, cur_time, KeyboardConfig::getKeyIndex(), LastKey::key, localPlayer, MAX_LASTKEYS, mLastKeys, InputAction::NO_VALUE, settings, and LastKey::time.

◆ videoResized()

void Game::videoResized ( const int  width,
const int  height 
)
static

Definition at line 1289 of file game.cpp.

1290 {
1291  if (viewport != nullptr)
1292  viewport->setSize(width, height);
1293  if (windowMenu != nullptr)
1294  windowMenu->setPosition(width - windowMenu->getWidth(), 0);
1295 }
void setPosition(const int x, const int y)
Definition: widget.cpp:161
int getWidth() const
Definition: widget.h:221

References Widget::getWidth(), Widget::setPosition(), Widget::setSize(), viewport, and windowMenu.

Referenced by WindowManager::resizeVideo().

Field Documentation

◆ mAdjustLevel

int Game::mAdjustLevel
private

Definition at line 148 of file game.h.

Referenced by adjustPerfomance(), resetAdjustLevel(), and setAdjustLevel().

◆ mAdjustPerfomance

bool Game::mAdjustPerfomance
private

Definition at line 149 of file game.h.

Referenced by resetAdjustLevel(), and slowLogic().

◆ mCurrentMap

Map* Game::mCurrentMap
private

Definition at line 143 of file game.h.

Referenced by changeMap(), getCurrentMap(), logic(), and ~Game().

◆ mInstance

Game * Game::mInstance = 0
staticprivate

Definition at line 155 of file game.h.

Referenced by clearInstance(), Game(), instance(), and ~Game().

◆ mLastKeys

LastKey Game::mLastKeys[MAX_LASTKEYS]
private

Definition at line 146 of file game.h.

Referenced by checkKeys(), clearKeysArray(), and updateHistory().

◆ mLowerCounter

int Game::mLowerCounter
private

Definition at line 150 of file game.h.

Referenced by adjustPerfomance().

◆ mMapName

std::string Game::mMapName
private

Definition at line 144 of file game.h.

Referenced by changeMap(), and getCurrentMapName().

◆ mNextAdjustTime

time_t Game::mNextAdjustTime
private

Definition at line 147 of file game.h.

Referenced by adjustPerfomance(), resetAdjustLevel(), slowLogic(), and updateFrameRate().

◆ mPing

int Game::mPing
private

Definition at line 151 of file game.h.

Referenced by slowLogic().

◆ mTime

time_t Game::mTime
private

Definition at line 152 of file game.h.

Referenced by slowLogic().

◆ mTime2

time_t Game::mTime2
private

Definition at line 153 of file game.h.

Referenced by slowLogic().

◆ mValidSpeed

bool Game::mValidSpeed
private

Definition at line 145 of file game.h.

Referenced by checkKeys(), getValidSpeed(), setValidSpeed(), and slowLogic().


The documentation for this class was generated from the following files: