The Battle for Wesnoth  1.17.12+dev
synced_user_choice.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2015 - 2022
3  Part of the Battle for Wesnoth Project https://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 #include "synced_user_choice.hpp"
17 
18 #include "actions/undo.hpp"
19 #include "display.hpp"
20 #include "floating_label.hpp"
21 #include "game_data.hpp"
22 #include "log.hpp"
23 #include "play_controller.hpp"
24 #include "synced_context.hpp"
25 #include "replay.hpp"
26 #include "resources.hpp"
28 #include <set>
29 #include <map>
30 #include "formula/string_utils.hpp"
31 #include "font/standard_colors.hpp"
32 
33 static lg::log_domain log_replay("replay");
34 #define DBG_REPLAY LOG_STREAM(debug, log_replay)
35 #define LOG_REPLAY LOG_STREAM(info, log_replay)
36 #define WRN_REPLAY LOG_STREAM(warn, log_replay)
37 #define ERR_REPLAY LOG_STREAM(err, log_replay)
38 
39 namespace
40 {
41  class user_choice_notifer_ingame
42  {
43  //the handle for the label on the screen -1 if not shown yet.
44  int label_id_;
45  std::string message_;
46  unsigned int start_show_;
47 
48  public:
49  user_choice_notifer_ingame()
50  : label_id_(-1)
51  , message_()
52  , start_show_(SDL_GetTicks() + 2000)
53  {
54 
55  }
56 
57  ~user_choice_notifer_ingame()
58  {
59  if(label_id_ != -1) {
60  end_show_label();
61  }
62  }
63 
64  void update(const std::string& message)
65  {
66  if(label_id_ == -1 && SDL_GetTicks() > start_show_)
67  {
68  start_show_label();
69  }
70  if(message == message_) {
71  return;
72  }
73  message_ = message;
74  if(label_id_ != -1) {
75  end_show_label();
76  start_show_label();
77  }
78  }
79 
80  void start_show_label()
81  {
82  assert(label_id_ == -1);
83  SDL_Rect area = display::get_singleton()->map_outside_area();
84  font::floating_label flabel(message_);
87  flabel.set_position(area.w/2, area.h/4);
88  flabel.set_lifetime(-1);
89  flabel.set_clip_rect(area);
90  label_id_ = font::add_floating_label(flabel);
91  }
92 
93  void end_show_label()
94  {
95  assert(label_id_ != -1);
96  font::remove_floating_label(label_id_);
97  label_id_ = -1;
98  }
99  };
100 }
101 
102 std::map<int,config> mp_sync::get_user_choice_multiple_sides(const std::string &name, const mp_sync::user_choice &uch,
103  std::set<int> sides)
104 {
105  //pass sides by copy because we need a copy.
106  const bool is_synced = synced_context::is_synced();
107  const int max_side = static_cast<int>(resources::gameboard->teams().size());
108  //we currently don't check for too early because lua's sync choice doesn't necessarily show screen dialogs.
109  //It (currently) in the responsibility of the user of sync choice to not use dialogs during prestart events..
110  if(!is_synced)
111  {
112  //we got called from inside lua's wesnoth.synchronize_choice or from a select event.
113  replay::process_error("MP synchronization only works in a synced context (for example Select or preload events are no synced context).\n");
114  return std::map<int,config>();
115  }
116 
117  for(int side : sides)
118  {
119  if(1 > side || side > max_side)
120  {
121  replay::process_error("MP synchronization with an invalid side number.\n");
122  return std::map<int,config>();
123  }
124  }
125 
126  /*
127  for empty sides we want to use random choice instead.
128  */
129  std::set<int> empty_sides;
130  for(int side : sides)
131  {
132  if( resources::gameboard->get_team(side).is_empty())
133  {
134  empty_sides.insert(side);
135  }
136  }
137 
138  for(int side : empty_sides)
139  {
140  sides.erase(side);
141  }
142 
143  std::map<int,config> retv = user_choice_manager::get_user_choice_internal(name, uch, sides);
144 
145  for(int side : empty_sides)
146  {
147  retv[side] = uch.random_choice(side);
148  }
149  return retv;
150 
151 }
152 
153 /*
154  fixes some rare cases and calls get_user_choice_internal if we are in a synced context.
155 */
156 config mp_sync::get_user_choice(const std::string &name, const mp_sync::user_choice &uch,
157  int side)
158 {
159  const bool is_too_early = resources::gamedata->phase() != game_data::START && resources::gamedata->phase() != game_data::PLAY;
160  const bool is_synced = synced_context::is_synced();
161  const bool is_mp_game = resources::controller->is_networked_mp();//Only used in debugging output below
162  const int max_side = static_cast<int>(resources::gameboard->teams().size());
163  bool is_side_null_controlled;
164 
165  /* side = 0 should default to the currently active side per definition. */
166  if(side < 1 || max_side < side) {
167  if(side != 0) {
168  ERR_REPLAY << "Invalid parameter for side in get_user_choice.";
169  }
170 
172  LOG_REPLAY << " side changed to " << side;
173  }
174 
175  if(!is_synced)
176  {
177  //we got called from inside lua's wesnoth.synchronize_choice or from a select event (or maybe a preload event?).
178  //This doesn't cause problems and someone could use it for example to use a [message][option] inside a wesnoth.synchronize_choice which could be useful,
179  //so just give a warning.
180  LOG_REPLAY << "MP synchronization called during an unsynced context.";
181  return uch.query_user(side);
182  }
183  if(is_too_early && uch.is_visible())
184  {
185  //We are in a prestart event or even earlier.
186  //Although we are able to sync them, we cannot use query_user,
187  //because we cannot (or shouldn't) put things on the screen inside a prestart event, this is true for SP and MP games.
188  //Quotation form event wiki: "For things displayed on-screen such as character dialog, use start instead"
189  return uch.random_choice(side);
190  }
191  //in start events it's unclear to decide on which side the function should be executed (default= side1 still).
192  //But for advancements we can just decide on the side that owns the unit and that's in the responsibility of advance_unit_at.
193  //For [message][option] and lua's sync_choice the scenario designer is responsible for that.
194  //For [get_global_variable] side is never null.
195 
196  is_side_null_controlled = resources::gameboard->get_team(side).is_empty();
197 
198  LOG_REPLAY << "get_user_choice_called with"
199  << " name=" << name
200  << " is_synced=" << is_synced
201  << " is_mp_game=" << is_mp_game
202  << " is_side_null_controlled=" << is_side_null_controlled;
203 
204  if (is_side_null_controlled)
205  {
206  DBG_REPLAY << "MP synchronization: side 1 being null-controlled in get_user_choice.";
207  //most likely we are in a start event with an empty side 1
208  //but calling [set_global_variable] to an empty side might also cause this.
209  //i think in that case we should better use uch.random_choice(),
210  //which could return something like config {"invalid", true};
211  side = 1;
212  while ( side <= max_side && resources::gameboard->get_team(side).is_empty() )
213  side++;
214  assert(side <= max_side);
215  }
216 
217 
218  assert(1 <= side && side <= max_side);
219 
220  std::set<int> sides;
221  sides.insert(side);
222  std::map<int, config> retv = user_choice_manager::get_user_choice_internal(name, uch, sides);
223  if(retv.find(side) == retv.end())
224  {
225  //An error occurred, get_user_choice_internal should have given an oos error message
226  return config();
227  }
228  return retv[side];
229 }
230 
231 user_choice_manager::user_choice_manager(const std::string &name, const mp_sync::user_choice &uch, const std::set<int>& sides)
232  : required_(sides)
233  , res_()
234  , local_choice_(0)
235  , wait_message_()
236  , oos_(false)
237  , uch_(uch)
238  , tagname_(name)
239  , current_side_(resources::controller->current_side())
240  , changed_event_("user_choice_update")
241 {
243  const int max_side = static_cast<int>(resources::gameboard->teams().size());
244 
245  for(int side : required_)
246  {
247  assert(1 <= side && side <= max_side);
248  const team& t = resources::gameboard->get_team(side);
249  assert(!t.is_empty());
250  if(side != current_side_)
251  {
253  }
254  }
255 
258 
259 }
260 
262 {
263  while(!finished() && !oos_)
264  {
266  if(resources::recorder->at_end()) {
267  return;
268  }
269 
270  DBG_REPLAY << "MP synchronization: extracting choice from replay with has_local_side=" << has_local_choice();
271 
272  const config *action = resources::recorder->get_next_action();
273  assert(action); //action cannot be null because resources::recorder->at_end() returned false.
274  if( !action->has_child(tagname_) || !(*action)["dependent"].to_bool())
275  {
276  replay::process_error("[" + tagname_ + "] expected but none found\n. found instead:\n" + action->debug());
277  //We save this action for later
279  // execute this local choice locally
280  oos_ = true;
282  return;
283  }
284  int from_side = (*action)["from_side"].to_int(0);
285  if((*action)["side_invalid"].to_bool(false) == true)
286  {
287  //since this 'cheat' can have a quite heavy effect especially in umc content we give an oos error .
288  replay::process_error("MP synchronization: side_invalid in replay data, this could mean someone wants to cheat.\n");
289  }
290  if(required_.find(from_side) == required_.end())
291  {
292  replay::process_error("MP synchronization: we got an answer from side " + std::to_string(from_side) + "for [" + tagname_ + "] which is not was we expected\n");
293  }
294  if(res_.find(from_side) != res_.end())
295  {
296  replay::process_error("MP synchronization: we got already our answer from side " + std::to_string(from_side) + "for [" + tagname_ + "] now we have it twice.\n");
297  }
298  res_[from_side] = action->child(tagname_);
300  }
301 }
303 {
304  // there might be speak or similar commands in the replay before the user input.
310 }
311 
313 {
314  int local_choice_prev = local_choice_;
315  //equals to any side in sides that is local, 0 if no such side exists.
316  local_choice_ = 0;
317  //if for any side from which we need an answer
318  std::vector<t_string> sides_str;
319  for(int side : required_)
320  {
321  //and we haven't already received our answer from that side
322  if(res_.find(side) == res_.end())
323  {
324  sides_str.push_back(std::to_string(side));
325  //and it is local
326  if(resources::gameboard->get_team(side).is_local() && !resources::gameboard->get_team(side).is_idle())
327  {
328  //then we have to make a local choice.
329  local_choice_ = side;
330  break;
331  }
332  }
333  }
334 
335  // TRANSLATORS: In networked games, this text is shown on the map while
336  // waiting for $desc from another player.
337  // Don't end the text with a punctuation sign.
339  "waiting for $desc from side $sides",
340  "waiting for $desc from sides $sides",
341  sides_str.size(),
342  {std::pair("desc", uch_.description()), std::pair("sides", utils::format_conjunct_list("", sides_str))}
343  );
344  if(local_choice_prev != local_choice_) {
346  }
347 }
348 
350 {
351  assert(local_choice_ != 0);
352 
354  /* At least one of the decisions is ours, and it will be inserted
355  into the replay. */
356  DBG_REPLAY << "MP synchronization: local choice";
358  if(res_.find(local_choice_) != res_.end()) {
359  // It might be possible that we this choice was already made by another client while we were in uch_.query_user
360  // because our side might be reassigned while we made our choice.
361  WRN_REPLAY << "Discarding a local choice because we found it already on the replay";
362  return;
363  }
365  res_[local_choice_] = cfg;
366 
367  //send data to others.
368  //but if there wasn't any data sent during this turn, we don't want to begin with that now.
369  //TODO: we should send user choices during nonundoable actions immediately.
371  {
373  }
375 }
376 
378 {
379  assert(oos_);
380  ERR_REPLAY << "A sync error appeared while waiting for a synced user choice of type '" << uch_.description() << "' ([" + tagname_ + "]), doing the choice locally";
381  for(int side : required_)
382  {
383  if(res_.find(side) == res_.end())
384  {
385  ERR_REPLAY << "Doing a local choice for side " << side;
386  res_[side] = uch_.query_user(side);
387  }
388  }
389  oos_ = false;
390 }
391 
393 {
394  user_choice_notifer_ingame notifer;
395  while(!man.finished() && man.waiting())
396  {
398  {
399  //during the prestart/preload event the screen is locked and we shouldn't call user_interact.
400  //because that might result in crashes if someone clicks anywhere during screenlock.
401 
402  // calls man.pull via events.cpp -> pump_monitor::process
404  }
405 
406  notifer.update(man.wait_message());
407  }
408 }
409 
411 {
412  gui2::dialogs::synched_choice_wait::display(man);
413 }
414 
415 std::map<int, config> user_choice_manager::get_user_choice_internal(const std::string &name, const mp_sync::user_choice &uch, const std::set<int>& sides)
416 {
417  const bool is_too_early = resources::gamedata->phase() != game_data::START && resources::gamedata->phase() != game_data::PLAY;
418  user_choice_manager man(name, uch, sides);
419  while(!man.finished())
420  {
421  if(man.waiting())
422  {
423  if(is_too_early) {
424  wait_prestart(man);
425  }
426  else {
427  wait_ingame(man);
428  }
429  }
430  else if(man.has_local_choice())
431  {
432  man.ask_local_choice();
433  }
434  else
435  {
436  man.fix_oos();
437  }
438  }
439  return man.res_;
440 }
441 
442 namespace {
443  // we want to prevent calling pull() while we are already calling pull()
444  // this could for example happen if pull() receives a [side_drop] and
445  // user_choice_manager::process is called while the "player has left the game.
446  // What do you want to do?" dialog is shown.
447  static bool ucm_in_proccess = false;
448  struct ucm_process_scope {
449  ucm_process_scope() { ucm_in_proccess = true; }
450  ~ucm_process_scope() { ucm_in_proccess = false; }
451  };
452 }
454 {
455  if(!oos_ && !finished() && !ucm_in_proccess)
456  {
457  ucm_process_scope scope1;
458  pull();
459  }
460 }
play_controller * controller
Definition: resources.cpp:22
config get_user_choice(const std::string &name, const user_choice &uch, int side=0)
#define DBG_REPLAY
#define LOG_REPLAY
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:402
std::string format_conjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a conjunctive list.
bool is_empty() const
Definition: team.hpp:247
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:98
static lg::log_domain log_replay("replay")
void remove_floating_label(int handle, int fadeout)
removes the floating label given by &#39;handle&#39; from the screen
virtual const std::vector< team > & teams() const override
Definition: game_board.hpp:86
virtual void notify_observers()
static bool is_simultaneous()
void set_clip_rect(const SDL_Rect &r)
std::set< int > required_
const std::string & tagname_
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:394
void set_lifetime(int lifetime, int fadeout=100)
static void set_is_simultaneous()
Sets is_simultaneous_ = true, called using a user choice that is not the currently playing side...
static void wait_ingame(user_choice_manager &man)
user_choice_manager(const std::string &name, const mp_sync::user_choice &uch, const std::set< int > &sides)
virtual void play_slice(bool is_delay_enabled=true)
#define VNGETTEXT(msgid, msgid_plural, count,...)
Replay control code.
virtual std::string description() const
void set_font_size(int font_size)
bool waiting() const
Note: currently finished() does not imply !waiting() so you may need to check both.
void process(events::pump_info &)
Inherited from events::pump_monitor.
std::map< int, config > get_user_choice_multiple_sides(const std::string &name, const user_choice &uch, std::set< int > sides)
Performs a choice for multiple sides for WML events.
virtual config random_choice(int side) const =0
game_data * gamedata
Definition: resources.cpp:23
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:75
team & get_team(int i)
Definition: game_board.hpp:98
void user_input(const std::string &name, const config &input, int from_side)
adds a user_input to the replay
Definition: replay.cpp:258
game_board * gameboard
Definition: resources.cpp:21
Interface for querying local choices.
static std::map< int, config > get_user_choice_internal(const std::string &name, const mp_sync::user_choice &uch, const std::set< int > &sides)
events::generic_event changed_event_
const mp_sync::user_choice & uch_
void set_position(double xpos, double ypos)
map_display and display: classes which take care of displaying the map and game-data on the screen...
replay * recorder
Definition: resources.cpp:29
static void send_user_choice()
called from get_user_choice to send a recently made choice to the other clients.
static void pull_remote_user_input()
called from get_user_choice while waiting for a remove user choice.
virtual config query_user(int side) const =0
static bool is_synced()
const color_t NORMAL_COLOR
void set_color(const color_t &color)
static void process_error(const std::string &msg)
Definition: replay.cpp:199
virtual bool is_networked_mp() const
int current_side_
Definition: move.cpp:315
static void update()
int add_floating_label(const floating_label &flabel)
add a label floating on the screen above everything else.
const int SIZE_LARGE
Definition: constants.cpp:30
#define WRN_REPLAY
double t
Definition: astarsearch.cpp:65
Various functions that implement the undoing (and redoing) of in-game commands.
Standard logging facilities (interface).
int current_side() const
Returns the number of the side whose turn it is.
config * get_next_action()
Definition: replay.cpp:623
virtual bool is_visible() const
whether the choice is visible for the user like an advancement choice a non-visible choice is for exa...
void revert_action()
Definition: replay.cpp:616
rect map_outside_area() const
Returns the available area for a map, this may differ from the above.
Definition: display.cpp:564
A RAII object to temporary leave the synced context like in wesnoth.synchronize_choice.
std::map< int, config > res_
PHASE phase() const
Definition: game_data.hpp:79
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:60
REPLAY_RETURN do_replay_handle(bool one_move)
Definition: replay.cpp:704
const std::string & wait_message() const
std::string debug() const
Definition: config.cpp:1347
static void wait_prestart(user_choice_manager &man)
#define ERR_REPLAY