The Battle for Wesnoth  1.15.11+dev
playcampaign.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003-2005 by David White <dave@whitevine.net>
3  Copyright (C) 2005 - 2018 by Philippe Plantier <ayin@anathas.org>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 /**
17  * @file
18  * Controls setup, play, (auto)save and replay of campaigns.
19  */
20 
22 
23 #include "carryover.hpp"
24 #include "formula/string_utils.hpp"
25 #include "game_config.hpp"
26 #include "game_errors.hpp"
32 #include "gettext.hpp"
33 #include "gui/dialogs/message.hpp"
34 #include "gui/dialogs/outro.hpp"
36 #include "gui/widgets/retval.hpp"
37 #include "log.hpp"
38 #include "map/exception.hpp"
39 #include "map/map.hpp"
40 #include "persist_manager.hpp"
41 #include "playmp_controller.hpp"
42 #include "preferences/game.hpp"
43 #include "saved_game.hpp"
44 #include "savegame.hpp"
45 #include "sound.hpp"
46 #include "wesnothd_connection.hpp"
47 #include "wml_exception.hpp"
48 
49 #define LOG_G LOG_STREAM(info, lg::general)
50 
51 static lg::log_domain log_engine("engine");
52 #define LOG_NG LOG_STREAM(info, log_engine)
53 #define ERR_NG LOG_STREAM(err, log_engine)
54 
55 static lg::log_domain log_enginerefac("enginerefac");
56 #define LOG_RG LOG_STREAM(info, log_enginerefac)
57 
59  playsingle_controller& playcontroller, const end_level_data& end_level, const LEVEL_RESULT res)
60 {
61  // We need to write the carryover amount to the team that's why we need non const
62  std::vector<team>& teams = playcontroller.get_teams();
63 
64  // maybe this can be the case for scenario that only contain a story and end during the prestart event ?
65  if(teams.size() < 1) {
66  return;
67  }
68 
69  std::ostringstream report;
70  std::string title;
71 
72  bool obs = playcontroller.is_observer();
73 
74  if(obs) {
75  title = _("Scenario Report");
76  } else if(res == LEVEL_RESULT::VICTORY) {
77  title = _("Victory");
78  report << "<b>" << _("You have emerged victorious!") << "</b>";
79  } else {
80  title = _("Defeat");
81  report << _("You have been defeated!");
82  }
83 
84  const std::string& next_scenario = playcontroller.gamestate().get_game_data()->next_scenario();
85  const bool has_next_scenario = !next_scenario.empty() && next_scenario != "null";
86 
87  int persistent_teams = 0;
88  for(const team& t : teams) {
89  if(t.persistent()) {
90  ++persistent_teams;
91  }
92  }
93 
94  if(persistent_teams > 0 && ((has_next_scenario && end_level.proceed_to_next_level) || state_.classification().is_test())) {
95  const gamemap& map = playcontroller.get_map();
96  const tod_manager& tod = playcontroller.get_tod_manager();
97 
98  const int turns_left = std::max<int>(0, tod.number_of_turns() - tod.turn());
99  for(team& t : teams) {
100  if(!t.persistent() || t.lost()) {
101  continue;
102  }
103 
104  const int finishing_bonus_per_turn = map.villages().size() * t.village_gold() + t.base_income();
105  const int finishing_bonus = t.carryover_bonus() * finishing_bonus_per_turn * turns_left;
106 
107  t.set_carryover_gold(div100rounded((t.gold() + finishing_bonus) * t.carryover_percentage()));
108 
109  if(!t.is_local_human()) {
110  continue;
111  }
112 
113  if(persistent_teams > 1) {
114  report << "\n\n<b>" << t.side_name() << "</b>";
115  }
116 
117  report << "<small>\n" << _("Remaining gold: ") << utils::half_signed_value(t.gold()) << "</small>";
118 
119  if(t.carryover_bonus() != 0) {
120  if(turns_left > -1) {
121  report << "\n\n<b>" << _("Turns finished early: ") << turns_left << "</b>\n"
122  << "<small>" << _("Early finish bonus: ") << finishing_bonus_per_turn << _(" per turn") << "</small>\n"
123  << "<small>" << _("Total bonus: ") << finishing_bonus << "</small>\n";
124  }
125 
126  report << "<small>" << _("Total gold: ") << utils::half_signed_value(t.gold() + finishing_bonus) << "</small>";
127  }
128 
129  if(t.gold() > 0) {
130  report << "\n<small>" << _("Carryover percentage: ") << t.carryover_percentage() << "</small>";
131  }
132 
133  if(t.carryover_add()) {
134  report << "\n\n<big><b>" << _("Bonus gold: ") << utils::half_signed_value(t.carryover_gold()) << "</b></big>";
135  } else {
136  report << "\n\n<big><b>" << _("Retained gold: ") << utils::half_signed_value(t.carryover_gold()) << "</b></big>";
137  }
138 
139  std::string goldmsg;
140  utils::string_map symbols;
141 
142  symbols["gold"] = lexical_cast_default<std::string>(t.carryover_gold());
143 
144  // Note that both strings are the same in English, but some languages will
145  // want to translate them differently.
146  if(t.carryover_add()) {
147  if(t.carryover_gold() > 0) {
148  goldmsg = VNGETTEXT(
149  "You will start the next scenario with $gold on top of the defined minimum starting gold.",
150  "You will start the next scenario with $gold on top of the defined minimum starting gold.",
151  t.carryover_gold(), symbols
152  );
153 
154  } else {
155  goldmsg = VNGETTEXT(
156  "You will start the next scenario with the defined minimum starting gold.",
157  "You will start the next scenario with the defined minimum starting gold.",
158  t.carryover_gold(), symbols
159  );
160  }
161  } else {
162  goldmsg = VNGETTEXT(
163  "You will start the next scenario with $gold or its defined minimum starting gold, "
164  "whichever is higher.",
165  "You will start the next scenario with $gold or its defined minimum starting gold, "
166  "whichever is higher.",
167  t.carryover_gold(), symbols
168  );
169  }
170 
171  // xgettext:no-c-format
172  report << "\n" << goldmsg;
173  }
174  }
175 
176  if(end_level.transient.carryover_report) {
177  gui2::show_transient_message(title, report.str(), "", true);
178  }
179 }
180 
182 {
183  const config& starting_point = is_replay_
186 
187  playsingle_controller playcontroller(starting_point, state_, false);
188 
189  LOG_NG << "created objects... " << (SDL_GetTicks() - playcontroller.get_ticks()) << "\n";
190  if(is_replay_) {
191  playcontroller.enable_replay(is_unit_test_);
192  }
193 
194  LEVEL_RESULT res = playcontroller.play_scenario(starting_point);
195  if(res == LEVEL_RESULT::QUIT) {
196  return LEVEL_RESULT::QUIT;
197  }
198 
199  if(!is_unit_test_) {
200  is_replay_ = false;
201  }
202 
203  if(is_replay_) {
204  return res;
205  }
206 
207  end_level = playcontroller.get_end_level_data();
208  show_carryover_message(playcontroller, end_level, res);
209 
210  if(!CVideo::get_singleton().faked()) {
211  playcontroller.maybe_linger();
212  }
213 
214  state_.set_snapshot(playcontroller.to_config());
215  return res;
216 }
217 
219 {
221  LEVEL_RESULT res = playcontroller.play_scenario(state_.get_starting_point());
222 
223  // Check if the player started as mp client and changed to host
224  if(res == LEVEL_RESULT::QUIT) {
225  return LEVEL_RESULT::QUIT;
226  }
227 
228  end_level = playcontroller.get_end_level_data();
229 
230  if(res != LEVEL_RESULT::OBSERVER_END) {
231  // We need to call this before linger because it prints the defeated/victory message.
232  //(we want to see that message before entering the linger mode)
233  show_carryover_message(playcontroller, end_level, res);
234  }
235 
236  playcontroller.maybe_linger();
237  playcontroller.update_savegame_snapshot();
238 
239  if(mp_info_) {
240  mp_info_->connected_players = playcontroller.all_players();
241  mp_info_->skip_replay = false;
243  }
244 
245  return res;
246 }
247 
249 {
250  if(is_replay_) {
252  } else {
254  }
255 
257 
258  while(state_.valid()) {
259  LEVEL_RESULT res = LEVEL_RESULT::VICTORY;
260  end_level_data end_level;
261 
262  try {
264  // In case this an mp scenario reloaded by sp this was not already done yet.
266 
268 
270 
271  // expand_mp_options must be called after expand_carryover because expand_carryover will to set previous
272  // variables if there are already variables in the [scenario]
274 
275 #if !defined(ALWAYS_USE_MP_CONTROLLER)
277  res = playsingle_scenario(end_level);
278  if(is_replay_) {
279  return res;
280  }
281  } else
282 #endif
283  {
284  res = playmp_scenario(end_level);
285  }
286  } catch(const leavegame_wesnothd_error&) {
287  LOG_NG << "The game was remotely ended\n";
288  return LEVEL_RESULT::QUIT;
289  } catch(const game::load_game_failed& e) {
290  gui2::show_error_message(_("The game could not be loaded: ") + e.message);
291  return LEVEL_RESULT::QUIT;
292  } catch(const quit_game_exception&) {
293  LOG_NG << "The game was aborted\n";
294  return LEVEL_RESULT::QUIT;
295  } catch(const game::game_error& e) {
296  gui2::show_error_message(_("Error while playing the game: ") + e.message);
297  return LEVEL_RESULT::QUIT;
298  } catch(const incorrect_map_format_error& e) {
299  gui2::show_error_message(_("The game map could not be loaded: ") + e.message);
300  return LEVEL_RESULT::QUIT;
301  } catch(const mapgen_exception& e) {
302  gui2::show_error_message(_("Map generator error: ") + e.message);
303  } catch(const config::error& e) {
304  gui2::show_error_message(_("Error while reading the WML: ") + e.message);
305  return LEVEL_RESULT::QUIT;
306  } catch(const wml_exception& e) {
307  e.show();
308  return LEVEL_RESULT::QUIT;
309  }
310 
311  if(is_unit_test_) {
312  return res;
313  }
314 
315  if(res == LEVEL_RESULT::QUIT) {
316  return res;
317  }
318 
319  // proceed_to_next_level <=> 'any human side received victory'
320  // If 'any human side received victory' we do the Save-management options
321  // Otherwise we are done now
322  if(!end_level.proceed_to_next_level) {
323  return res;
324  }
325 
328  }
329 
330  if(preferences::save_replays() && end_level.replay_save) {
332  save.save_game_automatic(true);
333  }
334 
336 
337  // If there is no next scenario we're done now.
338  if(state_.get_scenario_id().empty()) {
339  // Don't show The End for multiplayer scenarios.
340  if(res == LEVEL_RESULT::VICTORY && !state_.classification().is_normal_mp_game()) {
343 
345  gui2::dialogs::outro::display(state_.classification());
346  }
347  }
348 
349  return res;
350  } else if(res == LEVEL_RESULT::OBSERVER_END && mp_info_ && !mp_info_->is_host) {
351  const int dlg_res = gui2::show_message(_("Game Over"),
352  _("This scenario has ended. Do you want to continue the campaign?"),
354 
355  if(dlg_res == gui2::retval::CANCEL) {
356  return res;
357  }
358  }
359 
360  if(mp_info_ && !mp_info_->is_host) {
361  // Opens join game dialog to get a new gamestate.
362  if(!mp::goto_mp_wait(res == LEVEL_RESULT::OBSERVER_END)) {
363  return LEVEL_RESULT::QUIT;
364  }
365 
366  // The host should send the complete savegame now that also contains the carryover sides start.
367  } else {
368  // clear previous game content information
369  // otherwise it keeps getting appended for each scenario resulting in incorrect data being sent to the server to be stored
370  state_.mp_settings().addons.clear();
371  // Retrieve next scenario data.
373 
374  if(state_.valid()) {
375  // note that although starting_pos is const it might be changed by gamestate.some_non_const_operation()
376  const config& starting_pos = state_.get_starting_point();
377 
378  const bool is_mp = state_.classification().is_normal_mp_game();
379  state_.mp_settings().num_turns = starting_pos["turns"].to_int(-1);
380 
381  if(state_.mp_settings().saved_game == mp_game_settings::SAVED_GAME_MODE::MIDGAME) {
382  state_.mp_settings().saved_game = mp_game_settings::SAVED_GAME_MODE::SCENARIO_START;
383  }
384 
385  state_.mp_settings().use_map_settings = starting_pos["force_lock_settings"].to_bool(!is_mp);
386 
387  ng::connect_engine connect_engine(state_, false, mp_info_);
388 
389  if(!connect_engine.can_start_game() || (game_config::debug && state_.classification().is_multiplayer())) {
390  // Opens staging dialog to allow users to make an adjustments for scenario.
391  if(!mp::goto_mp_staging(connect_engine)) {
392  return LEVEL_RESULT::QUIT;
393  }
394  } else {
395  // Start the next scenario immediately.
396  connect_engine.start_game();
397  }
398  }
399  }
400 
401  if(state_.valid()) {
402  // Update the label
404 
405  // If this isn't the last scenario, then save the game
406  if(end_level.prescenario_save) {
407  // For multiplayer, we want the save to contain the starting position.
408  // For campaigns however, this is the start-of-scenario save and the
409  // starting position needs to be empty, to force a reload of the scenario config.
411  save.save_game_automatic();
412  }
413  }
414  }
415 
416  if(!state_.get_scenario_id().empty()) {
417  utils::string_map symbols;
418  symbols["scenario"] = state_.get_scenario_id();
419 
420  std::string message = _("Unknown scenario: '$scenario|'");
421  message = utils::interpolate_variables_into_string(message, &symbols);
422 
423  gui2::show_error_message(message);
424  return LEVEL_RESULT::QUIT;
425  }
426 
430  }
431  }
432 
433  return LEVEL_RESULT::VICTORY;
434 }
void empty_playlist()
Definition: sound.cpp:611
Dialog was closed with the CANCEL button.
Definition: retval.hpp:37
void show_message(const std::string &title, const std::string &msg, const std::string &button_caption, const bool auto_close, const bool message_use_markup, const bool title_use_markup)
Shows a message to the user.
Definition: message.cpp:152
bool end_credits
whether to show the standard credits at the end
Class for start-of-scenario saves.
Definition: savegame.hpp:305
std::string interpolate_variables_into_string(const std::string &str, const string_map *const symbols)
Function which will interpolate variables, starting with &#39;$&#39; in the string &#39;str&#39; with the equivalent ...
LEVEL_RESULT play_game()
std::map< std::string, t_string > string_map
std::string label
Name of the game (e.g.
void expand_scenario()
copies the content of a [scenario] with the correct id attribute from the game config into this objec...
Definition: saved_game.cpp:267
static lg::log_domain log_enginerefac("enginerefac")
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
Error used when game loading fails.
Definition: game_errors.hpp:30
replay_recorder_base & get_replay()
Definition: saved_game.hpp:134
void show_transient_message(const std::string &title, const std::string &message, const std::string &image, const bool message_use_markup, const bool title_use_markup, const bool restore_background)
Shows a transient message to the user.
void expand_random_scenario()
takes care of generate_map=, generate_scenario=, map= attributes This should be called before expandi...
Definition: saved_game.cpp:475
bool valid() const
Definition: saved_game.cpp:552
mp_game_metadata * mp_info_
static lg::log_domain log_engine("engine")
bool goto_mp_wait(bool observe)
Opens the MP Join Game screen and sets the game state according to the changes made.
bool prescenario_save
Should a prescenario be created the next game?
void enable_replay(bool is_unit_test=false)
static CVideo & get_singleton()
Definition: video.hpp:48
#define VNGETTEXT(msgid, msgid_plural, count,...)
const gamemap & get_map() const
bool replay_save
Should a replay save be made?
config & set_snapshot(config snapshot)
Definition: saved_game.cpp:557
saved_game & state_
static std::string _(const char *str)
Definition: gettext.hpp:92
LEVEL_RESULT playmp_scenario(end_level_data &end_level)
std::string get_scenario_id() const
Definition: saved_game.cpp:647
void show() const
Shows the error in a dialog.
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
std::string half_signed_value(int val)
Sign with Unicode "−" if negative.
int div100rounded(int num)
Guarantees portable results for division by 100; round half up, to the nearest integer.
Definition: math.hpp:38
void expand_mp_options()
adds values of [option]s into [carryover_sides_start][variables] so that they are applied in the next...
Definition: saved_game.cpp:411
config to_config() const
Builds the snapshot config from members and their respective configs.
void update_label()
sets classification().label to the correct value.
Definition: saved_game.cpp:670
Encapsulates the map of the game.
Definition: map.hpp:170
std::vector< team > & get_teams()
LEVEL_RESULT playsingle_scenario(end_level_data &end_level)
config & get_starting_point()
Definition: saved_game.cpp:581
Shows a yes and no button.
Definition: message.hpp:79
bool carryover_report
Should a summary of the scenario outcome be displayed?
std::string campaign
The id of the campaign being played.
Error used for any general game error, e.g.
Definition: game_errors.hpp:46
LEVEL_RESULT play_scenario(const config &level)
std::set< std::string > connected_players
players and observers
bool is_observer() const
int number_of_turns() const
Helper class, don&#39;t construct this directly.
transient_end_level transient
void show_carryover_message(playsingle_controller &playcontroller, const end_level_data &end_level, LEVEL_RESULT res)
const config & get_replay_starting_point()
Definition: saved_game.cpp:586
const bool is_unit_test_
void clean_saves(const std::string &label)
Delete all autosaves of a certain scenario from the default save directory.
Definition: savegame.cpp:69
std::map< std::string, addon_version_info > addons
the key is the addon_id
void add_completed_campaign(const std::string &campaign_id, const std::string &difficulty_level)
Definition: game.cpp:296
bool proceed_to_next_level
whether to proceed to the next scenario, equals is_victory in sp.
bool delete_saves()
Definition: game.cpp:774
void expand_mp_events()
adds [event]s from [era] and [modification] into this scenario does NOT expand [option]s because vari...
Definition: saved_game.cpp:370
Additional information on the game outcome which can be provided by WML.
const bool & debug
const end_level_data & get_end_level_data() const
void expand_carryover()
merges [carryover_sides_start] into [scenario] and saves the rest into [carryover_sides] Removes [car...
Definition: saved_game.cpp:536
static void save(LexState *ls, int c)
Definition: llex.cpp:57
const std::string & next_scenario() const
Definition: game_data.hpp:95
Class for replay saves (either manually or automatically).
Definition: savegame.hpp:266
std::string difficulty
The difficulty level the game is being played on.
compression::format save_compression_format()
Definition: game.cpp:851
virtual const game_data * get_game_data() const override
Inherited from filter_context.
Definition: game_state.hpp:104
#define LOG_NG
game_state & gamestate()
double t
Definition: astarsearch.cpp:64
const tod_manager & get_tod_manager() const
game_classification & classification()
Definition: saved_game.hpp:54
const std::vector< map_location > & villages() const
Return a list of the locations of villages on the map.
Definition: map.hpp:236
Standard logging facilities (interface).
void convert_to_start_save()
converts a normal savegame form the end of a scenaio to a start-of-scenario savefile for the next sce...
Definition: saved_game.cpp:605
std::string message
Definition: exceptions.hpp:29
void show_error_message(const std::string &msg, bool message_use_markup)
Shows an error message to the user.
Definition: message.cpp:205
bool goto_mp_staging(ng::connect_engine &engine)
Opens the MP Staging screen and sets the game state according to the changes made.
int turn() const
#define e
bool can_start_game() const
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:59
mp_game_settings & mp_settings()
Multiplayer parameters for this game.
Definition: saved_game.hpp:58
bool skip_replay_blindfolded
int turns_left
Definition: pathfind.cpp:156
bool save_game_automatic(bool ask_for_overwrite=false, const std::string &filename="")
Saves a game without user interaction, unless the file exists and it should be asked to overwrite it...
Definition: savegame.cpp:367
bool save_replays()
Definition: game.cpp:764