The Battle for Wesnoth  1.17.0-dev
playmp_controller.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2006 - 2021
3  by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
4  Copyright (C) 2003 by David White <dave@whitevine.net>
5  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
6 
7  This program is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2 of the License, or
10  (at your option) any later version.
11  This program is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY.
13 
14  See the COPYING file for more details.
15 */
16 
17 #include "playmp_controller.hpp"
18 
19 #include "actions/undo.hpp"
20 #include "countdown_clock.hpp"
21 #include "display_chat_manager.hpp"
22 #include "floating_label.hpp"
23 #include "game_end_exceptions.hpp"
25 #include "gettext.hpp"
28 #include "log.hpp"
29 #include "mp_ui_alerts.hpp"
30 #include "playturn.hpp"
31 #include "preferences/game.hpp"
32 #include "preferences/general.hpp"
33 #include "replay_helper.hpp"
34 #include "resources.hpp"
35 #include "savegame.hpp"
37 #include "synced_context.hpp"
38 #include "wesnothd_connection.hpp"
39 #include "whiteboard/manager.hpp"
40 
41 static lg::log_domain log_engine("engine");
42 #define LOG_NG LOG_STREAM(info, log_engine)
43 
45  : playsingle_controller(level, state_of_game, mp_info && mp_info->skip_replay)
46  , network_processing_stopped_(false)
47  , blindfold_(*gui_, mp_info && mp_info->skip_replay_blindfolded)
48  , mp_info_(mp_info)
49 {
50  // upgrade hotkey handler to the mp (network enabled) version
51  hotkey_handler_.reset(new hotkey_handler(*this, saved_game_));
52 
53  // turn_data_.set_host(is_host);
55  if(!mp_info || mp_info->current_turn <= turn()) {
56  skip_replay_ = false;
57  }
58 
59  if(gui_->is_blindfolded() && gamestate().first_human_team_ != -1) {
61  }
62 }
63 
65 {
66  // halt and cancel the countdown timer
67  try {
69  } catch(...) {
70  }
71 }
72 
74 {
76  LOG_NG << "network processing activated again";
77 }
78 
80 {
82  LOG_NG << "network processing stopped";
83 }
84 
86 {
88 }
89 
91 {
92  if(gui_->is_blindfolded()) {
94  LOG_NG << "Taking off the blindfold now " << std::endl;
95  gui_->redraw_everything();
96  }
97 }
98 
100 {
101  if(is_host()) {
102  end_turn_enable(true);
103  }
104 
105  while(end_turn_ == END_TURN_NONE) {
106  config cfg;
107  if(network_reader_.read(cfg)) {
109  end_turn();
110  }
111  }
112 
113  play_slice();
114  }
115 }
116 
118 {
119  LOG_NG << "playmp::play_human_turn...\n";
120  assert(!linger_);
121  assert(gamestate_->init_side_done());
122  assert(gamestate().gamedata_.phase() == game_data::PLAY);
123 
124  mp_ui_alerts::turn_changed(current_team().current_player());
125 
126  LOG_NG << "events::commands_disabled=" << events::commands_disabled << "\n";
127 
129 
130  const std::unique_ptr<countdown_clock> timer(saved_game_.mp_settings().mp_countdown
132  : nullptr);
133 
135 
136  if(undo_stack().can_undo()) {
137  // If we reload a networked mp game we cannot undo moves made before the save
138  // because other players already received them
139  if(!current_team().auto_shroud_updates()) {
141  }
142  undo_stack().clear();
143  }
144 
146  execute_gotos();
147  }
148 
149  end_turn_enable(true);
150 
151  while(!should_return_to_play_side()) {
152  try {
157  // Clean undo stack if turn has to be restarted (losing control)
158  if(undo_stack().can_undo()) {
159  font::floating_label flabel(_("Undoing moves not yet transmitted to the server."));
160 
161  color_t color{255, 255, 255, SDL_ALPHA_OPAQUE};
162  flabel.set_color(color);
163  SDL_Rect rect = gui_->map_area();
164  flabel.set_position(rect.w / 2, rect.h / 2);
165  flabel.set_lifetime(2500);
166  flabel.set_clip_rect(rect);
167 
168  font::add_floating_label(flabel);
169  }
170 
171  while(undo_stack().can_undo()) {
172  undo_stack().undo();
173  }
174  }
175 
176  if(timer) {
177  bool time_left = timer->update();
178  if(!time_left) {
180  }
181  }
182  } catch(...) {
184  throw;
185  }
186 
188  }
189 }
190 
192 {
193  LOG_NG << "playmp::play_human_turn...\n";
194 
196 
197  while(!should_return_to_play_side()) {
198  try {
201  SDL_Delay(1);
202  } catch(...) {
204  throw;
205  }
206 
208  }
209 }
210 
212 {
213  // Modify the end-turn button
214  if(!is_host()) {
215  std::shared_ptr<gui::button> btn_end = gui_->find_action_button("button-endturn");
216  btn_end->enable(false);
217  }
218 
219  gui_->get_theme().refresh_title2("button-endturn", "title2");
220  gui_->invalidate_theme();
221  gui_->redraw_everything();
222 }
223 
225 {
226  // revert the end-turn button text to its normal label
227  gui_->get_theme().refresh_title2("button-endturn", "title");
228  gui_->invalidate_theme();
229  gui_->redraw_everything();
230  gui_->set_game_mode(game_display::RUNNING);
231 }
232 
234 {
235  LOG_NG << "beginning end-of-scenario linger\n";
236  linger_ = true;
237 
238  // If we need to set the status depending on the completion state
239  // we're needed here.
240  gui_->set_game_mode(game_display::LINGER);
241 
242  // End all unit moves
244 
246  assert(is_regular_game_end());
247 
248  if(get_end_level_data().transient.reveal_map) {
249  // Change the view of all players and observers
250  // to see the whole map regardless of shroud and fog.
251  update_gui_to_player(gui_->viewing_team(), true);
252  }
253 
254  bool quit;
255  do {
256  quit = true;
257  try {
258  // reimplement parts of play_side()
263  LOG_NG << "finished human turn" << std::endl;
264  } catch(const savegame::load_game_exception&) {
265  LOG_NG << "caught load-game-exception" << std::endl;
266  // this should not happen, the option to load a game is disabled
267  throw;
268  } catch(const leavegame_wesnothd_error& e) {
269  scoped_savegame_snapshot snapshot(*this);
271 
272  if(e.message == "") {
273  save.save_game_interactive(_("A network disconnection has occurred, and the game cannot continue. Do you want to save the game?"),
275  } else {
277  _("This game has been ended.\nReason: ") + e.message + _("\nDo you want to save the game?"),
279  }
280  throw;
281  } catch(const ingame_wesnothd_error&) {
282  LOG_NG << "caught network-error-exception" << std::endl;
283  quit = false;
284  }
285  } while(!quit);
286 
288 
289  LOG_NG << "ending end-of-scenario linger\n";
290 }
291 
293 {
294  // If the host is here we'll never leave since we wait for the host to
295  // upload the next scenario.
296  assert(!is_host());
297 
298  config cfg;
300 
301  while(true) {
302  try {
303  bool res = false;
306 
308  });
309 
311  break;
312  } else {
314  }
315  } catch(const quit_game_exception&) {
316  network_reader_.set_source([this](config& cfg) { return receive_from_wesnothd(cfg); });
318  throw;
319  }
320  }
321 
322  network_reader_.set_source([this](config& cfg) { return receive_from_wesnothd(cfg); });
323 }
324 
326 {
328  // time_left + turn_bonus + (action_bonus * number of actions done)
329  const int new_time_in_secs = (current_team().countdown_time() / 1000)
332 
333  const int new_time
334  = 1000 * std::min<int>(new_time_in_secs, saved_game_.mp_settings().mp_countdown_reservoir_time);
335 
337  current_team().set_countdown_time(new_time);
338 
340  }
341 
342  LOG_NG << "playmp::after_human_turn...\n";
343 
344  // Normal post-processing for human turns (clear undos, end the turn, etc.)
346 
347  // send one more time to make sure network is up-to-date.
349 }
350 
352 {
353  LOG_NG << "is networked...\n";
354 
355  end_turn_enable(false);
357 
361  if(!mp_info_ || mp_info_->current_turn == turn()) {
362  skip_replay_ = false;
363  }
364  }
365 
369  }
370  }
371 
372  LOG_NG << "finished networked...\n";
373 }
374 
375 void playmp_controller::process_oos(const std::string& err_msg) const
376 {
377  // Notify the server of the oos error.
378  config cfg;
379  config& info = cfg.add_child("info");
380  info["type"] = "termination";
381  info["condition"] = "out of sync";
382  send_to_wesnothd(cfg);
383 
384  std::stringstream temp_buf;
385  std::vector<std::string> err_lines = utils::split(err_msg, '\n');
386  temp_buf << _("The game is out of sync, and cannot continue. There are a number of reasons this could happen: this "
387  "can occur if you or another player have modified their game settings. This may mean one of the "
388  "players is attempting to cheat. It could also be due to a bug in the game, but this is less "
389  "likely.\n\nDo you want to save an error log of your game?");
390 
391  if(!err_msg.empty()) {
392  temp_buf << " \n \n"; // and now the "Details:"
393  for(std::vector<std::string>::iterator i = err_lines.begin(); i != err_lines.end(); ++i) {
394  temp_buf << *i << '\n';
395  }
396  temp_buf << " \n";
397  }
398 
399  scoped_savegame_snapshot snapshot(*this);
401 
403 }
404 
405 void playmp_controller::handle_generic_event(const std::string& name)
406 {
408 
409  if(name == "ai_user_interact") {
412  } else if(name == "ai_gamestate_changed") {
414  } else if(name == "host_transfer") {
415  assert(mp_info_);
416  mp_info_->is_host = true;
417  if(linger_) {
418  end_turn_enable(true);
419  gui_->invalidate_theme();
420  }
421  }
422 }
424 {
425  return !mp_info_ || mp_info_->is_host;
426 }
427 
429 {
430  gui_->get_chat_manager().add_chat_message(std::time(nullptr), "", 0,
431  _("This side is in an idle state. To proceed with the game, it must be assigned to another controller. You may "
432  "use :droid, :control or :give_control for example."),
434 }
435 
437 {
438  // mouse_handler expects at least one team for linger mode to work.
439  assert(is_regular_game_end());
440  if(!get_end_level_data().transient.linger_mode || get_teams().empty() || gui_->video().faked()) {
441  const bool has_next_scenario
442  = !gamestate().gamedata_.next_scenario().empty() && gamestate().gamedata_.next_scenario() != "null";
443  if(!is_host() && has_next_scenario) {
444  // If we continue without lingering we need to
445  // make sure the host uploads the next scenario
446  // before we attempt to download it.
447  wait_for_upload();
448  }
449  } else {
450  linger();
451  }
452 }
453 
455 {
456  undo_stack().clear();
457  resources::recorder->add_surrender(side_number);
459 }
460 
462 {
464  assert(res != turn_info::PROCESS_END_TURN);
465 
466  if(res == turn_info::PROCESS_END_LINGER) {
467  // Probably some bad OOS, but there is currently no way to recover from this.
468  throw ingame_wesnothd_error("");
469  }
470 
472  player_type_changed_ = true;
473  }
474 }
475 
477 {
479 }
480 
481 void playmp_controller::play_slice(bool is_delay_enabled)
482 {
483  if(!linger_ && !is_replay()) {
484  // receive chat during animations and delay
485  process_network_data(true);
486  // cannot use turn_data_.send_data() here.
488  }
489 
490  playsingle_controller::play_slice(is_delay_enabled);
491 }
492 
494 {
496  return;
497  }
498 
500  config cfg;
501 
502  if(!resources::recorder->at_end()) {
504  } else if(network_reader_.read(cfg)) {
505  res = turn_data_.process_network_data(cfg, chat_only);
506  }
507 
509  network_reader_.push_front(std::move(cfg));
510  } else if(res == turn_info::PROCESS_RESTART_TURN) {
511  player_type_changed_ = true;
512  } else if(res == turn_info::PROCESS_END_TURN) {
514  } else if(res == turn_info::PROCESS_END_LEVEL) {
515  } else if(res == turn_info::PROCESS_END_LINGER) {
516  replay::process_error("Received unexpected next_scenario during the game");
517  }
518 }
519 
521 {
522  return mp_info_ != nullptr;
523 }
524 
525 void playmp_controller::send_to_wesnothd(const config& cfg, const std::string&) const
526 {
527  if(mp_info_ != nullptr) {
529  }
530 }
531 
533 {
534  if(mp_info_ != nullptr) {
535  return mp_info_->connection.receive_data(cfg);
536  } else {
537  return false;
538  }
539 }
bool disable_auto_moves()
Definition: general.cpp:949
void send_data(const configr_of &request)
Queues the given data to be sent to the server.
void clear()
Clears the stack of undoable (and redoable) actions.
Definition: undo.cpp:221
void set_all_units_user_end_turn()
Definition: game_board.cpp:86
void process_oos(const std::string &err_msg) const override
Asks the user whether to continue on an OOS error.
void maybe_linger() override
void set_countdown_time(const int amount) const
Definition: team.hpp:223
static bool run_and_store(const std::string &commandname, const config &data, bool use_undo=true, bool show=true, synced_command::error_handler_function error_handler=default_error_function)
int countdown_time() const
Definition: team.hpp:222
events::generic_event & host_transfer()
Definition: playturn.hpp:62
void turn_changed(const std::string &player_name)
void add_countdown_update(int value, int team)
Definition: replay.cpp:237
static lg::log_domain log_engine("engine")
unsigned current_turn
void surrender(int side_number)
std::unique_ptr< game_display > gui_
void process_network_data(bool chat_only=false)
void set_clip_rect(const SDL_Rect &r)
logger & info()
Definition: log.cpp:89
bool is_networked_mp() const override
void send_to_wesnothd(const config &cfg, const std::string &packet_type="unknown") const override
std::unique_ptr< hotkey_handler > hotkey_handler_
int first_human_team_
Definition: game_state.hpp:75
virtual void play_linger_turn()
static void progress(loading_stage stage=loading_stage::none)
void set_lifetime(int lifetime, int fadeout=100)
void sync_non_undoable()
Definition: replay.cpp:913
PROCESS_DATA_RESULT sync_network()
Definition: playturn.cpp:62
void undo()
Undoes the top action on the undo stack.
Definition: undo.cpp:349
And endturn was required eigher by the player, by the ai or by [end_turn].
virtual void play_slice(bool is_delay_enabled=true)
Class for "normal" midgame saves.
Definition: savegame.hpp:252
virtual void handle_generic_event(const std::string &name) override
bool receive_data(config &result)
Receives the next pending data pack from the server, if available.
REPLAY_RETURN do_replay(bool one_move)
Definition: replay.cpp:684
Contains the exception interfaces used to signal completion of a scenario, campaign or turn...
PROCESS_DATA_RESULT process_network_data_from_reader()
Definition: playturn.cpp:114
bool save_game_interactive(const std::string &message, DIALOG_TYPE dialog_type)
Save a game interactively through the savegame dialog.
Definition: savegame.cpp:384
static std::string _(const char *str)
Definition: gettext.hpp:93
void set_source(source_type source)
void send_data()
Definition: playturn.cpp:81
static config get_update_shroud()
Records that the player has manually updated fog/shroud.
PROCESS_DATA_RESULT
Definition: playturn.hpp:37
void pull_remote_choice() override
bool can_undo() const
std::unique_ptr< game_state > gamestate_
no linger overlay, show fog and shroud.
int action_bonus_count() const
Definition: team.hpp:225
virtual void on_not_observer() override
saved_game & saved_game_
void end_turn_enable(bool enable)
void send_user_choice() override
virtual void check_objectives() override
virtual bool should_return_to_play_side() const override
void throw_quit_game_exception()
void wait_for_upload()
Wait for the host to upload the next scenario.
We received invalid data from wesnothd during a game This means we cannot continue with the game but ...
void add_surrender(int side_number)
Definition: replay.cpp:231
bool is_regular_game_end() const
std::vector< team > & get_teams()
void unblind()
Definition: display.hpp:1095
void set_position(double xpos, double ypos)
replay * recorder
Definition: resources.cpp:29
virtual void play_human_turn() override
virtual void after_human_turn() override
static bool quit()
Shows the quit confirmation if needed.
void update_gui_to_player(const int team_index, const bool observe=false)
Changes the UI for this client to the passed side index.
playmp_controller(const config &level, saved_game &state_of_game, mp_game_metadata *mp_info)
void set_color(const color_t &color)
bool receive_from_wesnothd(config &cfg) const override
static void process_error(const std::string &msg)
Definition: replay.cpp:196
Exception used to signal that the user has decided to abortt a game, and to load another game instead...
Definition: savegame.hpp:83
An extension of playsingle_controller::hotkey_handler, which has support for MP wesnoth features like...
virtual bool attach_handler(observer *obs)
std::size_t i
Definition: function.cpp:967
When the host uploaded the next scenario this is returned.
Definition: playturn.hpp:43
#define LOG_NG
virtual void play_network_turn() override
Will handle networked turns in descendent classes.
We found a player action in the replay that caused the game to end.
Definition: playturn.hpp:49
void play_slice(bool is_delay_enabled=true) override
int add_floating_label(const floating_label &flabel)
add a label floating on the screen above everything else.
static source_type get_source_from_config(config &src)
game_data gamedata_
Definition: game_state.hpp:46
actions::undo_list & undo_stack()
const end_level_data & get_end_level_data() const
static void save(LexState *ls, int c)
Definition: llex.cpp:57
const std::string & next_scenario() const
Definition: game_data.hpp:96
config & add_child(config_key_type key)
Definition: config.cpp:514
compression::format save_compression_format()
Definition: game.cpp:857
bool is_replay() const
virtual void play_idle_loop() override
static void display(std::function< void()> f)
game_state & gamestate()
playturn_network_adapter network_reader_
std::vector< std::string > split(const config_attribute_value &val)
game_board board_
Definition: game_state.hpp:47
Various functions that implement the undoing (and redoing) of in-game commands.
void set_action_bonus_count(const int count)
Definition: team.hpp:226
Standard logging facilities (interface).
int current_side() const
Returns the number of the side whose turn it is.
replay_network_sender replay_sender_
virtual bool detach_handler(observer *obs)
std::string message
Definition: exceptions.hpp:30
virtual void do_idle_notification() override
Will handle sending a networked notification in descendent classes.
static PROCESS_DATA_RESULT replay_to_process_data_result(REPLAY_RETURN replayreturn)
Definition: playturn.cpp:399
bool wait_and_receive_data(config &data)
Unlike receive_data, waits until data is available instead of returning immediately.
#define e
int side_number
Definition: game_info.hpp:40
std::size_t turn() const
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:61
PROCESS_DATA_RESULT process_network_data(const config &cfg, bool chat_only=false)
Definition: playturn.cpp:129
mp_game_settings & mp_settings()
Multiplayer parameters for this game.
Definition: saved_game.hpp:59
std::string::const_iterator iterator
Definition: tokenizer.hpp:25
when we couldn&#39;t handle the given action currently.
Definition: playturn.hpp:47
virtual void handle_generic_event(const std::string &name) override
wesnothd_connection & connection
An [end_turn] was added to the replay.
mp_game_metadata * mp_info_