The Battle for Wesnoth  1.15.0-dev
undo.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project http://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file
17  * Undoing, redoing.
18  */
19 
20 #include "actions/undo.hpp"
21 
22 #include "game_board.hpp" // for game_board
23 #include "game_display.hpp" // for game_display
24 #include "log.hpp" // for LOG_STREAM, logger, etc
25 #include "map/map.hpp" // for gamemap
26 #include "map/location.hpp" // for map_location, operator<<, etc
27 #include "mouse_handler_base.hpp" // for command_disabler
28 #include "preferences/general.hpp"
29 #include "recall_list_manager.hpp" // for recall_list_manager
30 #include "replay.hpp" // for recorder, replay
31 #include "replay_helper.hpp" // for replay_helper
32 #include "resources.hpp" // for screen, teams, units, etc
33 #include "synced_context.hpp" // for set_scontext_synced
34 #include "team.hpp" // for team
35 #include "units/unit.hpp" // for unit
37 #include "units/id.hpp"
38 #include "units/map.hpp" // for unit_map, etc
39 #include "units/ptr.hpp" // for unit_const_ptr, unit_ptr
40 #include "units/types.hpp" // for unit_type, unit_type_data, etc
41 #include "whiteboard/manager.hpp" // for manager
42 
43 #include "actions/create.hpp" // for find_recall_location, etc
44 #include "actions/move.hpp" // for get_village
45 #include "actions/vision.hpp" // for clearer_info, etc
52 
53 #include <algorithm> // for reverse
54 #include <cassert> // for assert
55 #include <ostream> // for operator<<, basic_ostream, etc
56 #include <set> // for set
57 
58 static lg::log_domain log_engine("engine");
59 #define ERR_NG LOG_STREAM(err, log_engine)
60 #define LOG_NG LOG_STREAM(info, log_engine)
61 
62 
63 namespace actions {
64 
65 
66 
67 /**
68  * Creates an undo_action based on a config.
69  * @return a pointer that must be deleted, or nullptr if the @a cfg could not be parsed.
70  */
72 {
73  const std::string str = cfg["type"];
74  undo_action_base * res = nullptr;
75  // The general division of labor in this function is that the various
76  // constructors will parse the "unit" child config, while this function
77  // parses everything else.
78 
79  if ( str == "move" ) {
80  res = new undo::move_action(cfg, cfg.child_or_empty("unit"),
81  cfg["starting_moves"],
82  map_location::parse_direction(cfg["starting_direction"]));
83  }
84 
85  else if ( str == "recruit" ) {
86  // Validate the unit type.
87  const config & child = cfg.child("unit");
88  const unit_type * u_type = unit_types.find(child["type"]);
89 
90  if ( !u_type ) {
91  // Bad data.
92  ERR_NG << "Invalid recruit found in [undo] or [redo]; unit type '"
93  << child["type"] << "' was not found.\n";
94  return nullptr;
95  }
96  res = new undo::recruit_action(cfg, *u_type, map_location(cfg.child_or_empty("leader"), nullptr));
97  }
98 
99  else if ( str == "recall" )
100  res = new undo::recall_action(cfg, map_location(cfg.child_or_empty("leader"), nullptr));
101 
102  else if ( str == "dismiss" )
103  res = new undo::dismiss_action(cfg, cfg.child("unit"));
104 
105  else if ( str == "auto_shroud" )
106  res = new undo::auto_shroud_action(cfg["active"].to_bool());
107 
108  else if ( str == "update_shroud" )
109  res = new undo::update_shroud_action();
110  else if ( str == "dummy" )
111  res = new undo_dummy_action(cfg);
112  else
113  {
114  // Unrecognized type.
115  ERR_NG << "Unrecognized undo action type: " << str << "." << std::endl;
116  return nullptr;
117  }
118  return res;
119 }
120 
121 
122 /**
123  * Constructor.
124  * The config is allowed to be invalid.
125  */
127  undos_(), redos_(), side_(1), committed_actions_(false)
128 {
129  if ( cfg )
130  read(cfg);
131 }
132 
133 /**
134  * Destructor.
135  */
137 {
138  // Default destructor, but defined out-of-line to localize the templating.
139  // (Might make compiles faster.)
140 }
141 
142 
143 /**
144  * Adds an auto-shroud toggle to the undo stack.
145  */
146 void undo_list::add_auto_shroud(bool turned_on)
147 {
148  /// @todo: Consecutive shroud actions can be collapsed into one.
149 
150  // Do not call add(), as this should not clear the redo stack.
151  add(new undo::auto_shroud_action(turned_on));
152 }
153 
155 {
156  /// @todo: Consecutive shroud actions can be collapsed into one.
157 
158  // Do not call add(), as this should not clear the redo stack.
159  add(new undo_dummy_action());
160 }
161 
162 /**
163  * Adds a dismissal to the undo stack.
164  */
166 {
167  add(new undo::dismiss_action(u));
168 }
169 
170 /**
171  * Adds a move to the undo stack.
172  */
174  const std::vector<map_location>::const_iterator & begin,
175  const std::vector<map_location>::const_iterator & end,
176  int start_moves, int timebonus, int village_owner,
177  const map_location::DIRECTION dir)
178 {
179  add(new undo::move_action(u, begin, end, start_moves, timebonus, village_owner, dir));
180 }
181 
182 /**
183  * Adds a recall to the undo stack.
184  */
186  const map_location& from, int orig_village_owner, bool time_bonus)
187 {
188  add(new undo::recall_action(u, loc, from, orig_village_owner, time_bonus));
189 }
190 
191 /**
192  * Adds a recruit to the undo stack.
193  */
195  const map_location& from, int orig_village_owner, bool time_bonus)
196 {
197  add(new undo::recruit_action(u, loc, from, orig_village_owner, time_bonus));
198 }
199 
200 /**
201  * Adds a shroud update to the undo stack.
202  * This is called from within commit_vision(), so there should be no need
203  * for this to be publicly visible.
204  */
206 {
207  /// @todo: Consecutive shroud actions can be collapsed into one.
208 
210 }
211 
212 
213 /**
214  * Clears the stack of undoable (and redoable) actions.
215  * (Also handles updating fog/shroud if needed.)
216  * Call this if an action alters the game state, but add that action to the
217  * stack before calling this (if the action is a kind that can be undone).
218  * This may fire events and change the game state.
219  */
221 {
222  // The fact that this function was called indicates that something was done.
223  // (Some actions, such as attacks, are never put on the stack.)
224  committed_actions_ = true;
225 
226  // We can save some overhead by not calling apply_shroud_changes() for an
227  // empty stack.
228  if ( !undos_.empty() ) {
230  undos_.clear();
231  }
232  // No special handling for redos, so just clear that stack.
233  redos_.clear();
234 }
235 
236 
237 /**
238  * Updates fog/shroud based on the undo stack, then updates stack as needed.
239  * Call this when "updating shroud now".
240  * This may fire events and change the game state.
241  * @param[in] is_replay Set to true when this is called during a replay.
242  */
244 {
245  // Update fog/shroud.
246  bool cleared_something = apply_shroud_changes();
247 
248  if (cleared_something) {
249  // The actions that led to information being revealed can no longer
250  // be undone.
251  undos_.clear();
252  //undos_.erase(undos_.begin(), undos_.begin() + erase_to);
253  committed_actions_ = true;
254  }
255 }
256 
257 
258 /**
259  * Performs some initializations and error checks when starting a new side-turn.
260  * @param[in] side The side whose turn is about to start.
261  */
263 {
264  // Error checks.
265  if ( !undos_.empty() ) {
266  ERR_NG << "Undo stack not empty in new_side_turn()." << std::endl;
267  // At worst, someone missed some sighted events, so try to recover.
268  undos_.clear();
269  redos_.clear();
270  }
271  else if ( !redos_.empty() ) {
272  ERR_NG << "Redo stack not empty in new_side_turn()." << std::endl;
273  // Sloppy tracking somewhere, but not critically so.
274  redos_.clear();
275  }
276 
277  // Reset the side.
278  side_ = side;
279  committed_actions_ = false;
280 }
281 
282 
283 /**
284  * Read the undo_list from the provided config.
285  * Currently, this is only used when the undo_list is empty, but in theory
286  * it could be used to append the config to the current data.
287  */
288 void undo_list::read(const config & cfg)
289 {
290  // Merge header data.
291  side_ = cfg["side"].to_int(side_);
292  committed_actions_ = committed_actions_ || cfg["committed"].to_bool();
293 
294  // Build the undo stack.
295  for (const config & child : cfg.child_range("undo")) {
296  try {
297  undo_action_base * action = create_action(child);
298  if ( action ) {
299  undos_.push_back(action);
300  }
301  } catch (const bad_lexical_cast &) {
302  ERR_NG << "Error when parsing undo list from config: bad lexical cast." << std::endl;
303  ERR_NG << "config was: " << child.debug() << std::endl;
304  ERR_NG << "Skipping this undo action..." << std::endl;
305  } catch (const config::error& e) {
306  ERR_NG << "Error when parsing undo list from config: " << e.what() << std::endl;
307  ERR_NG << "config was: " << child.debug() << std::endl;
308  ERR_NG << "Skipping this undo action..." << std::endl;
309  }
310  }
311 
312  // Build the redo stack.
313  for (const config & child : cfg.child_range("redo")) {
314  try {
315  redos_.push_back(new config(child));
316  } catch (const bad_lexical_cast &) {
317  ERR_NG << "Error when parsing redo list from config: bad lexical cast." << std::endl;
318  ERR_NG << "config was: " << child.debug() << std::endl;
319  ERR_NG << "Skipping this redo action..." << std::endl;
320  } catch (const config::error& e) {
321  ERR_NG << "Error when parsing redo list from config: " << e.what() << std::endl;
322  ERR_NG << "config was: " << child.debug() << std::endl;
323  ERR_NG << "Skipping this redo action..." << std::endl;
324  }
325  }
326 }
327 
328 
329 /**
330  * Write the undo_list into the provided config.
331  */
332 void undo_list::write(config & cfg) const
333 {
334  cfg["side"] = side_;
335  cfg["committed"] = committed_actions_;
336 
337  for ( action_list::const_iterator it = undos_.begin(); it != undos_.end(); ++it )
338  it->write(cfg.add_child("undo"));
339 
340  for ( redos_list::const_iterator it = redos_.begin(); it != redos_.end(); ++it )
341  cfg.add_child("redo") = *it;
342 }
343 
344 
345 /**
346  * Undoes the top action on the undo stack.
347  */
349 {
350  if ( undos_.empty() )
351  return;
352 
353  const events::command_disabler disable_commands;
354 
356 
357  // Get the action to undo. (This will be placed on the redo stack, but
358  // only if the undo is successful.)
359  action_list::auto_type action = undos_.pop_back();
360  if (undo_action* undoable_action = dynamic_cast<undo_action*>(action.ptr()))
361  {
362  int last_unit_id = resources::gameboard->unit_id_manager().get_save_id();
363  if ( !undoable_action->undo(side_) ) {
364  return;
365  }
366  if(last_unit_id - undoable_action->unit_id_diff < 0) {
367  ERR_NG << "Next unit id is below 0 after undoing" << std::endl;
368  }
369  resources::gameboard->unit_id_manager().set_save_id(last_unit_id - undoable_action->unit_id_diff);
370 
371  // Bookkeeping.
372  redos_.push_back(new config());
374 
375  resources::whiteboard->on_gamestate_change();
376 
377  // Screen updates.
378  gui.redraw_minimap();
379  }
380  else
381  {
382  //ignore this action, and undo the previous one.
383  config replay_data;
384  resources::recorder->undo_cut(replay_data);
385  undo();
386  resources::recorder->redo(replay_data);
387  undos_.push_back(action.release());
388  }
389 }
390 
391 
392 
393 /**
394  * Redoes the top action on the redo stack.
395  */
397 {
398  if ( redos_.empty() )
399  return;
400 
401  const events::command_disabler disable_commands;
402 
404 
405  // Get the action to redo. (This will be placed on the undo stack, but
406  // only if the redo is successful.)
407  redos_list::auto_type action = redos_.pop_back();
408 
409  const config& command_wml = action->child("command");
410  std::string commandname = command_wml.all_children_range().front().key;
411  const config& data = command_wml.all_children_range().front().cfg;
412 
413  resources::recorder->redo(const_cast<const config&>(*action));
414 
415 
416  // synced_context::run readds the undo command with the normal undo_lis::add function which clears the
417  // redo stack which makes redoign of more than one move impossible. to work around that we save redo stack here and set it later.
418  redos_list temp;
419  temp.swap(redos_);
420  synced_context::run(commandname, data, /*use_undo*/ true, /*show*/ true);
421  temp.swap(redos_);
422 
423  // Screen updates.
424  gui.redraw_minimap();
425 }
426 
427 
428 
429 
430 
431 /**
432  * Applies the pending fog/shroud changes from the undo stack.
433  * Does nothing if the the current side does not use fog or shroud.
434  * @returns true if shroud or fog was cleared.
435  */
437 {
439  // No need to do clearing if fog/shroud has been kept up-to-date.
440  if ( tm.auto_shroud_updates() || !tm.fog_or_shroud() ) {
441  return false;
442  }
443  shroud_clearer clearer;
444  bool cleared_shroud = false;
445  const std::size_t list_size = undos_.size();
446 
447 
448  // Loop through the list of undo_actions.
449  for( std::size_t i = 0; i != list_size; ++i ) {
450  if (const shroud_clearing_action* action = dynamic_cast<const shroud_clearing_action*>(&undos_[i])) {
451  LOG_NG << "Turning an undo...\n";
452 
453  // Clear the hexes this unit can see from each hex occupied during
454  // the action.
455  std::vector<map_location>::const_iterator step;
456  for (step = action->route.begin(); step != action->route.end(); ++step) {
457  // Clear the shroud, collecting new sighted events.
458  // (This can be made gradual by changing "true" to "false".)
459  if ( clearer.clear_unit(*step, tm, action->view_info, true) ) {
460  cleared_shroud = true;
461  }
462  }
463  }
464  }
465 
466 
467  if (!cleared_shroud) {
468  return false;
469  }
470  // If we clear fog or shroud outside a synced context we get OOS
471  // Note that it can happen that we call this function from ouside a synced context
472  // when we reload a game and want to prevent undoing. But in this case this is
473  // preceded by a manual update_shroud call so that cleared_shroud is false.
474  assert(synced_context::is_synced());
475 
476  // The entire stack needs to be cleared in order to preserve replays.
477  // (The events that fired might depend on current unit positions.)
478  // (Also the events that did not fire might depend on unit positions (they whould have fired if the unit would have standed on different positions, for example this can happen if they have a [have_unit] in [filter_condition]))
479 
480  // Update the display before pumping events.
481  clearer.invalidate_after_clear();
482 
483  // Fire sighted events
484  if ( std::get<0>(clearer.fire_events() )) {
485  // Fix up the display in case WML changed stuff.
487  }
488 
489  return true;
490 }
491 
492 }//namespace actions
void clear()
Clears the stack of undoable (and redoable) actions.
Definition: undo.cpp:220
boost::intrusive_ptr< const unit > unit_const_ptr
Definition: ptr.hpp:30
base class for classes that clear srhoud (move/recruit/recall)
bool committed_actions_
Tracks if actions have been cleared from the stack since the turn began.
Definition: undo.hpp:114
static DIRECTION parse_direction(const std::string &str)
Definition: location.cpp:64
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:423
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:874
std::size_t get_save_id() const
Used for saving id to savegame.
Definition: id.cpp:41
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition: types.cpp:1275
bool apply_shroud_changes() const
Applies the pending fog/shroud changes from the undo stack.
Definition: undo.cpp:436
Various functions implementing vision (through fog of war and shroud).
static bool run(const std::string &commandname, const config &data, bool use_undo=true, bool show=true, synced_command::error_handler_function error_handler=default_error_function)
Sets the context to &#39;synced&#39;, initialises random context, and calls the given function.
action_list undos_
Definition: undo.hpp:108
child_itors child_range(config_key_type key)
Definition: config.cpp:366
General purpose widgets.
void undo()
Undoes the top action on the undo stack.
Definition: undo.cpp:348
void add(undo_action_base *action)
Adds an action to the undo stack.
Definition: undo.hpp:102
int side_
Tracks the current side.
Definition: undo.hpp:112
unit_type_data unit_types
Definition: types.cpp:1452
void new_side_turn(int side)
Performs some initializations and error checks when starting a new side-turn.
Definition: undo.cpp:262
Replay control code.
-file sdl_utils.hpp
void redraw_minimap()
Schedule the minimap to be redrawn.
Definition: display.hpp:656
A single unit type that the player may recruit.
Definition: types.hpp:42
Records information to be able to undo an action.
Definition: undo_action.hpp:38
bool clear_unit(const map_location &view_loc, team &view_team, std::size_t viewer_id, int sight_range, bool slowed, const movetype::terrain_costs &costs, const map_location &real_loc, const std::set< map_location > *known_units=nullptr, std::size_t *enemy_count=nullptr, std::size_t *friend_count=nullptr, move_unit_spectator *spectator=nullptr, bool instant=true)
Clears shroud (and fog) around the provided location for view_team based on sight_range, costs, and slowed.
Definition: vision.cpp:319
void read(const config &cfg)
Read the undo_list from the provided config.
Definition: undo.cpp:288
undo_list(const undo_list &)=delete
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
team & get_team(int i)
Definition: game_board.hpp:104
game_events::pump_result_t fire_events()
Fires the sighted events that were earlier recorded by fog/shroud clearing.
Definition: vision.cpp:535
void redo(const config &dst, bool set_to_end=false)
Definition: replay.cpp:414
#define ERR_NG
Definition: undo.cpp:59
boost::ptr_vector< config > redos_list
Definition: undo.hpp:38
game_board * gameboard
Definition: resources.cpp:20
bool fog_or_shroud() const
Definition: team.hpp:316
static lg::log_domain log_engine("engine")
replay * recorder
Definition: resources.cpp:28
const char * what() const noexcept
Definition: exceptions.hpp:37
void commit_vision()
Updates fog/shroud based on the undo stack, then updates stack as needed.
Definition: undo.cpp:243
void set_save_id(std::size_t)
Definition: id.cpp:46
Encapsulates the map of the game.
Definition: location.hpp:42
bool auto_shroud_updates() const
Definition: team.hpp:334
Various functions related to moving units.
void add_recruit(const unit_const_ptr u, const map_location &loc, const map_location &from, int orig_village_owner, bool time_bonus)
Adds a recruit to the undo stack.
Definition: undo.cpp:194
std::shared_ptr< wb::manager > whiteboard
Definition: resources.cpp:33
Various functions related to the creation of units (recruits, recalls, and placed units)...
#define LOG_NG
Definition: undo.cpp:60
void add_dismissal(const unit_const_ptr u)
Adds a dismissal to the undo stack.
Definition: undo.cpp:165
static undo_action_base * create_action(const config &cfg)
Creates an undo_action based on a config.
Definition: undo.cpp:71
std::size_t i
Definition: function.cpp:933
entry for player actions that do not need any special code to be performed when undoing such as right...
Definition: undo_action.hpp:89
void redo()
Redoes the top action on the redo stack.
Definition: undo.cpp:396
redos_list redos_
Definition: undo.hpp:109
void add_recall(const unit_const_ptr u, const map_location &loc, const map_location &from, int orig_village_owner, bool time_bonus)
Adds a recall to the undo stack.
Definition: undo.cpp:185
void add_move(const unit_const_ptr u, const std::vector< map_location >::const_iterator &begin, const std::vector< map_location >::const_iterator &end, int start_moves, int timebonus=0, int village_owner=-1, const map_location::DIRECTION dir=map_location::NDIRECTIONS)
Adds a move to the undo stack.
Definition: undo.cpp:173
DIRECTION
Valid directions which can be moved in our hexagonal world.
Definition: location.hpp:44
config & add_child(config_key_type key)
Definition: config.cpp:479
bool clear_shroud(int side, bool reset_fog, bool fire_events)
Function that will clear shroud (and fog) based on current unit positions.
Definition: vision.cpp:739
void add_update_shroud()
Adds a shroud update to the undo stack.
Definition: undo.cpp:205
n_unit::id_manager & unit_id_manager()
Definition: game_board.hpp:86
Various functions that implement the undoing (and redoing) of in-game commands.
void undo_cut(config &dst)
Definition: replay.cpp:494
Standard logging facilities (interface).
void add_dummy()
Adds an auto-shroud toggle to the undo stack.
Definition: undo.cpp:154
Class to encapsulate fog/shroud clearing and the resultant sighted events.
Definition: vision.hpp:57
#define e
void add_auto_shroud(bool turned_on)
Adds an auto-shroud toggle to the undo stack.
Definition: undo.cpp:146
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:456
void invalidate_after_clear()
The invalidations that should occur after invoking clear_unit().
Definition: vision.cpp:570
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
Thrown when a lexical_cast fails.
static bool is_synced()
void write(config &cfg) const
Write the undo_list into the provided config.
Definition: undo.cpp:332
actions that are undoable (this does not include update_shroud and auto_shroud)
Definition: undo_action.hpp:60
static game_display * get_singleton()
~undo_list()
Destructor.
Definition: undo.cpp:136