The Battle for Wesnoth  1.19.5+dev
countdown_clock.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017 - 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 #include "countdown_clock.hpp"
16 
17 #include "team.hpp"
19 #include "sound.hpp"
20 #include "utils/rate_counter.hpp"
21 
22 using namespace std::chrono_literals;
23 
24 namespace {
25  constexpr auto warn_threshold = 20s; // start beeping when 20 seconds are left
26  constexpr auto fade_end = warn_threshold / 2;
27  utils::rate_counter timer_refresh_rate{50};
28 }
29 
31  : team_(team)
32  , last_timestamp_(clock::now())
33  , playing_sound_(false)
34 {
35 }
36 
38 {
39  if(playing_sound_)
40  {
42  }
43 }
44 
45 std::chrono::milliseconds countdown_clock::update_timestamp()
46 {
47  auto now = clock::now();
48  auto prev_time = std::exchange(last_timestamp_, now);
49  return std::chrono::duration_cast<std::chrono::milliseconds>(now - prev_time);
50 }
51 
53 {
54  auto time_passed = update_timestamp();
55  team_.set_countdown_time(std::max(0ms, team_.countdown_time() - time_passed));
56 }
57 
58 //make sure we think about countdown even while dialogs are open
60 {
61  if(timer_refresh_rate.poll()) {
62  update();
63  }
64 }
65 
67 {
68  update_team();
70  return team_.countdown_time() > 0ms;
71 }
72 
74 {
75  if(!playing_sound_ && team_.countdown_time() < warn_threshold )
76  {
78  {
79  const auto loop_ticks = team_.countdown_time();
80  const auto fadein_ticks = std::max(loop_ticks - fade_end, 0ms);
81  sound::play_timer(game_config::sounds::timer_bell, loop_ticks, fadein_ticks);
82  playing_sound_ = true;
83  }
84  }
85 }
countdown_clock(team &team)
std::chrono::steady_clock clock
clock::time_point last_timestamp_
virtual void process() override
Inherited from pump_monitor.
std::chrono::milliseconds update_timestamp()
static prefs & get()
This class stores all the data for a single 'side' (in game nomenclature).
Definition: team.hpp:75
void set_countdown_time(const std::chrono::milliseconds &amount) const
Definition: team.hpp:198
std::chrono::milliseconds countdown_time() const
Definition: team.hpp:197
std::string turn_bell
std::string timer_bell
static bool sound()
static bool ui_sound_on()
void stop_bell()
Definition: sound.cpp:580
void play_timer(const std::string &files, const std::chrono::milliseconds &loop_ticks, const std::chrono::milliseconds &fadein_ticks)
Definition: sound.cpp:1069
static map_location::direction s