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