Skip to content

Instantly share code, notes, and snippets.

@gfgtdf
Created October 7, 2018 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfgtdf/acdf3cd4ed88088eb5854d8e73701f94 to your computer and use it in GitHub Desktop.
Save gfgtdf/acdf3cd4ed88088eb5854d8e73701f94 to your computer and use it in GitHub Desktop.
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 30272144975..b5c8c132124 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -20,6 +20,8 @@ include_directories(SYSTEM ${PANGOCAIRO_INCLUDE_DIRS} )
include_directories(SYSTEM ${GETTEXT_INCLUDE_DIR} )
include_directories(SYSTEM ${LIBDBUS_INCLUDE_DIRS} )
include_directories(SYSTEM ${VORBISFILE_INCLUDE_DIR} )
+include_directories(SYSTEM ${GLEW_INCLUDE_DIRS})
+include_directories(SYSTEM ${OPENGL_INCLUDE_DIR})
include_directories(SYSTEM ${SDL2_INCLUDE_DIR} )
set(sdl-lib ${SDL2_LIBRARY})
@@ -82,6 +84,8 @@ set(game-external-libs
${FONTCONFIG_LIBRARIES}
${LIBDBUS_LIBRARIES}
${VORBISFILE_LIBRARIES}
+ ${OPENGL_LIBRARIES}
+ ${GLEW_LIBRARIES}
)
if(ENABLE_HISTORY AND HISTORY_FOUND)
@@ -94,15 +98,10 @@ endif(ENABLE_HISTORY AND HISTORY_FOUND)
set(server-external-libs
${common-external-libs}
${Boost_SYSTEM_LIBRARIES}
- -lpthread
-)
-
-set(tools-external-libs
- ${common-external-libs}
- ${sdl_image-lib}
- ${Boost_FILESYSTEM_LIBRARY}
- ${Boost_SYSTEM_LIBRARIES}
${Boost_RANDOM_LIBRARY}
+ ${CRYPTO_LIBRARY}
+ ${MYSQL_LIBS}
+ -lpthread
)
if(ENABLE_FRIBIDI AND FRIBIDI_FOUND)
@@ -115,9 +114,6 @@ if(X11_FOUND)
set(game-external-libs ${game-external-libs} ${X11_LIBRARIES})
endif(X11_FOUND)
-if(APPLE)
- set(game-external-libs ${game-external-libs} "-framework IOKit")
-endif(APPLE)
########### Set Library mode ###############
if(ENABLE_SHARED_LIBRARIES)
@@ -257,12 +253,11 @@ endif(ENABLE_GAME OR ENABLE_TESTS)
GetSources("libwesnoth" libwesnoth-game_STAT_SRC)
-# On windows only, these files need to be linked, as their headers are included #ifdef win32.
+# On windows only, this file needs to be linked, as its header is included #ifdef win32.
if(WIN32)
set(libwesnoth-game_STAT_SRC
${libwesnoth-game_STAT_SRC}
desktop/windows_tray_notification.cpp
- desktop/windows_battery_info.cpp
)
endif(WIN32)
@@ -270,7 +265,6 @@ endif(WIN32)
if(APPLE)
set(libwesnoth-game_STAT_SRC
${libwesnoth-game_STAT_SRC}
- desktop/apple_battery_info.mm
desktop/apple_notification.mm
desktop/apple_version.mm
)
@@ -280,7 +274,7 @@ endif(APPLE)
if(LIBDBUS_FOUND)
set(libwesnoth-game_STAT_SRC
${libwesnoth-game_STAT_SRC}
- desktop/dbus_features.cpp
+ desktop/dbus_notification.cpp
)
endif(LIBDBUS_FOUND)
@@ -293,11 +287,8 @@ add_library(wesnoth-game ${LIBRARY_TYPE} EXCLUDE_FROM_ALL ${libwesnoth-game_STAT
if(ENABLE_GAME)
if(NOT APPLE)
add_executable(wesnoth WIN32 wesnoth.cpp)
- else()
- add_executable(wesnoth WIN32 wesnoth.cpp macosx/SDLMain.mm)
- endif(NOT APPLE)
- target_link_libraries(wesnoth
+ set(static-libs -Wl,--start-group
wesnoth-client
lua
wesnoth-core
@@ -305,6 +296,21 @@ if(ENABLE_GAME)
wesnoth-sdl
${WIDGETS_LIB}
wesnoth-client
+ -Wl,--end-group)
+ else()
+ add_executable(wesnoth WIN32 wesnoth.cpp macosx/SDLMain.mm)
+
+ set(static-libs wesnoth-client
+ lua
+ wesnoth-core
+ wesnoth-game
+ wesnoth-sdl
+ ${WIDGETS_LIB}
+ wesnoth-client)
+ endif(NOT APPLE)
+
+ target_link_libraries(wesnoth
+ ${static-libs}
${game-external-libs}
)
set_target_properties(wesnoth
@@ -330,9 +336,6 @@ if(ENABLE_SERVER)
target_link_libraries(wesnothd
wesnoth-core
${server-external-libs}
- ${Boost_RANDOM_LIBRARY}
- ${CRYPTO_LIBRARY}
- ${MYSQL_LIBS}
)
set_target_properties(wesnothd PROPERTIES OUTPUT_NAME ${BINARY_PREFIX}wesnothd${BINARY_SUFFIX})
@@ -356,9 +359,6 @@ if(ENABLE_CAMPAIGN_SERVER)
target_link_libraries(campaignd
wesnoth-core
${server-external-libs}
- ${CRYPTO_LIBRARY}
- ${Boost_RANDOM_LIBRARY}
- ${MYSQL_LIBS}
)
set_target_properties(campaignd PROPERTIES OUTPUT_NAME ${BINARY_PREFIX}campaignd${BINARY_SUFFIX})
@@ -383,7 +383,8 @@ if(ENABLE_TESTS)
add_executable(boost_unit_tests ${test_SRC})
- target_link_libraries(boost_unit_tests
+ if(NOT APPLE)
+ set(static-libs -Wl,--start-group
wesnoth-client
lua
wesnoth-core
@@ -391,6 +392,19 @@ if(ENABLE_TESTS)
wesnoth-sdl
${WIDGETS_LIB}
wesnoth-client
+ -Wl,--end-group)
+ else()
+ set(static-libs wesnoth-client
+ lua
+ wesnoth-core
+ wesnoth-game
+ wesnoth-sdl
+ ${WIDGETS_LIB}
+ wesnoth-client)
+ endif(NOT APPLE)
+
+ target_link_libraries(boost_unit_tests
+ ${static-libs}
${game-external-libs}
boost_unit_test_framework
)
diff --git a/src/SConscript b/src/SConscript
index 3101219e53d..035617e0b84 100644
--- a/src/SConscript
+++ b/src/SConscript
@@ -87,15 +87,13 @@ wesnoth_client_sources = GetSources("wesnoth")
if env["PLATFORM"] == "win32":
wesnoth_client_sources.append("desktop/windows_tray_notification.cpp")
- wesnoth_client_sources.append("desktop/windows_battery_info.cpp")
if env["PLATFORM"] == 'darwin':
- wesnoth_client_sources.append("desktop/apple_battery_info.mm")
wesnoth_client_sources.append("desktop/apple_notification.mm")
wesnoth_client_sources.append("desktop/apple_version.mm")
if env["notifications"]:
- wesnoth_client_sources.append("desktop/dbus_features.cpp")
+ wesnoth_client_sources.append("desktop/dbus_notification.cpp")
libwesnoth_client = client_env.Library("wesnoth-client", wesnoth_client_sources)
diff --git a/src/actions/advancement.cpp b/src/actions/advancement.cpp
index af80dfe3501..74dc083c141 100644
--- a/src/actions/advancement.cpp
+++ b/src/actions/advancement.cpp
@@ -26,7 +26,6 @@
#include "game_data.hpp" //resources::gamedata->phase()
#include "gettext.hpp"
#include "gui/dialogs/unit_advance.hpp"
-#include "gui/widgets/retval.hpp" //gui2::retval::OK
#include "log.hpp"
#include "play_controller.hpp" //resources::controller
#include "random.hpp"
@@ -78,9 +77,7 @@ namespace
if (previews.size() > 1 || always_display) {
gui2::dialogs::unit_advance dlg(previews, num_real_advances);
- dlg.show();
-
- if (dlg.get_retval() == gui2::retval::OK) {
+ if(dlg.show()) {
return dlg.get_selected_index();
}
diff --git a/src/actions/attack.cpp b/src/actions/attack.cpp
index 43ae7ae65dd..fd7cdc1437b 100644
--- a/src/actions/attack.cpp
+++ b/src/actions/attack.cpp
@@ -55,12 +55,6 @@ static lg::log_domain log_engine("engine");
#define WRN_NG LOG_STREAM(err, log_engine)
#define ERR_NG LOG_STREAM(err, log_engine)
-static lg::log_domain log_attack("engine/attack");
-#define DBG_AT LOG_STREAM(debug, log_attack)
-#define LOG_AT LOG_STREAM(info, log_attack)
-#define WRN_AT LOG_STREAM(err, log_attack)
-#define ERR_AT LOG_STREAM(err, log_attack)
-
static lg::log_domain log_config("config");
#define LOG_CF LOG_STREAM(info, log_config)
@@ -132,7 +126,7 @@ battle_context_unit_stats::battle_context_unit_stats(const unit& u,
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
- opp_ctx = opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon);
+ opp_ctx.emplace(opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon));
}
slows = weapon->get_special_bool("slow");
@@ -189,13 +183,13 @@ battle_context_unit_stats::battle_context_unit_stats(const unit& u,
resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
// Leadership bonus.
- int leader_bonus = under_leadership(units, u_loc).first;
+ int leader_bonus = under_leadership(units, u_loc, weapon, opp_weapon).first;
if(leader_bonus != 0) {
damage_multiplier += leader_bonus;
}
// Resistance modifier.
- damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc);
+ damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon);
// Compute both the normal and slowed damage.
damage = round_damage(base_damage, damage_multiplier, 10000);
@@ -289,7 +283,7 @@ battle_context_unit_stats::battle_context_unit_stats(const unit_type* u_type,
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
- opp_ctx = opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking);
+ opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
}
slows = weapon->get_special_bool("slow");
@@ -355,42 +349,6 @@ battle_context_unit_stats::battle_context_unit_stats(const unit_type* u_type,
// BATTLE CONTEXT
// ==================================================================================
-battle_context::battle_context(
- const unit& attacker,
- const map_location& a_loc,
- int a_wep_index,
- const unit& defender,
- const map_location& d_loc,
- int d_wep_index,
- const unit_map& units)
- : attacker_stats_()
- , defender_stats_()
- , attacker_combatant_()
- , defender_combatant_()
-{
- size_t a_wep_uindex = static_cast<size_t>(a_wep_index);
- size_t d_wep_uindex = static_cast<size_t>(d_wep_index);
-
- const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr);
- const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr);
-
- attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units));
- defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units));
-}
-
-void battle_context::simulate(const combatant* prev_def)
-{
- assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr));
- assert(attacker_stats_);
- assert(defender_stats_);
- if(!attacker_combatant_) {
- attacker_combatant_.reset(new combatant(*attacker_stats_));
- defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
- attacker_combatant_->fight(*defender_combatant_);
- }
-}
-
-// more like a factory method than a constructor, always calls one of the other constructors.
battle_context::battle_context(const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
@@ -409,19 +367,43 @@ battle_context::battle_context(const unit_map& units,
const double harm_weight = 1.0 - aggression;
if(attacker_weapon == -1) {
- *this = choose_attacker_weapon(
- attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def
+ attacker_weapon = choose_attacker_weapon(
+ attacker, defender, units, attacker_loc, defender_loc, harm_weight, &defender_weapon, prev_def
);
- }
- else if(defender_weapon == -1) {
- *this = choose_defender_weapon(
+ } else if(defender_weapon == -1) {
+ defender_weapon = choose_defender_weapon(
attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
);
}
- else {
- *this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units);
+
+ // If those didn't have to generate statistics, do so now.
+ if(!attacker_stats_) {
+ const_attack_ptr adef = nullptr;
+ const_attack_ptr ddef = nullptr;
+
+ if(attacker_weapon >= 0) {
+ VALIDATE(attacker_weapon < static_cast<int>(attacker.attacks().size()),
+ _("An invalid attacker weapon got selected."));
+
+ adef = attacker.attacks()[attacker_weapon].shared_from_this();
+ }
+
+ if(defender_weapon >= 0) {
+ VALIDATE(defender_weapon < static_cast<int>(defender.attacks().size()),
+ _("An invalid defender weapon got selected."));
+
+ ddef = defender.attacks()[defender_weapon].shared_from_this();
+ }
+
+ assert(!defender_stats_ && !attacker_combatant_ && !defender_combatant_);
+
+ attacker_stats_.reset(new battle_context_unit_stats(
+ attacker, attacker_loc, attacker_weapon, true, defender, defender_loc, ddef, units));
+ defender_stats_.reset(new battle_context_unit_stats(
+ defender, defender_loc, defender_weapon, false, attacker, attacker_loc, adef, units));
}
+ // There have been various bugs where only one of these was set
assert(attacker_stats_);
assert(defender_stats_);
}
@@ -434,24 +416,64 @@ battle_context::battle_context(const battle_context_unit_stats& att, const battl
{
}
+battle_context::battle_context(const battle_context& other)
+ : attacker_stats_(nullptr)
+ , defender_stats_(nullptr)
+ , attacker_combatant_(nullptr)
+ , defender_combatant_(nullptr)
+{
+ *this = other;
+}
+
+battle_context& battle_context::operator=(const battle_context& other)
+{
+ if(&other != this) {
+ attacker_stats_.reset(new battle_context_unit_stats(*other.attacker_stats_));
+ defender_stats_.reset(new battle_context_unit_stats(*other.defender_stats_));
+
+ attacker_combatant_.reset(other.attacker_combatant_
+ ? new combatant(*other.attacker_combatant_, *attacker_stats_) : nullptr);
+
+ defender_combatant_.reset(other.defender_combatant_
+ ? new combatant(*other.defender_combatant_, *defender_stats_) : nullptr);
+ }
+
+ return *this;
+}
/** @todo FIXME: better to initialize combatant initially (move into
battle_context_unit_stats?), just do fight() when required. */
const combatant& battle_context::get_attacker_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
- simulate(prev_def);
+ if(!attacker_combatant_) {
+ assert(!defender_combatant_);
+
+ attacker_combatant_.reset(new combatant(*attacker_stats_));
+ defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
+
+ attacker_combatant_->fight(*defender_combatant_);
+ }
+
return *attacker_combatant_;
}
const combatant& battle_context::get_defender_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
- simulate(prev_def);
+ if(!defender_combatant_) {
+ assert(!attacker_combatant_);
+
+ attacker_combatant_.reset(new combatant(*attacker_stats_));
+ defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
+
+ attacker_combatant_->fight(*defender_combatant_);
+ }
+
return *defender_combatant_;
}
-// Given this harm_weight, are we better than that other context?
+// Given this harm_weight, are we better than this other context?
bool battle_context::better_attack(class battle_context& that, double harm_weight)
{
return better_combat(
@@ -463,18 +485,6 @@ bool battle_context::better_attack(class battle_context& that, double harm_weigh
);
}
-// Given this harm_weight, are we better than that other context?
-bool battle_context::better_defense(class battle_context& that, double harm_weight)
-{
- return better_combat(
- get_defender_combatant(),
- get_attacker_combatant(),
- that.get_defender_combatant(),
- that.get_attacker_combatant(),
- harm_weight
- );
-}
-
// Does combat A give us a better result than combat B?
bool battle_context::better_combat(const combatant& us_a,
const combatant& them_a,
@@ -518,61 +528,124 @@ bool battle_context::better_combat(const combatant& us_a,
return them_a.average_hp() < them_b.average_hp();
}
-battle_context battle_context::choose_attacker_weapon(const unit& attacker,
+int battle_context::choose_attacker_weapon(const unit& attacker,
const unit& defender,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
double harm_weight,
+ int* defender_weapon,
const combatant* prev_def)
{
- log_scope2(log_attack, "choose_attacker_weapon");
- std::vector<battle_context> choices;
+ std::vector<unsigned int> choices;
// What options does attacker have?
- for(size_t i = 0; i < attacker.attacks().size(); ++i) {
+ unsigned int i;
+
+ for(i = 0; i < attacker.attacks().size(); ++i) {
const attack_type& att = attacker.attacks()[i];
- if(att.attack_weight() <= 0) {
- continue;
+ if(att.attack_weight() > 0) {
+ choices.push_back(i);
}
- battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def);
- //choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible.
- if(bc.attacker_stats_->disable) {
- continue;
- }
- choices.emplace_back(std::move(bc));
}
if(choices.empty()) {
- return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
+ return -1;
}
if(choices.size() == 1) {
- return std::move(choices[0]);
+ *defender_weapon
+ = choose_defender_weapon(attacker, defender, choices[0], units, attacker_loc, defender_loc, prev_def);
+ const_attack_ptr def_weapon
+ = *defender_weapon >= 0 ? defender.attacks()[*defender_weapon].shared_from_this() : nullptr;
+ attacker_stats_.reset(new battle_context_unit_stats(
+ attacker, attacker_loc, choices[0], true, defender, defender_loc, def_weapon, units));
+
+ if(attacker_stats_->disable) {
+ attacker_stats_.reset();
+ return -1;
+ }
+
+ const attack_type& att = attacker.attacks()[choices[0]];
+ defender_stats_.reset(new battle_context_unit_stats(
+ defender, defender_loc, *defender_weapon, false, attacker, attacker_loc, att.shared_from_this(), units));
+
+ return choices[0];
}
// Multiple options: simulate them, save best.
- battle_context* best_choice = nullptr;
- for(auto& choice : choices) {
- // If choose_defender_weapon didn't simulate, do so now.
- choice.simulate(prev_def);
+ std::unique_ptr<battle_context_unit_stats> best_att_stats(nullptr);
+ std::unique_ptr<battle_context_unit_stats> best_def_stats(nullptr);
+
+ std::unique_ptr<combatant> best_att_comb(nullptr);
+ std::unique_ptr<combatant> best_def_comb(nullptr);
+
+ for(i = 0; i < choices.size(); ++i) {
+ const attack_type& att = attacker.attacks()[choices[i]];
+
+ int def_weapon =
+ choose_defender_weapon(attacker, defender, choices[i], units, attacker_loc, defender_loc, prev_def);
+
+ // If that didn't simulate, do so now.
+ if(!attacker_combatant_) {
+ const_attack_ptr def = nullptr;
+
+ if(def_weapon >= 0) {
+ def = defender.attacks()[def_weapon].shared_from_this();
+ }
+
+ attacker_stats_.reset(new battle_context_unit_stats(
+ attacker, attacker_loc, choices[i], true, defender, defender_loc, def, units));
+
+ if(attacker_stats_->disable) {
+ continue;
+ }
+
+ defender_stats_.reset(new battle_context_unit_stats(
+ defender, defender_loc, def_weapon, false, attacker, attacker_loc, att.shared_from_this(), units));
- if(!best_choice || choice.better_attack(*best_choice, harm_weight)) {
- best_choice = &choice;
+ attacker_combatant_.reset(new combatant(*attacker_stats_));
+ defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
+
+ attacker_combatant_->fight(*defender_combatant_);
+ } else {
+ if(attacker_stats_ != nullptr && attacker_stats_->disable) {
+ continue;
+ }
}
- }
- if(best_choice) {
- return std::move(*best_choice);
+ if(!best_att_comb ||
+ better_combat(*attacker_combatant_, *defender_combatant_, *best_att_comb, *best_def_comb, harm_weight)
+ ) {
+ best_att_comb = std::move(attacker_combatant_);
+ best_def_comb = std::move(defender_combatant_);
+ best_att_stats = std::move(attacker_stats_);
+ best_def_stats = std::move(defender_stats_);
+ }
+
+ attacker_combatant_.reset();
+ defender_combatant_.reset();
+ attacker_stats_.reset();
+ defender_stats_.reset();
}
- else {
- return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
+
+ attacker_combatant_ = std::move(best_att_comb);
+ defender_combatant_ = std::move(best_def_comb);
+ attacker_stats_ = std::move(best_att_stats);
+ defender_stats_ = std::move(best_def_stats);
+
+ // These currently mean the same thing, but assumptions like that have been broken before
+ if(!defender_stats_ || !attacker_stats_) {
+ return -1;
}
+
+ *defender_weapon = defender_stats_->attack_num;
+ return attacker_stats_->attack_num;
}
/** @todo FIXME: Hand previous defender unit in here. */
-battle_context battle_context::choose_defender_weapon(const unit& attacker,
+int battle_context::choose_defender_weapon(const unit& attacker,
const unit& defender,
unsigned attacker_weapon,
const unit_map& units,
@@ -580,39 +653,31 @@ battle_context battle_context::choose_defender_weapon(const unit& attacker,
const map_location& defender_loc,
const combatant* prev_def)
{
- log_scope2(log_attack, "choose_defender_weapon");
VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
const attack_type& att = attacker.attacks()[attacker_weapon];
- auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); };
- std::vector<battle_context> choices;
+ std::vector<unsigned int> choices;
// What options does defender have?
- for(size_t i = 0; i < defender.attacks().size(); ++i) {
+ unsigned int i;
+
+ for(i = 0; i < defender.attacks().size(); ++i) {
const attack_type& def = defender.attacks()[i];
- if(def.range() != att.range() || def.defense_weight() <= 0) {
- //no need to calculate the battle_context here.
- continue;
- }
- battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units);
- if(bc.defender_stats_->disable) {
- continue;
+ if(def.range() == att.range() && def.defense_weight() > 0) {
+ choices.push_back(i);
}
- if(bc.attacker_stats_->disable) {
- //the defenders attack disables the attakers attack: always choose this one.
- return bc;
- }
- choices.emplace_back(std::move(bc));
}
if(choices.empty()) {
- return no_weapon();
+ return -1;
}
if(choices.size() == 1) {
- //only one usable weapon, don't simulate
- return std::move(choices[0]);
+ const battle_context_unit_stats def_stats(
+ defender, defender_loc, choices[0], false, attacker, attacker_loc, att.shared_from_this(), units);
+
+ return (def_stats.disable) ? -1 : choices[0];
}
// Multiple options:
@@ -624,11 +689,16 @@ battle_context battle_context::choose_defender_weapon(const unit& attacker,
{
double max_weight = 0.0;
- for(const auto& choice : choices) {
- const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
+ for(i = 0; i < choices.size(); ++i) {
+ const attack_type& def = defender.attacks()[choices[i]];
if(def.defense_weight() >= max_weight) {
- const battle_context_unit_stats& def_stats = *choice.defender_stats_;
+ const battle_context_unit_stats def_stats(defender, defender_loc, choices[i], false, attacker,
+ attacker_loc, att.shared_from_this(), units);
+
+ if(def_stats.disable) {
+ continue;
+ }
max_weight = def.defense_weight();
int rating = static_cast<int>(
@@ -641,23 +711,39 @@ battle_context battle_context::choose_defender_weapon(const unit& attacker,
}
}
- battle_context* best_choice = nullptr;
// Multiple options: simulate them, save best.
- for(auto& choice : choices) {
- const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
+ for(i = 0; i < choices.size(); ++i) {
+ const attack_type& def = defender.attacks()[choices[i]];
- choice.simulate(prev_def);
+ auto att_stats = std::make_unique<battle_context_unit_stats>(
+ attacker, attacker_loc, attacker_weapon, true, defender, defender_loc, def.shared_from_this(), units);
- int simple_rating = static_cast<int>(
- choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight());
+ auto def_stats = std::make_unique<battle_context_unit_stats>(
+ defender, defender_loc, choices[i], false, attacker, attacker_loc, att.shared_from_this(), units);
- //FIXME: make sure there is no mostake in the better_combat call-
- if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) {
- best_choice = &choice;
+ if(def_stats->disable) {
+ continue;
+ }
+
+ auto att_comb = std::make_unique<combatant>(*att_stats);
+ auto def_comb = std::make_unique<combatant>(*def_stats, prev_def);
+
+ att_comb->fight(*def_comb);
+
+ int simple_rating = static_cast<int>(
+ def_stats->num_blows * def_stats->damage * def_stats->chance_to_hit * def.defense_weight());
+
+ if(simple_rating >= min_rating &&
+ (!attacker_combatant_ || better_combat(*def_comb, *att_comb, *defender_combatant_, *attacker_combatant_, 1.0))
+ ) {
+ attacker_combatant_ = std::move(att_comb);
+ defender_combatant_ = std::move(def_comb);
+ attacker_stats_ = std::move(att_stats);
+ defender_stats_ = std::move(def_stats);
}
}
- return best_choice ? std::move(*best_choice) : no_weapon();
+ return defender_stats_ ? defender_stats_->attack_num : -1;
}
@@ -838,7 +924,7 @@ attack::attack(const map_location& attacker,
void attack::fire_event(const std::string& n)
{
- LOG_NG << "attack: firing '" << n << "' event\n";
+ LOG_NG << "firing " << n << " event\n";
// prepare the event data for weapon filtering
config ev_data;
@@ -850,18 +936,18 @@ void attack::fire_event(const std::string& n)
if(a_stats_->weapon != nullptr && a_.valid()) {
if(d_stats_->weapon != nullptr && d_.valid()) {
- a_ctx = a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon);
+ a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon));
} else {
- a_ctx = a_stats_->weapon->specials_context(nullptr, a_.loc_, true);
+ a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true));
}
a_stats_->weapon->write(a_weapon_cfg);
}
if(d_stats_->weapon != nullptr && d_.valid()) {
if(a_stats_->weapon != nullptr && a_.valid()) {
- d_ctx = d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon);
+ d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon));
} else {
- d_ctx = d_stats_->weapon->specials_context(nullptr, d_.loc_, false);
+ d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false));
}
d_stats_->weapon->write(d_weapon_cfg);
}
@@ -1372,8 +1458,8 @@ void attack::perform()
d_.orig_attacks_ = d_stats_->num_blows;
a_.n_attacks_ = a_.orig_attacks_;
d_.n_attacks_ = d_.orig_attacks_;
- a_.xp_ = d_.get_unit().level();
- d_.xp_ = a_.get_unit().level();
+ a_.xp_ = game_config::combat_xp(d_.get_unit().level());
+ d_.xp_ = game_config::combat_xp(a_.get_unit().level());
bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1;
@@ -1549,14 +1635,14 @@ void attack_unit_and_advance(const map_location& attacker,
}
}
-std::pair<int, map_location> under_leadership(const unit_map& units, const map_location& loc)
+std::pair<int, map_location> under_leadership(const unit_map& units, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
{
const unit_map::const_iterator un = units.find(loc);
if(un == units.end()) {
return {0, map_location::null_location()};
}
- unit_ability_list abil = un->get_abilities("leadership");
+ unit_ability_list abil = un->get_abilities("leadership", weapon, opp_weapon);
return abil.highest("value");
}
diff --git a/src/actions/attack.hpp b/src/actions/attack.hpp
index bf41ce3d97c..2c90369a75b 100644
--- a/src/actions/attack.hpp
+++ b/src/actions/attack.hpp
@@ -188,8 +188,10 @@ public:
/** Used by the AI which caches battle_context_unit_stats */
battle_context(const battle_context_unit_stats& att, const battle_context_unit_stats& def);
+ battle_context(const battle_context& other);
battle_context(battle_context&& other) = default;
+ battle_context& operator=(const battle_context& other);
battle_context& operator=(battle_context&& other) = default;
/** This method returns the statistics of the attacker. */
@@ -210,8 +212,6 @@ public:
/** Given this harm_weight, is this attack better than that? */
bool better_attack(class battle_context& that, double harm_weight);
- /** Given this harm_weight, is this attack better than that? */
- bool better_defense(class battle_context& that, double harm_weight);
static bool better_combat(const combatant& us_a,
const combatant& them_a,
@@ -219,26 +219,17 @@ public:
const combatant& them_b,
double harm_weight);
- void simulate(const combatant* prev_def);
private:
- battle_context(
- const unit& attacker,
- const map_location& attacker_loc,
- int attacker_weapon,
- const unit& defender,
- const map_location& defender_loc,
- int defender_weapon,
- const unit_map& units);
-
- static battle_context choose_attacker_weapon(const unit& attacker,
+ int choose_attacker_weapon(const unit& attacker,
const unit& defender,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
double harm_weight,
+ int* defender_weapon,
const combatant* prev_def);
- static battle_context choose_defender_weapon(const unit& attacker,
+ int choose_defender_weapon(const unit& attacker,
const unit& defender,
unsigned attacker_weapon,
const unit_map& units,
@@ -277,7 +268,7 @@ void attack_unit_and_advance(const map_location& attacker,
* Returns a pair of bonus percentage and the leader's location if the unit is affected,
* or 0 and map_location::null_location() otherwise.
*/
-std::pair<int, map_location> under_leadership(const unit_map& units, const map_location& loc);
+std::pair<int, map_location> under_leadership(const unit_map& units, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon = nullptr);
/**
* Returns the amount that a unit's damage should be multiplied by
diff --git a/src/actions/create.cpp b/src/actions/create.cpp
index 5bece404276..780de4ecad0 100644
--- a/src/actions/create.cpp
+++ b/src/actions/create.cpp
@@ -83,7 +83,7 @@ const std::set<std::string> get_recruits(int side, const map_location &recruit_l
local_result.insert(find_it->recruits().begin(),
find_it->recruits().end());
}
- else if ( find_it->is_visible_to_team(current_team, *resources::gameboard, false) )
+ else if ( find_it->is_visible_to_team(current_team, false) )
{
// This hex is visibly occupied, so we cannot recruit here.
allow_local = false;
@@ -130,7 +130,7 @@ namespace { // Helpers for get_recalls()
std::set<size_t> * already_added = nullptr)
{
const team& leader_team = resources::gameboard->get_team(leader->side());
- std::string save_id = leader_team.save_id_or_number();
+ const std::string& save_id = leader_team.save_id_or_number();
const unit_filter ufilt(vconfig(leader->recall_filter()));
@@ -184,7 +184,7 @@ std::vector<unit_const_ptr > get_recalls(int side, const map_location &recall_lo
add_leader_filtered_recalls(find_it.get_shared_ptr(), result);
return result;
}
- else if ( find_it->is_visible_to_team(resources::gameboard->get_team(side), *resources::gameboard, false) )
+ else if ( find_it->is_visible_to_team(resources::gameboard->get_team(side), false) )
{
// This hex is visibly occupied, so we cannot recall here.
allow_local = false;
@@ -585,7 +585,7 @@ namespace { // Helpers for place_recruit()
for ( unit_itor = units.begin(); unit_itor != units.end(); ++unit_itor ) {
if (resources::gameboard->get_team(unit_itor->side()).is_enemy(new_unit.side()) &&
- unit_itor->is_visible_to_team(resources::gameboard->get_team(new_unit.side()), *resources::gameboard, false)) {
+ unit_itor->is_visible_to_team(resources::gameboard->get_team(new_unit.side()), false)) {
int dist = distance_between(unit_itor->get_location(),recruit_loc) - unit_itor->level();
if (dist < min_dist) {
min_dist = dist;
diff --git a/src/actions/heal.cpp b/src/actions/heal.cpp
index a1c2a817f32..55101aac39a 100644
--- a/src/actions/heal.cpp
+++ b/src/actions/heal.cpp
@@ -349,7 +349,7 @@ void calculate_healing(int side, bool update_display)
const team & viewing_team =
resources::gameboard->teams()[display::get_singleton()->viewing_team()];
if (!resources::controller->is_skipping_replay() && update_display &&
- patient.is_visible_to_team(viewing_team, *resources::gameboard, false) )
+ patient.is_visible_to_team(viewing_team, false) )
{
unit_list.emplace_front(patient, healers, healing, curing == POISON_CURE);
}
diff --git a/src/actions/move.cpp b/src/actions/move.cpp
index 53bfa1e0c1e..c5455ff1709 100644
--- a/src/actions/move.cpp
+++ b/src/actions/move.cpp
@@ -428,7 +428,7 @@ namespace { // Private helpers for move_unit()
if ( neighbor_it != units.end() &&
current_team_->is_enemy(neighbor_it->side()) &&
- neighbor_it->invisible(adjacent[i], *resources::gameboard) )
+ neighbor_it->invisible(adjacent[i]) )
{
// Ambushed!
ambushed_ = true;
@@ -751,7 +751,7 @@ namespace { // Private helpers for move_unit()
if ( start != begin_ ) {
// Check for being unable to leave the current hex.
- if ( !move_it_->get_ability_bool("skirmisher", *start, *resources::gameboard) &&
+ if ( !move_it_->get_ability_bool("skirmisher", *start) &&
pathfind::enemy_zoc(*current_team_, *start, *current_team_) )
zoc_stop_ = *start;
}
@@ -774,7 +774,7 @@ namespace { // Private helpers for move_unit()
moves_left_.push_back(remaining_moves);
// Check for being unable to leave this hex.
- if (!move_it_->get_ability_bool("skirmisher", *end, *resources::gameboard) &&
+ if (!move_it_->get_ability_bool("skirmisher", *end) &&
pathfind::enemy_zoc(*current_team_, *end, *current_team_))
{
zoc_stop_ = *end;
diff --git a/src/actions/vision.cpp b/src/actions/vision.cpp
index 32a89a9826e..3b190adaff4 100644
--- a/src/actions/vision.cpp
+++ b/src/actions/vision.cpp
@@ -599,7 +599,7 @@ std::vector<int> get_sides_not_seeing(const unit & target)
size_t team_size = teams.size();
for ( size_t i = 0; i != team_size; ++i)
- if ( !target.is_visible_to_team(teams[i], *resources::gameboard, false) )
+ if ( !target.is_visible_to_team(teams[i], false) )
// not_see contains side numbers; i is a team index, so add 1.
not_seeing.push_back(i+1);
@@ -646,7 +646,7 @@ game_events::pump_result_t actor_sighted(const unit & target, const std::vector<
needs_event[target.side()-1] = false;
// Exclude those teams that cannot see the target.
for ( size_t i = 0; i != teams_size; ++i )
- needs_event[i] = needs_event[i] && target.is_visible_to_team(teams[i], *resources::gameboard, false);
+ needs_event[i] = needs_event[i] && target.is_visible_to_team(teams[i], false);
// Cache "jamming".
std::vector< std::map<map_location, int>> jamming_cache(teams_size);
diff --git a/src/addon/client.cpp b/src/addon/client.cpp
index 2f0a0297cd2..f9d5aefa0a0 100644
--- a/src/addon/client.cpp
+++ b/src/addon/client.cpp
@@ -28,6 +28,7 @@
#include "random.hpp"
#include "serialization/parser.hpp"
#include "serialization/string_utils.hpp"
+#include "serialization/utf8_exception.hpp"
#include <stdexcept>
@@ -332,7 +333,7 @@ addons_client::install_result addons_client::do_resolve_addon_dependencies(const
result.outcome = install_outcome::success;
result.wml_changed = false;
- std::unique_ptr<cursor::setter> cursor_setter(new cursor::setter(cursor::WAIT));
+ auto cursor_setter = std::make_unique<cursor::setter>(cursor::WAIT);
// TODO: We don't currently check for the need to upgrade. I'll probably
// work on that when implementing dependency tiers later.
diff --git a/src/addon/info.cpp b/src/addon/info.cpp
index 66caccd4810..a86b6ab30ce 100644
--- a/src/addon/info.cpp
+++ b/src/addon/info.cpp
@@ -17,7 +17,6 @@
#include "addon/manager.hpp"
#include "config.hpp"
#include "font/pango/escape.hpp"
-#include "game_config.hpp"
#include "gettext.hpp"
#include "picture.hpp"
#include "log.hpp"
diff --git a/src/addon/validation.cpp b/src/addon/validation.cpp
index df5ad18b2cb..90f55f66d05 100644
--- a/src/addon/validation.cpp
+++ b/src/addon/validation.cpp
@@ -60,7 +60,7 @@ namespace {
struct addon_filename_ucs4char_illegal
{
- inline bool operator()(ucs4::char_t c) const
+ inline bool operator()(char32_t c) const
{
switch(c){
case ' ':
@@ -118,8 +118,8 @@ bool addon_filename_legal(const std::string& name)
return false;
}
- const ucs4::string name_ucs4 = unicode_cast<ucs4::string>(name);
- const std::string name_utf8 = unicode_cast<utf8::string>(name_ucs4);
+ const std::u32string name_ucs4 = unicode_cast<std::u32string>(name);
+ const std::string name_utf8 = unicode_cast<std::string>(name_ucs4);
if(name != name_utf8){ // name is invalid UTF-8
return false;
}
diff --git a/src/ai/actions.cpp b/src/ai/actions.cpp
index 0d697375db5..3be7c7a6c2b 100644
--- a/src/ai/actions.cpp
+++ b/src/ai/actions.cpp
@@ -986,16 +986,25 @@ void synced_command_result::do_init_for_execution()
// STATELESS INTERFACE TO AI ACTIONS
// =======================================================================
-attack_result_ptr actions::execute_attack_action( side_number side,
- bool execute,
- const map_location& attacker_loc,
- const map_location& defender_loc,
- int attacker_weapon,
- double aggression,
- const unit_advancements_aspect& advancements)
-{
- attack_result_ptr action(new attack_result(side,attacker_loc,defender_loc,attacker_weapon,aggression,advancements));
- execute ? action->execute() : action->check_before();
+static void execute_or_check(action_result& action, bool execute)
+{
+ if(execute) {
+ action.execute();
+ } else {
+ action.check_before();
+ }
+}
+
+attack_result_ptr actions::execute_attack_action(side_number side,
+ bool execute,
+ const map_location& attacker_loc,
+ const map_location& defender_loc,
+ int attacker_weapon,
+ double aggression,
+ const unit_advancements_aspect& advancements)
+{
+ attack_result_ptr action(new attack_result(side, attacker_loc, defender_loc, attacker_weapon, aggression, advancements));
+ execute_or_check(*action, execute);
return action;
}
@@ -1006,8 +1015,8 @@ move_result_ptr actions::execute_move_action( side_number side,
bool remove_movement,
bool unreach_is_ok)
{
- move_result_ptr action(new move_result(side,from,to,remove_movement,unreach_is_ok));
- execute ? action->execute() : action->check_before();
+ move_result_ptr action(new move_result(side, from, to, remove_movement, unreach_is_ok));
+ execute_or_check(*action, execute);
return action;
}
@@ -1017,8 +1026,8 @@ recall_result_ptr actions::execute_recall_action( side_number side,
const map_location& where,
const map_location& from)
{
- recall_result_ptr action(new recall_result(side,unit_id,where,from));
- execute ? action->execute() : action->check_before();
+ recall_result_ptr action(new recall_result(side, unit_id, where, from));
+ execute_or_check(*action, execute);
return action;
}
@@ -1028,8 +1037,8 @@ recruit_result_ptr actions::execute_recruit_action( side_number side,
const map_location& where,
const map_location& from)
{
- recruit_result_ptr action(new recruit_result(side,unit_name,where,from));
- execute ? action->execute() : action->check_before();
+ recruit_result_ptr action(new recruit_result(side, unit_name, where, from));
+ execute_or_check(*action, execute);
return action;
}
@@ -1039,8 +1048,8 @@ stopunit_result_ptr actions::execute_stopunit_action( side_number side,
bool remove_movement,
bool remove_attacks)
{
- stopunit_result_ptr action(new stopunit_result(side,unit_location,remove_movement,remove_attacks));
- execute ? action->execute() : action->check_before();
+ stopunit_result_ptr action(new stopunit_result(side, unit_location, remove_movement, remove_attacks));
+ execute_or_check(*action, execute);
return action;
}
@@ -1049,8 +1058,8 @@ synced_command_result_ptr actions::execute_synced_command_action( side_number si
const std::string& lua_code,
const map_location& location)
{
- synced_command_result_ptr action(new synced_command_result(side,lua_code,location));
- execute ? action->execute() : action->check_before();
+ synced_command_result_ptr action(new synced_command_result(side, lua_code, location));
+ execute_or_check(*action, execute);
return action;
}
diff --git a/src/ai/composite/aspect.hpp b/src/ai/composite/aspect.hpp
index c35d13bc63b..b085689afcb 100644
--- a/src/ai/composite/aspect.hpp
+++ b/src/ai/composite/aspect.hpp
@@ -212,14 +212,14 @@ class composite_aspect;
template<typename T>
class typesafe_known_aspect : public known_aspect {
public:
- typesafe_known_aspect(const std::string &name, std::shared_ptr< typesafe_aspect<T>> &where, aspect_map &aspects)
+ typesafe_known_aspect(const std::string &name, typesafe_aspect_ptr<T>& where, aspect_map &aspects)
: known_aspect(name), where_(where), aspects_(aspects)
{
}
void set(aspect_ptr a)
{
- std::shared_ptr< typesafe_aspect <T>> c = std::dynamic_pointer_cast< typesafe_aspect<T>>(a);
+ typesafe_aspect_ptr<T> c = std::dynamic_pointer_cast<typesafe_aspect<T>>(a);
if (c) {
assert (c->get_id()== this->get_name());
where_ = c;
@@ -242,9 +242,8 @@ public:
}
protected:
- std::shared_ptr<typesafe_aspect <T>> &where_;
+ typesafe_aspect_ptr<T>& where_;
aspect_map &aspects_;
-
};
@@ -268,7 +267,7 @@ public:
std::vector< aspect_ptr > default_aspects;
engine::parse_aspect_from_config(*this,_default,parent_id_,std::back_inserter(default_aspects));
if (!default_aspects.empty()) {
- typename aspect_type<T>::typesafe_ptr b = std::dynamic_pointer_cast< typesafe_aspect<T>>(default_aspects.front());
+ typesafe_aspect_ptr<T> b = std::dynamic_pointer_cast< typesafe_aspect<T>>(default_aspects.front());
if (composite_aspect<T>* c = dynamic_cast<composite_aspect<T>*>(b.get())) {
c->parent_id_ = parent_id_;
}
@@ -276,7 +275,7 @@ public:
}
}
- std::function<void(typename aspect_type<T>::typesafe_ptr_vector&, const config&)> factory_facets =
+ std::function<void(typesafe_aspect_vector<T>&, const config&)> factory_facets =
std::bind(&ai::composite_aspect<T>::create_facet,*this,_1,_2);
register_facets_property(this->property_handlers(),"facet",facets_,default_, factory_facets);
@@ -284,12 +283,12 @@ public:
}
- void create_facet( typename aspect_type<T>::typesafe_ptr_vector &facets, const config &cfg)
+ void create_facet(typesafe_aspect_vector<T>& facets, const config &cfg)
{
std::vector<aspect_ptr> facets_base;
engine::parse_aspect_from_config(*this,cfg,parent_id_,std::back_inserter(facets_base));
for (aspect_ptr a : facets_base) {
- typename aspect_type<T>::typesafe_ptr b = std::dynamic_pointer_cast< typesafe_aspect<T>> (a);
+ typesafe_aspect_ptr<T> b = std::dynamic_pointer_cast< typesafe_aspect<T>> (a);
if (composite_aspect<T>* c = dynamic_cast<composite_aspect<T>*>(b.get())) {
c->parent_id_ = parent_id_;
}
@@ -318,7 +317,7 @@ public:
virtual config to_config() const
{
config cfg = aspect::to_config();
- for (const typename aspect_type<T>::typesafe_ptr f : facets_) {
+ for (const typesafe_aspect_ptr<T> f : facets_) {
cfg.add_child("facet",f->to_config());
}
if (default_) {
@@ -338,7 +337,7 @@ public:
engine::parse_aspect_from_config(*this,cfg,parent_id_,std::back_inserter(facets));
int j=0;
for (aspect_ptr a : facets) {
- typename aspect_type<T>::typesafe_ptr b = std::dynamic_pointer_cast< typesafe_aspect<T>> (a);
+ typesafe_aspect_ptr<T> b = std::dynamic_pointer_cast< typesafe_aspect<T>> (a);
if (composite_aspect<T>* c = dynamic_cast<composite_aspect<T>*>(b.get())) {
c->parent_id_ = parent_id_;
}
@@ -367,8 +366,8 @@ public:
}
protected:
- typename aspect_type<T>::typesafe_ptr_vector facets_;
- typename aspect_type<T>::typesafe_ptr default_;
+ typesafe_aspect_vector<T> facets_;
+ typesafe_aspect_ptr<T> default_;
std::string parent_id_;
};
diff --git a/src/ai/composite/goal.cpp b/src/ai/composite/goal.cpp
index c0d186c8131..c3c248983bb 100644
--- a/src/ai/composite/goal.cpp
+++ b/src/ai/composite/goal.cpp
@@ -280,11 +280,11 @@ void protect_goal::add_targets(std::back_insert_iterator< std::vector< target >>
{
int distance = distance_between(u.get_location(), loc);
if (current_team().is_enemy(u.side()) && distance < radius_ &&
- !u.invisible(u.get_location(), *resources::gameboard))
+ !u.invisible(u.get_location()))
{
DBG_AI_GOAL << "side " << get_side() << ": in " << goal_type << ": found threat target. " << u.get_location() << " is a threat to "<< loc << '\n';
*target_list = target(u.get_location(),
- value_ * double(radius_ - distance) /
+ value_ * static_cast<double>(radius_ - distance) /
radius_, target::TYPE::THREAT);
}
}
diff --git a/src/ai/contexts.cpp b/src/ai/contexts.cpp
index 53b8538bf7c..4565e75c55f 100644
--- a/src/ai/contexts.cpp
+++ b/src/ai/contexts.cpp
@@ -27,7 +27,7 @@
#include "ai/composite/engine.hpp" // for engine, engine_factory, etc
#include "ai/composite/goal.hpp" // for goal
#include "ai/composite/stage.hpp" // for ministage
-#include "ai/game_info.hpp" // for aspect_type<>::typesafe_ptr, etc
+#include "ai/game_info.hpp" // for typesafe_aspect_ptr, etc
#include "ai/lua/aspect_advancements.hpp"
#include "ai/manager.hpp" // for manager
@@ -172,12 +172,10 @@ synced_command_result_ptr readonly_context_impl::check_synced_command_action(con
return actions::execute_synced_command_action(get_side(),false,lua_code,location);
}
-
template<typename T>
-void readonly_context_impl::add_known_aspect(const std::string &name, std::shared_ptr< typesafe_aspect <T>> &where)
+void readonly_context_impl::add_known_aspect(const std::string& name, typesafe_aspect_ptr<T>& where)
{
- std::shared_ptr< typesafe_known_aspect <T>> ka_ptr(new typesafe_known_aspect<T>(name,where,aspects_));
- known_aspects_.emplace(name,ka_ptr);
+ known_aspects_.emplace(name, std::make_shared<typesafe_known_aspect<T>>(name, where, aspects_));
}
readonly_context_impl::readonly_context_impl(side_context &context, const config &cfg)
@@ -340,8 +338,8 @@ const team& readonly_context_impl::current_team() const
void readonly_context_impl::log_message(const std::string& msg)
{
if(game_config::debug) {
- game_display::get_singleton()->get_chat_manager().add_chat_message(time(nullptr), "ai", get_side(), msg,
- events::chat_handler::MESSAGE_PUBLIC, false);
+ game_display::get_singleton()->get_chat_manager().add_chat_message(
+ time(nullptr), "ai", get_side(), msg, events::chat_handler::MESSAGE_PUBLIC, false);
}
}
@@ -376,7 +374,7 @@ void readonly_context_impl::calculate_moves(const unit_map& units, std::map<map_
}
// We can't see where invisible enemy units might move.
- if (enemy && un_it->invisible(un_it->get_location(), *resources::gameboard) && !see_all) {
+ if (enemy && un_it->invisible(un_it->get_location()) && !see_all) {
continue;
}
// If it's an enemy unit, reset its moves while we do the calculations.
@@ -1119,7 +1117,7 @@ double readonly_context_impl::power_projection(const map_location& loc, const mo
}
// The 0.5 power avoids underestimating too much the damage of a wounded unit.
- int64_t hp = int(sqrt(double(un.hitpoints()) / un.max_hitpoints()) * 1000);
+ int64_t hp = static_cast<int>(std::sqrt(static_cast<double>(un.hitpoints()) / un.max_hitpoints()) * 1000);
int64_t most_damage = 0;
for(const attack_type &att : un.attacks())
{
diff --git a/src/ai/contexts.hpp b/src/ai/contexts.hpp
index 0b166932105..b67e00908dd 100644
--- a/src/ai/contexts.hpp
+++ b/src/ai/contexts.hpp
@@ -20,7 +20,7 @@
#pragma once
-#include "ai/game_info.hpp" // for move_map, aspect_type, etc
+#include "ai/game_info.hpp" // for move_map, typesafe_aspect_ptr, etc
#include "config.hpp" // for config
#include "game_errors.hpp"
@@ -1489,7 +1489,7 @@ public:
private:
template<typename T>
- void add_known_aspect(const std::string &name, std::shared_ptr< typesafe_aspect <T>>& where);
+ void add_known_aspect(const std::string &name, typesafe_aspect_ptr<T>& where);
const config cfg_;
@@ -1500,50 +1500,48 @@ private:
known_aspect_map known_aspects_;
- aspect_type< unit_advancements_aspect >::typesafe_ptr advancements_;
- aspect_type<double>::typesafe_ptr aggression_;
- aspect_type<int>::typesafe_ptr attack_depth_;
+ typesafe_aspect_ptr<unit_advancements_aspect> advancements_;
+ typesafe_aspect_ptr<double> aggression_;
+ typesafe_aspect_ptr<int> attack_depth_;
aspect_map aspects_;
- aspect_type< attacks_vector >::typesafe_ptr attacks_;
- mutable aspect_type<terrain_filter>::typesafe_ptr avoid_;
- aspect_type<double>::typesafe_ptr caution_;
+ typesafe_aspect_ptr<attacks_vector> attacks_;
+ mutable typesafe_aspect_ptr<terrain_filter> avoid_;
+ typesafe_aspect_ptr<double> caution_;
mutable std::map<map_location,defensive_position> defensive_position_cache_;
mutable move_map dstsrc_;
mutable move_map enemy_dstsrc_;
mutable moves_map enemy_possible_moves_;
mutable move_map enemy_srcdst_;
- aspect_type< std::string >::typesafe_ptr grouping_;
+ typesafe_aspect_ptr<std::string> grouping_;
std::vector< goal_ptr > goals_;
mutable keeps_cache keeps_;
- aspect_type<double>::typesafe_ptr leader_aggression_;
- aspect_type< config >::typesafe_ptr leader_goal_;
- aspect_type<bool>::typesafe_ptr leader_ignores_keep_;
- aspect_type< double >::typesafe_ptr leader_value_;
+ typesafe_aspect_ptr<double> leader_aggression_;
+ typesafe_aspect_ptr<config> leader_goal_;
+ typesafe_aspect_ptr<bool> leader_ignores_keep_;
+ typesafe_aspect_ptr<double> leader_value_;
mutable bool move_maps_enemy_valid_;
mutable bool move_maps_valid_;
mutable bool dst_src_valid_lua_;
mutable bool dst_src_enemy_valid_lua_;
mutable bool src_dst_valid_lua_;
mutable bool src_dst_enemy_valid_lua_;
- aspect_type<bool>::typesafe_ptr passive_leader_;
- aspect_type<bool>::typesafe_ptr passive_leader_shares_keep_;
+ typesafe_aspect_ptr<bool> passive_leader_;
+ typesafe_aspect_ptr<bool> passive_leader_shares_keep_;
mutable moves_map possible_moves_;
- aspect_type< double >::typesafe_ptr recruitment_diversity_;
- aspect_type< config >::typesafe_ptr recruitment_instructions_;
- aspect_type< std::vector<std::string>>::typesafe_ptr recruitment_more_;
- aspect_type< std::vector<std::string>>::typesafe_ptr recruitment_pattern_;
- aspect_type< int >::typesafe_ptr recruitment_randomness_;
- aspect_type< config >::typesafe_ptr recruitment_save_gold_;
+ typesafe_aspect_ptr<double> recruitment_diversity_;
+ typesafe_aspect_ptr<config> recruitment_instructions_;
+ typesafe_aspect_ptr<std::vector<std::string>> recruitment_more_;
+ typesafe_aspect_ptr<std::vector<std::string>> recruitment_pattern_;
+ typesafe_aspect_ptr<int> recruitment_randomness_;
+ typesafe_aspect_ptr<config> recruitment_save_gold_;
recursion_counter recursion_counter_;
- aspect_type< double >::typesafe_ptr scout_village_targeting_;
- aspect_type< bool >::typesafe_ptr simple_targeting_;
+ typesafe_aspect_ptr<double> scout_village_targeting_;
+ typesafe_aspect_ptr<bool> simple_targeting_;
mutable move_map srcdst_;
- aspect_type< bool >::typesafe_ptr support_villages_;
+ typesafe_aspect_ptr<bool> support_villages_;
mutable unit_stats_cache_t unit_stats_cache_;
- aspect_type< double >::typesafe_ptr village_value_;
- aspect_type< int >::typesafe_ptr villages_per_scout_;
-
-
+ typesafe_aspect_ptr<double> village_value_;
+ typesafe_aspect_ptr<int> villages_per_scout_;
};
class readwrite_context_impl : public virtual readonly_context_proxy, public readwrite_context {
diff --git a/src/ai/default/aspect_attacks.cpp b/src/ai/default/aspect_attacks.cpp
index f830e22757b..8f1cdc11d93 100644
--- a/src/ai/default/aspect_attacks.cpp
+++ b/src/ai/default/aspect_attacks.cpp
@@ -104,7 +104,7 @@ std::shared_ptr<attacks_vector> aspect_attacks_base::analyze_targets() const
// Attack anyone who is on the enemy side,
// and who is not invisible or petrified.
if (current_team().is_enemy(j->side()) && !j->incapacitated() &&
- !j->invisible(j->get_location(), *resources::gameboard))
+ !j->invisible(j->get_location()))
{
if (!is_allowed_enemy(*j)) {
continue;
@@ -288,7 +288,7 @@ void aspect_attacks_base::do_attack_analysis(
}
// No surround bonus if target is skirmisher
- if (!itor->get_ability_bool("skirmisher", *resources::gameboard))
+ if (!itor->get_ability_bool("skirmisher"))
surround_bonus = 1.2;
}
@@ -360,7 +360,7 @@ int aspect_attacks_base::rate_terrain(const unit& u, const map_location& loc)
const int neutral_village_value = 10;
const int enemy_village_value = 15;
- if(map_.gives_healing(terrain) && u.get_ability_bool("regenerate", loc, *resources::gameboard) == false) {
+ if(map_.gives_healing(terrain) && u.get_ability_bool("regenerate", loc) == false) {
rating += healing_value;
}
diff --git a/src/ai/default/attack.cpp b/src/ai/default/attack.cpp
index 456521200d7..1c67b6f5b15 100644
--- a/src/ai/default/attack.cpp
+++ b/src/ai/default/attack.cpp
@@ -65,8 +65,8 @@ void attack_analysis::analyze(const gamemap& map, unit_map& units,
uses_leader = false;
target_value = defend_it->cost();
- target_value += (double(defend_it->experience())/
- double(defend_it->max_experience()))*target_value;
+ target_value += (static_cast<double>(defend_it->experience())/
+ static_cast<double>(defend_it->max_experience()))*target_value;
target_starting_damage = defend_it->max_hitpoints() -
defend_it->hitpoints();
@@ -166,7 +166,7 @@ void attack_analysis::analyze(const gamemap& map, unit_map& units,
double cost = up->cost();
const bool on_village = map.is_village(m->second);
// Up to double the value of a unit based on experience
- cost += (double(up->experience()) / up->max_experience())*cost;
+ cost += (static_cast<double>(up->experience()) / up->max_experience())*cost;
resources_used += cost;
avg_losses += cost * prob_died;
@@ -182,7 +182,7 @@ void attack_analysis::analyze(const gamemap& map, unit_map& units,
avg_damage_taken -= game_config::poison_amount*2 * prob_survived;
}
- terrain_quality += (double(bc->get_defender_stats().chance_to_hit)/100.0)*cost * (on_village ? 0.5 : 1.0);
+ terrain_quality += (static_cast<double>(bc->get_defender_stats().chance_to_hit)/100.0)*cost * (on_village ? 0.5 : 1.0);
double advance_prob = 0.0;
// The reward for advancing a unit is to get a 'negative' loss of that unit
@@ -194,7 +194,7 @@ void attack_analysis::analyze(const gamemap& map, unit_map& units,
if (xp_for_advance == 0)
xp_for_advance = 1;
- int fight_xp = defend_it->level();
+ int fight_xp = game_config::combat_xp(defend_it->level());
int kill_xp = game_config::kill_xp(fight_xp);
if (fight_xp >= xp_for_advance) {
@@ -233,7 +233,7 @@ void attack_analysis::analyze(const gamemap& map, unit_map& units,
* directly. For each level of attacker def gets 1 xp or
* kill_experience.
*/
- int fight_xp = up->level();
+ int fight_xp = game_config::combat_xp(up->level());
int kill_xp = game_config::kill_xp(fight_xp);
def_avg_experience += fight_xp * (1.0 - att.hp_dist[0]) + kill_xp * att.hp_dist[0];
if (m == movements.begin()) {
diff --git a/src/ai/default/ca.cpp b/src/ai/default/ca.cpp
index 91c47335d9b..8d2db21624b 100644
--- a/src/ai/default/ca.cpp
+++ b/src/ai/default/ca.cpp
@@ -1333,7 +1333,7 @@ double get_healing_phase::evaluate()
if(u.side() == get_side() &&
(u.max_hitpoints() - u.hitpoints() >= game_config::poison_amount/2
|| u.get_state(unit::STATE_POISONED)) &&
- !u.get_ability_bool("regenerate", *resources::gameboard))
+ !u.get_ability_bool("regenerate"))
{
// Look for the village which is the least vulnerable to enemy attack.
typedef std::multimap<map_location,map_location>::const_iterator Itor;
@@ -1473,7 +1473,7 @@ double retreat_phase::evaluate()
const map_location& hex = itors.first->second;
const int defense = i->defense_modifier(resources::gameboard->map().get_terrain(hex));
const double our_power = power_projection(hex,get_dstsrc());
- const double their_power = power_projection(hex,get_enemy_dstsrc()) * double(defense)/100.0;
+ const double their_power = power_projection(hex,get_enemy_dstsrc()) * static_cast<double>(defense)/100.0;
const double rating = our_power - their_power;
if(rating > best_rating) {
best_pos = hex;
diff --git a/src/ai/default/ca_move_to_targets.cpp b/src/ai/default/ca_move_to_targets.cpp
index 38b418b230f..b58b3d3ce73 100644
--- a/src/ai/default/ca_move_to_targets.cpp
+++ b/src/ai/default/ca_move_to_targets.cpp
@@ -641,7 +641,7 @@ void move_to_targets_phase::access_points(const move_map& srcdst, const map_loca
const std::pair<move_map::const_iterator,move_map::const_iterator> locs = srcdst.equal_range(u);
for(move_map::const_iterator i = locs.first; i != locs.second; ++i) {
const map_location& loc = i->second;
- if (int(distance_between(loc,dst)) <= u_it->total_movement()) {
+ if (static_cast<int>(distance_between(loc,dst)) <= u_it->total_movement()) {
pathfind::shortest_path_calculator calc(*u_it, current_team(), resources::gameboard->teams(), map_);
const pathfind::teleport_map allowed_teleports = pathfind::get_teleport_locations(*u_it, current_team());
pathfind::plain_route rt = a_star_search(loc, dst, u_it->total_movement(), calc, map_.w(), map_.h(), &allowed_teleports);
@@ -849,7 +849,7 @@ double move_to_targets_phase::rate_group(const std::set<map_location>& group, co
}
const int rating = (defense*best_attack*un.hitpoints())/(100*un.max_hitpoints());
- strength += double(rating);
+ strength += static_cast<double>(rating);
}
return strength;
diff --git a/src/ai/default/contexts.cpp b/src/ai/default/contexts.cpp
index 4cfabbf5797..9e864412221 100644
--- a/src/ai/default/contexts.cpp
+++ b/src/ai/default/contexts.cpp
@@ -81,7 +81,7 @@ int default_ai_context_impl::count_free_hexes_in_castle(const map_location &loc,
ret += count_free_hexes_in_castle(adj[n], checked_hexes);
if (u == units_.end()
|| (current_team().is_enemy(u->side())
- && u->invisible(adj[n], *resources::gameboard))
+ && u->invisible(adj[n]))
|| ((&resources::gameboard->get_team(u->side()) == &current_team())
&& u->movement_left() > 0)) {
ret += 1;
@@ -109,7 +109,7 @@ int default_ai_context_impl::rate_terrain(const unit& u, const map_location& loc
const int neutral_village_value = 10;
const int enemy_village_value = 15;
- if(map_.gives_healing(terrain) && u.get_ability_bool("regenerate", loc, *resources::gameboard) == false) {
+ if(map_.gives_healing(terrain) && u.get_ability_bool("regenerate", loc) == false) {
rating += healing_value;
}
@@ -164,7 +164,7 @@ std::vector<target> default_ai_context_impl::find_targets(const move_map& enemy_
assert(threats.empty() == false);
- const double value = threat/double(threats.size());
+ const double value = threat/static_cast<double>(threats.size());
for(std::set<map_location>::const_iterator i = threats.begin(); i != threats.end(); ++i) {
LOG_AI << "found threat target... " << *i << " with value: " << value << "\n";
targets.emplace_back(*i,value,target::TYPE::THREAT);
@@ -228,7 +228,7 @@ std::vector<target> default_ai_context_impl::find_targets(const move_map& enemy_
for(u = units_.begin(); u != units_.end(); ++u) {
//is a visible enemy leader
if (u->can_recruit() && current_team().is_enemy(u->side())
- && !u->invisible(u->get_location(), *resources::gameboard)) {
+ && !u->invisible(u->get_location())) {
assert(map_.on_board(u->get_location()));
LOG_AI << "found enemy leader (side: " << u->side() << ") target... " << u->get_location() << " with value: " << get_leader_value() << "\n";
targets.emplace_back(u->get_location(), get_leader_value(), target::TYPE::LEADER);
diff --git a/src/ai/default/recruitment.cpp b/src/ai/default/recruitment.cpp
index f388d8c0d21..61b5a7a78ec 100644
--- a/src/ai/default/recruitment.cpp
+++ b/src/ai/default/recruitment.cpp
@@ -262,10 +262,6 @@ void recruitment::execute() {
if (!ufilt(*recall, map_location::null_location())) {
continue;
}
- const double recall_value = recruitment::recall_unit_value(recall);
- if (recall_value < 0) {
- continue; // Unit is not worth to get recalled.
- }
data.recruits.insert(recall->type_id());
data.scores[recall->type_id()] = 0.0;
global_recruits.insert(recall->type_id());
@@ -478,37 +474,6 @@ action_result_ptr recruitment::execute_recruit(const std::string& type, data& le
* If this value is less then the recall cost, we dismiss the unit.
* The unit with the highest value will be returned.
*/
-
-double recruitment::recall_unit_value(const unit_const_ptr & recall_unit) const {
- double average_cost_of_advanced_unit = 0;
- int counter = 0;
- for (const std::string& advancement : recall_unit->advances_to()) {
- const unit_type* advancement_type = unit_types.find(advancement);
- if (!advancement_type) {
- continue;
- }
- average_cost_of_advanced_unit += advancement_type->cost();
- ++counter;
- }
- if (counter > 0) {
- average_cost_of_advanced_unit /= counter;
- } else {
- // Unit don't have advancements. Use cost of unit itself.
- average_cost_of_advanced_unit = recall_unit->cost();
- }
- double xp_quantity = static_cast<double>(recall_unit->experience()) /
- recall_unit->max_experience();
- double recall_value = recall_unit->cost() + xp_quantity * average_cost_of_advanced_unit;
- int cost = current_team().recall_cost();
- if (recall_unit->recall_cost() > -1) {
- cost=recall_unit->recall_cost();
- }
- if (recall_value < cost) {
- recall_value = -1; // Unit is not worth to get recalled.
- }
- return recall_value;
-}
-
const std::string* recruitment::get_appropriate_recall(const std::string& type,
const data& leader_data) const {
const std::string* best_recall_id = nullptr;
@@ -523,7 +488,28 @@ const std::string* recruitment::get_appropriate_recall(const std::string& type,
LOG_AI_RECRUITMENT << "Refused recall because of filter: " << recall_unit->id() << "\n";
continue;
}
- const double recall_value = recruitment::recall_unit_value(recall_unit);
+ double average_cost_of_advanced_unit = 0;
+ int counter = 0;
+ for (const std::string& advancement : recall_unit->advances_to()) {
+ const unit_type* advancement_type = unit_types.find(advancement);
+ if (!advancement_type) {
+ continue;
+ }
+ average_cost_of_advanced_unit += advancement_type->cost();
+ ++counter;
+ }
+ if (counter > 0) {
+ average_cost_of_advanced_unit /= counter;
+ } else {
+ // Unit don't have advancements. Use cost of unit itself.
+ average_cost_of_advanced_unit = recall_unit->cost();
+ }
+ double xp_quantity = static_cast<double>(recall_unit->experience()) /
+ recall_unit->max_experience();
+ double recall_value = recall_unit->cost() + xp_quantity * average_cost_of_advanced_unit;
+ if (recall_value < current_team().recall_cost()) {
+ continue; // Unit is not worth to get recalled.
+ }
if (recall_value > best_recall_value) {
best_recall_id = &recall_unit->id();
best_recall_value = recall_value;
@@ -758,7 +744,7 @@ void recruitment::update_average_lawful_bonus() {
++counter;
}
if (counter > 0) {
- average_lawful_bonus_ = round_double(static_cast<double>(sum) / counter);
+ average_lawful_bonus_ = std::round(static_cast<double>(sum) / counter);
}
}
@@ -989,7 +975,7 @@ void recruitment::do_combat_analysis(std::vector<data>* leader_data) {
for (const std::string& recruit : leader.recruits) {
double score = compare_unit_types(recruit, enemy_unit);
score *= enemy_unit_hp;
- score = pow(score, COMBAT_SCORE_POWER);
+ score = std::pow(score, COMBAT_SCORE_POWER);
temp_scores[recruit] += score;
}
}
@@ -1083,9 +1069,9 @@ struct attack_simulation {
attacker_type(attacker),
defender_type(defender),
attacker_stats(attacker, att_weapon, true, defender, def_weapon,
- round_double(defender_defense), average_lawful_bonus),
+ std::round(defender_defense), average_lawful_bonus),
defender_stats(defender, def_weapon, false, attacker, att_weapon,
- round_double(attacker_defense), average_lawful_bonus),
+ std::round(attacker_defense), average_lawful_bonus),
attacker_combatant(attacker_stats),
defender_combatant(defender_stats)
{
@@ -1742,7 +1728,7 @@ void recruitment::update_scouts_wanted() {
// making us get twice as many scouts.
double villages_per_scout = (VILLAGE_PER_SCOUT_MULTIPLICATOR * get_villages_per_scout()) / 2;
- scouts_wanted_ = (villages_per_scout > 0) ? round_double(our_share / villages_per_scout) : 0;
+ scouts_wanted_ = (villages_per_scout > 0) ? std::round(our_share / villages_per_scout) : 0;
if (scouts_wanted_ == 0) {
return;
diff --git a/src/ai/default/recruitment.hpp b/src/ai/default/recruitment.hpp
index 2a7d097c692..a2cf71a9d06 100644
--- a/src/ai/default/recruitment.hpp
+++ b/src/ai/default/recruitment.hpp
@@ -174,7 +174,6 @@ private:
// Helper functions for execute()
action_result_ptr execute_recall(const std::string& id, data& leader_data);
action_result_ptr execute_recruit(const std::string& type, data& leader_data);
- double recall_unit_value(const unit_const_ptr & recall_unit) const;
const std::string* get_appropriate_recall(const std::string& type,
const data& leader_data) const;
data* get_best_leader_from_ratio_scores(std::vector<data>& leader_data,
diff --git a/src/ai/formula/ai.cpp b/src/ai/formula/ai.cpp
index f0b7cd27ae3..74589658715 100644
--- a/src/ai/formula/ai.cpp
+++ b/src/ai/formula/ai.cpp
@@ -234,7 +234,7 @@ pathfind::plain_route formula_ai::shortest_path_calculator(const map_location &s
}
static const size_t NDIRECTIONS = map_location::NDIRECTIONS;
- unsigned int difference = std::abs(int(preferred - n));
+ unsigned int difference = std::abs(static_cast<int>(preferred - n));
if(difference > NDIRECTIONS/2) {
difference = NDIRECTIONS - difference;
}
diff --git a/src/ai/formula/callable_objects.cpp b/src/ai/formula/callable_objects.cpp
index b31132fd50a..c33d1237909 100644
--- a/src/ai/formula/callable_objects.cpp
+++ b/src/ai/formula/callable_objects.cpp
@@ -285,7 +285,7 @@ void attack_map_callable::collect_possible_attacks(std::vector<variant>& vars, m
/* if tile is occupied by friendly or petrified/invisible unit */
if (!ai_.current_team().is_enemy(unit->side()) ||
unit->incapacitated() ||
- unit->invisible(unit->get_location(), *resources::gameboard))
+ unit->invisible(unit->get_location()))
continue;
/* add attacks with default weapon */
auto item = std::make_shared<attack_callable>(attacker_location, attack_position, adj[n], -1);
diff --git a/src/ai/formula/candidates.cpp b/src/ai/formula/candidates.cpp
index d5e55d4b281..9212e874e2a 100644
--- a/src/ai/formula/candidates.cpp
+++ b/src/ai/formula/candidates.cpp
@@ -21,7 +21,6 @@
#include "ai/formula/candidates.hpp"
#include "game_board.hpp"
#include "log.hpp"
-#include "resources.hpp"
#include "units/unit.hpp"
static lg::log_domain log_formula_ai("ai/engine/fai");
@@ -166,7 +165,7 @@ void attack_candidate_action::evaluate(ai::formula_ai* ai, unit_map& units)
}
} else
{
- if (ai->current_team().is_enemy(i->side()) && !i->incapacitated() && !i->invisible(i->get_location(), *resources::gameboard)) {
+ if (ai->current_team().is_enemy(i->side()) && !i->incapacitated() && !i->invisible(i->get_location())) {
enemy_res.emplace_back(std::make_shared<unit_callable>(*i));
}
}
diff --git a/src/ai/formula/function_table.cpp b/src/ai/formula/function_table.cpp
index 74cd90daf8e..64767a6ddf8 100644
--- a/src/ai/formula/function_table.cpp
+++ b/src/ai/formula/function_table.cpp
@@ -625,7 +625,7 @@ DEFINE_WFL_FUNCTION(calculate_outcome, 3, 4)
while (it != hp_dist.end()) {
if (*it != 0) {
hitLeft.emplace_back(i);
- prob.emplace_back(int(*it*10000));
+ prob.emplace_back(static_cast<int>(*it*10000));
}
++it;
++i;
@@ -649,7 +649,7 @@ DEFINE_WFL_FUNCTION(calculate_outcome, 3, 4)
while (it != hp_dist.end()) {
if (*it != 0) {
hitLeft.emplace_back(i);
- prob.emplace_back(int(*it*10000));
+ prob.emplace_back(static_cast<int>(*it*10000));
}
++it;
++i;
diff --git a/src/ai/game_info.hpp b/src/ai/game_info.hpp
index fa4f5672285..6dbde6a824f 100644
--- a/src/ai/game_info.hpp
+++ b/src/ai/game_info.hpp
@@ -20,63 +20,53 @@
#pragma once
#include "map/location.hpp"
-namespace pathfind {
- struct paths;
-}
+
#include <map>
#include <memory>
+namespace pathfind
+{
+struct paths;
+}
+
/**
* info is structure which holds references to all the important objects
* that an AI might need access to, in order to make and implement its
* decisions.
*/
-namespace ai {
-
+namespace ai
+{
typedef int side_number;
/** The standard way in which a map of possible moves is recorded. */
-typedef std::multimap<map_location,map_location> move_map;
+typedef std::multimap<map_location, map_location> move_map;
/** The standard way in which a map of possible movement routes to location is recorded*/
-typedef std::map<map_location,pathfind::paths> moves_map;
+typedef std::map<map_location, pathfind::paths> moves_map;
class ai_composite;
-
-typedef std::shared_ptr<ai_composite> ai_ptr;
+typedef std::unique_ptr<ai_composite> composite_ai_ptr;
class attack_analysis;
typedef std::vector<attack_analysis> attacks_vector;
-class readonly_context;
-class readwrite_context;
-class default_ai_context;
-class ai_context;
-
-class aspect;
-class candidate_action;
-class engine;
-class goal;
-class known_aspect;
-class stage;
-
template<typename T>
class typesafe_aspect;
template<typename T>
-struct aspect_type {
- typedef std::shared_ptr< typesafe_aspect<T>> typesafe_ptr;
- typedef std::vector< std::shared_ptr< typesafe_aspect<T>> > typesafe_ptr_vector;
-};
+using typesafe_aspect_ptr = std::shared_ptr<typesafe_aspect<T>>;
+
+template<typename T>
+using typesafe_aspect_vector = std::vector<typesafe_aspect_ptr<T>>;
template<typename T>
class typesafe_known_aspect;
template<typename T>
-struct known_aspect_type {
- typedef std::shared_ptr< typesafe_known_aspect<T>> typesafe_ptr;
- typedef std::vector< std::shared_ptr< typesafe_known_aspect<T>> > typesafe_ptr_vector;
-};
+using typesafe_known_aspect_ptr = std::shared_ptr<typesafe_known_aspect<T>>;
+
+template<typename T>
+using typesafe_known_aspect_vector = std::vector<typesafe_known_aspect_ptr<T>>;
class action_result;
class attack_result;
@@ -96,25 +86,33 @@ typedef std::shared_ptr<move_and_attack_result> move_and_attack_result_ptr;
typedef std::shared_ptr<stopunit_result> stopunit_result_ptr;
typedef std::shared_ptr<synced_command_result> synced_command_result_ptr;
-typedef std::shared_ptr< aspect > aspect_ptr;
-typedef std::shared_ptr< candidate_action > candidate_action_ptr;
-typedef std::shared_ptr< engine > engine_ptr;
-typedef std::shared_ptr< goal > goal_ptr;
-typedef std::shared_ptr< known_aspect > known_aspect_ptr;
-typedef std::shared_ptr< stage > stage_ptr;
+class aspect;
+class candidate_action;
+class engine;
+class goal;
+class known_aspect;
+class stage;
+
+typedef std::shared_ptr<aspect> aspect_ptr;
+typedef std::shared_ptr<candidate_action> candidate_action_ptr;
+typedef std::shared_ptr<engine> engine_ptr;
+typedef std::shared_ptr<goal> goal_ptr;
+typedef std::shared_ptr<known_aspect> known_aspect_ptr;
+typedef std::shared_ptr<stage> stage_ptr;
-typedef std::map<std::string, aspect_ptr > aspect_map;
-typedef std::map<std::string, known_aspect_ptr > known_aspect_map;
+typedef std::map<std::string, aspect_ptr> aspect_map;
+typedef std::map<std::string, known_aspect_ptr> known_aspect_map;
-class game_info {
+class game_info
+{
public:
+ game_info()
+ : recent_attacks()
+ {
+ }
- game_info()
- : recent_attacks()
- {}
-
- /** hack. @todo 1.9 rework that via extended event system, or at least ensure it hurts no one */
- std::set<map_location> recent_attacks;
+ /** hack. @todo 1.9 rework that via extended event system, or at least ensure it hurts no one */
+ std::set<map_location> recent_attacks;
};
-} //of namespace ai
+} // of namespace ai
diff --git a/src/ai/lua/core.cpp b/src/ai/lua/core.cpp
index efa03fd8ec5..6f84c823148 100644
--- a/src/ai/lua/core.cpp
+++ b/src/ai/lua/core.cpp
@@ -271,25 +271,6 @@ static int cfun_ai_check_stopunit(lua_State *L)
return ai_stopunit_select(L, false, true, true);
}
-static int cfun_ai_execute_synced_command(lua_State *L)
-{
- luaW_getglobal(L, "wesnoth", "deprecated_message");
- lua_pushstring(L, "ai.synced_command");
- lua_pushinteger(L, 4);
- lua_pushstring(L, "1.14");
- lua_pushstring(L, "Instead, you must register a custom synced command in wesnoth.custom_synced_commands, and invoke it with wesnoth.invoke_synced_command.");
- luaW_pcall(L, 4, 0);
- return 0; // Unreachable, as luaW_pcall throws an exception
-}
-
-static int cfun_ai_check_synced_command(lua_State *L)
-{
- // This is basically the same as above but returns false instead of raising an error.
- deprecated_message("ai.check_synced_command", DEP_LEVEL::REMOVED, "1.14", "Instead, you must register a custom synced command in wesnoth.custom_synced_commands, and invoke it with wesnoth.invoke_synced_command.");
- lua_pushboolean(L, false);
- return 1;
-}
-
static int ai_recruit(lua_State *L, bool exec)
{
const char *unit_name = luaL_checkstring(L, 1);
@@ -943,7 +924,6 @@ static int impl_ai_get(lua_State* L)
{ "check_recall", &cfun_ai_check_recall },
{ "check_move", &cfun_ai_check_move },
{ "check_stopunit", &cfun_ai_check_stopunit },
- { "check_synced_command", &cfun_ai_check_synced_command },
{ "check_attack", &cfun_ai_check_attack },
{ "check_recruit", &cfun_ai_check_recruit },
//{ "",},
@@ -976,7 +956,6 @@ static int impl_ai_get(lua_State* L)
{ "stopunit_all", &cfun_ai_execute_stopunit_all },
{ "stopunit_attacks", &cfun_ai_execute_stopunit_attacks },
{ "stopunit_moves", &cfun_ai_execute_stopunit_moves },
- { "synced_command", &cfun_ai_execute_synced_command },
{ "fallback_human", &cfun_ai_fallback_human},
{ nullptr, nullptr } };
for (const luaL_Reg* p = mutating_callbacks; p->name; ++p) {
diff --git a/src/ai/manager.hpp b/src/ai/manager.hpp
index ba9275f5ab8..753216a819d 100644
--- a/src/ai/manager.hpp
+++ b/src/ai/manager.hpp
@@ -42,9 +42,8 @@ namespace events { class generic_event; }
namespace events { class observer; }
-namespace ai {
-
-typedef std::shared_ptr<ai_composite> composite_ai_ptr;
+namespace ai
+{
/**
* Base class that holds the AI and current AI parameters.
diff --git a/src/ai/simulated_actions.cpp b/src/ai/simulated_actions.cpp
index 18fe64708e5..defcb118971 100644
--- a/src/ai/simulated_actions.cpp
+++ b/src/ai/simulated_actions.cpp
@@ -61,8 +61,8 @@ bool simulated_attack(const map_location& attacker_loc, const map_location& defe
LOG_AI_SIM_ACTIONS << "attacker's hp after attack: " << attack_unit->hitpoints() << std::endl;
LOG_AI_SIM_ACTIONS << "defender's hp after attack: " << defend_unit->hitpoints() << std::endl;
- int attacker_xp = defend_unit->level();
- int defender_xp = attack_unit->level();
+ int attacker_xp = game_config::combat_xp(defend_unit->level());
+ int defender_xp = game_config::combat_xp(attack_unit->level());
bool attacker_died = false;
bool defender_died = false;
if(attack_unit->hitpoints() <= 0){
diff --git a/src/ai/testing.cpp b/src/ai/testing.cpp
index 3729487eeaa..365fc2d0ba8 100644
--- a/src/ai/testing.cpp
+++ b/src/ai/testing.cpp
@@ -25,6 +25,7 @@
#include "team.hpp"
#include "units/unit.hpp"
#include "tod_manager.hpp"
+#include "game_version.hpp"
static lg::log_domain log_ai_testing("ai/testing");
#define DBG_AI_TESTING LOG_STREAM(debug, log_ai_testing)
@@ -61,7 +62,7 @@ void ai_testing::log_turn(const char* msg, unsigned int side)
DBG_AI_TESTING << msg << "_INCOME " << side << ": " << _income << std::endl;
config c;
- c["side"] = int(side);
+ c["side"] = static_cast<int>(side);
c["turn"] = _turn_number;
c["event"] = msg;
c["units"] = _units;
diff --git a/src/animated.tpp b/src/animated.tpp
index af14958d4f7..a93fb6ec22f 100644
--- a/src/animated.tpp
+++ b/src/animated.tpp
@@ -310,7 +310,7 @@ inline const T& animated<T, T_void_value>::get_first_frame() const
}
template<typename T, typename T_void_value>
-inline const T& animated<T, T_void_value>::get_frame(size_t n) const
+inline const T& animated<T, T_void_value>::get_frame(std::size_t n) const
{
if(n >= frames_.size()) {
return void_value_;
@@ -330,7 +330,7 @@ inline const T& animated<T, T_void_value>::get_last_frame() const
}
template<typename T, typename T_void_value>
-inline size_t animated<T, T_void_value>::get_frames_count() const
+inline std::size_t animated<T, T_void_value>::get_frames_count() const
{
return frames_.size();
}
diff --git a/src/attack_prediction.cpp b/src/attack_prediction.cpp
index 62dc9828ae9..cb3d33f4a0c 100644
--- a/src/attack_prediction.cpp
+++ b/src/attack_prediction.cpp
@@ -2035,13 +2035,13 @@ void one_strike_fight(const battle_context_unit_stats& stats,
return;
}
- if(stats.experience + opp_stats.level >= stats.max_experience) {
+ if(stats.experience + game_config::combat_xp(opp_stats.level) >= stats.max_experience) {
forced_levelup(hp_dist);
} else if(stats.experience + game_config::kill_xp(opp_stats.level) >= stats.max_experience) {
conditional_levelup(hp_dist, opp_hp_dist[0]);
}
- if(opp_stats.experience + stats.level >= opp_stats.max_experience) {
+ if(opp_stats.experience + game_config::combat_xp(stats.level) >= opp_stats.max_experience) {
forced_levelup(opp_hp_dist);
} else if(opp_stats.experience + game_config::kill_xp(stats.level) >= opp_stats.max_experience) {
conditional_levelup(opp_hp_dist, hp_dist[0]);
@@ -2180,13 +2180,13 @@ void complex_fight(attack_prediction_mode mode,
}
if(levelup_considered) {
- if(stats.experience + opp_stats.level >= stats.max_experience) {
+ if(stats.experience + game_config::combat_xp(opp_stats.level) >= stats.max_experience) {
m->forced_levelup_a();
} else if(stats.experience + game_config::kill_xp(opp_stats.level) >= stats.max_experience) {
m->conditional_levelup_a();
}
- if(opp_stats.experience + stats.level >= opp_stats.max_experience) {
+ if(opp_stats.experience + game_config::combat_xp(stats.level) >= opp_stats.max_experience) {
m->forced_levelup_b();
} else if(opp_stats.experience + game_config::kill_xp(stats.level) >= opp_stats.max_experience) {
m->conditional_levelup_b();
@@ -2447,12 +2447,12 @@ void combatant::fight(combatant& opponent, bool levelup_considered)
opponent.slowed = std::min(std::accumulate(opponent.summary[1].begin(), opponent.summary[1].end(), 0.0), 1.0);
}
- if(u_.experience + opponent.u_.level >= u_.max_experience) {
+ if(u_.experience + game_config::combat_xp(opponent.u_.level) >= u_.max_experience) {
// We'll level up after the battle -> slow/poison will go away
poisoned = 0.0;
slowed = 0.0;
}
- if(opponent.u_.experience + u_.level >= opponent.u_.max_experience) {
+ if(opponent.u_.experience + game_config::combat_xp(u_.level) >= opponent.u_.max_experience) {
opponent.poisoned = 0.0;
opponent.slowed = 0.0;
}
@@ -2526,7 +2526,7 @@ void combatant::print(const char label[], unsigned int battle, unsigned int figh
// TODO: add this to the stream... no idea how to convert it properly...
printf("#%06u: (%02u) %s%*c %u-%d; %uhp; %02u%% to hit; %.2f%% unscathed; ", battle, fighter, label,
- int(strlen(label)) - 12, ':', u_.swarm_max, u_.damage, u_.hp, u_.chance_to_hit, untouched * 100.0);
+ static_cast<int>(strlen(label)) - 12, ':', u_.swarm_max, u_.damage, u_.hp, u_.chance_to_hit, untouched * 100.0);
if(u_.drains) {
ss << "drains, ";
diff --git a/src/build_info.cpp b/src/build_info.cpp
index f6a043ff8a3..e14e4927226 100644
--- a/src/build_info.cpp
+++ b/src/build_info.cpp
@@ -22,6 +22,7 @@
#include "formatter.hpp"
#include "gettext.hpp"
#include "serialization/unicode.hpp"
+#include "game_version.hpp"
#include <algorithm>
@@ -75,7 +76,7 @@ std::string format_version(const SDL_version& v)
std::string format_openssl_patch_level(uint8_t p)
{
return p <= 26
- ? std::string(1, 'a' + char(p) - 1)
+ ? std::string(1, 'a' + static_cast<char>(p) - 1)
: "patch" + std::to_string(p);
}
@@ -257,11 +258,6 @@ version_table_manager::version_table_manager()
// Features table.
//
- features.emplace_back(N_("feature^Experimental OpenMP support"));
-#ifdef _OPENMP
- features.back().enabled = true;
-#endif
-
features.emplace_back(N_("feature^JPG screenshots"));
#ifdef SDL_IMAGE_VERSION_ATLEAST
#if SDL_IMAGE_VERSION_ATLEAST(2, 0, 2)
diff --git a/src/campaign_server/campaign_server.cpp b/src/campaign_server/campaign_server.cpp
index 034fa3e0ef4..2723e7f9d42 100644
--- a/src/campaign_server/campaign_server.cpp
+++ b/src/campaign_server/campaign_server.cpp
@@ -587,14 +587,14 @@ void server::handle_request_campaign_list(const server::request& req)
bool before_flag = false;
time_t before = epoch;
try {
- before = before + lexical_cast<time_t>(req.cfg["before"]);
+ before += req.cfg["before"].to_time_t();
before_flag = true;
} catch(const bad_lexical_cast&) {}
bool after_flag = false;
time_t after = epoch;
try {
- after = after + lexical_cast<time_t>(req.cfg["after"]);
+ after += req.cfg["after"].to_time_t();
after_flag = true;
} catch(const bad_lexical_cast&) {}
@@ -611,12 +611,12 @@ void server::handle_request_campaign_list(const server::request& req)
continue;
}
- const std::string& tm = i["timestamp"];
+ const auto& tm = i["timestamp"];
- if(before_flag && (tm.empty() || lexical_cast_default<time_t>(tm, 0) >= before)) {
+ if(before_flag && (tm.empty() || tm.to_time_t(0) >= before)) {
continue;
}
- if(after_flag && (tm.empty() || lexical_cast_default<time_t>(tm, 0) <= after)) {
+ if(after_flag && (tm.empty() || tm.to_time_t(0) <= after)) {
continue;
}
diff --git a/src/campaign_server/control.hpp b/src/campaign_server/control.hpp
index f0e4ef8b57b..67abc96e5ef 100644
--- a/src/campaign_server/control.hpp
+++ b/src/campaign_server/control.hpp
@@ -54,8 +54,6 @@ public:
/**
* Returns the control command.
- *
- * Equivalent to calling arg(0).
*/
operator const std::string&() const
{
@@ -64,8 +62,6 @@ public:
/**
* Returns the control command.
- *
- * Equivalent to calling arg(0).
*/
const std::string& cmd() const
{
@@ -87,21 +83,7 @@ public:
*/
const std::string& operator[](size_t n) const
{
- return arg(n);
- }
-
- /**
- * Returns the nth argument.
- *
- * @throws std::out_of_range @a n exceeds args_count().
- */
- const std::string& arg(size_t n) const
- {
- if(n > args_count()) {
- throw std::out_of_range("control line argument range exceeded");
- }
-
- return args_[n];
+ return args_.at(n);
}
/**
diff --git a/src/color.hpp b/src/color.hpp
index 0877f7d1c15..8ce49ce8980 100644
--- a/src/color.hpp
+++ b/src/color.hpp
@@ -13,8 +13,6 @@
#pragma once
-#include "global.hpp"
-
#include <algorithm> // for max
#include <cstdint>
#include <ostream>
@@ -24,7 +22,7 @@
struct SDL_Color;
//
-// TODO: constexpr
+// TODO: CONSTEXPR
//
const uint32_t SDL_ALPHA_MASK = 0xFF000000;
@@ -243,7 +241,11 @@ struct color_t
inline std::ostream& operator<<(std::ostream& s, const color_t& c)
{
- s << int(c.r) << " " << int(c.g) << " " << int(c.b) << " " << int(c.a) << std::endl;
+ s << static_cast<int>(c.r) << " "
+ << static_cast<int>(c.g) << " "
+ << static_cast<int>(c.b) << " "
+ << static_cast<int>(c.a) << std::endl;
+
return s;
}
diff --git a/src/color_range.cpp b/src/color_range.cpp
index 4210b835b99..e4c336e9eef 100644
--- a/src/color_range.cpp
+++ b/src/color_range.cpp
@@ -20,7 +20,6 @@
#include "color_range.hpp"
-#include "game_config.hpp"
#include "map/map.hpp"
#include <iomanip>
diff --git a/src/config.cpp b/src/config.cpp
index 16776c48877..ef08152dc26 100644
--- a/src/config.cpp
+++ b/src/config.cpp
@@ -27,6 +27,7 @@
#include "utils/functional.hpp"
#include "deprecation.hpp"
#include "game_version.hpp"
+#include "serialization/string_utils.hpp"
#include <algorithm>
#include <cstdlib>
@@ -541,6 +542,42 @@ config& config::add_child_at(config_key_type key, const config& val, unsigned in
return *v[index];
}
+config& config::add_child_at(config_key_type key, const config &val, const const_all_children_iterator& pos)
+{
+ if(pos == ordered_end()) {
+ //optimisation
+ config::add_child(key, val);
+ }
+
+ auto end = ordered_children.end();
+ assert(pos.i_ <= end);
+
+ auto pos_it = ordered_children.begin() + (pos.i_ - ordered_children.begin()); //'const cast'.
+ auto next = std::find_if(pos_it, end,[&](const child_pos& p){ return p.pos->first == key; });
+
+ if(next == end) {
+ config& res = config::add_child(key, val);
+ std::rotate( pos_it, ordered_children.end(), ordered_children.end());
+ return res;
+ }
+
+ auto pl = next->pos;
+ child_list& l = pl->second;
+ unsigned int index = next->index;
+ config& res = **(l.emplace(l.begin() + index, new config(val)));
+
+ for(auto ord = next; ord != end; ++ord) {
+ //this changes next->index and all later refernces to that tag.
+ if(ord->pos == pl) {
+ ++ord->index;
+ }
+ }
+
+ //finally insert our new child in ordered_children.
+ ordered_children.insert(pos.i_, { pl, index });
+ return res;
+}
+
namespace
{
struct remove_ordered
@@ -1182,19 +1219,33 @@ bool config::matches(const config& filter) const
{
check_valid(filter);
+ bool result = true;
+
for(const attribute& i : filter.attribute_range()) {
- const attribute_value* v = get(i.first);
- if(!v || *v != i.second) {
- return false;
+ if(i.first.compare(0, 8, "glob_on_") == 0) {
+ const attribute_value* v = get(i.first.substr(8));
+ if(!v || !utils::wildcard_string_match(v->str(), i.second.str())) {
+ result = false;
+ break;
+ }
+ } else {
+ const attribute_value* v = get(i.first);
+ if(!v || *v != i.second) {
+ result = false;
+ break;
+ }
}
}
for(const any_child& i : filter.all_children_range()) {
if(i.key == "not") {
- if(matches(i.cfg)) {
- return false;
- }
-
+ result = result && !matches(i.cfg);
+ continue;
+ } else if(i.key == "and") {
+ result = result && matches(i.cfg);
+ continue;
+ } else if(i.key == "or") {
+ result = result || matches(i.cfg);
continue;
}
@@ -1206,12 +1257,10 @@ bool config::matches(const config& filter) const
}
}
- if(!found) {
- return false;
- }
+ result = result && found;
}
- return true;
+ return result;
}
std::string config::debug() const
@@ -1234,7 +1283,7 @@ std::ostream& operator<<(std::ostream& outstream, const config& cfg)
}
for(int j = 0; j < i - 1; j++) {
- outstream << char(9);
+ outstream << '\t';
}
outstream << val.first << " = " << val.second << '\n';
@@ -1242,14 +1291,14 @@ std::ostream& operator<<(std::ostream& outstream, const config& cfg)
for(const config::any_child& child : cfg.all_children_range()) {
for(int j = 0; j < i - 1; ++j) {
- outstream << char(9);
+ outstream << '\t';
}
outstream << "[" << child.key << "]\n";
outstream << child.cfg;
for(int j = 0; j < i - 1; ++j) {
- outstream << char(9);
+ outstream << '\t';
}
outstream << "[/" << child.key << "]\n";
diff --git a/src/config.hpp b/src/config.hpp
index dcdf420eed6..8f7be941e14 100644
--- a/src/config.hpp
+++ b/src/config.hpp
@@ -624,7 +624,7 @@ public:
typedef std::vector<child_pos>::const_iterator Itor;
typedef const_all_children_iterator this_type;
explicit const_all_children_iterator(const Itor &i): i_(i) {}
- const_all_children_iterator(all_children_iterator& i): i_(i.i_) {}
+ const_all_children_iterator(const all_children_iterator& i): i_(i.i_) {}
const_all_children_iterator &operator++() { ++i_; return *this; }
const_all_children_iterator operator++(int) { return const_all_children_iterator(i_++); }
@@ -659,6 +659,8 @@ public:
friend class config;
};
+ config& add_child_at(config_key_type key, const config &val, const const_all_children_iterator& pos);
+
typedef boost::iterator_range<all_children_iterator> all_children_itors;
typedef boost::iterator_range<const_all_children_iterator> const_all_children_itors;
diff --git a/src/config_attribute_value.hpp b/src/config_attribute_value.hpp
index 0cb705fbb2f..546199f5809 100644
--- a/src/config_attribute_value.hpp
+++ b/src/config_attribute_value.hpp
@@ -28,7 +28,6 @@
#pragma once
#include "global.hpp"
-#include "utils/type_trait_aliases.hpp"
#include <climits>
#include <ctime>
@@ -68,18 +67,6 @@
# define USE_HETEROGENOUS_LOOKUPS
#endif
-#ifdef USE_HETEROGENOUS_LOOKUPS
-#if BOOST_VERSION > 106100
-#include <boost/utility/string_view.hpp>
-using config_key_type = boost::string_view;
-#else
-#include <boost/utility/string_ref.hpp>
-using config_key_type = boost::string_ref;
-#endif
-#else
-using config_key_type = const std::string &;
-#endif
-
class enum_tag;
/**
@@ -172,7 +159,7 @@ public:
config_attribute_value& operator=(const std::string &v);
config_attribute_value& operator=(const t_string &v);
template<typename T>
- utils::enable_if_t<std::is_base_of<enum_tag, T>::value, config_attribute_value&> operator=(const T &v)
+ std::enable_if_t<std::is_base_of<enum_tag, T>::value, config_attribute_value&> operator=(const T &v)
{
return operator=(T::enum_to_string(v));
}
@@ -193,10 +180,10 @@ public:
/**
@tparam T a type created with MAKE_ENUM macro
NOTE: since T::VALUE constants is not of type T but of the underlying enum type you must specify the template parameter explicitly
- TODO: Fix this in c++11 using constexpr types.
+ TODO: Fix this in c++11 using CONSTEXPR types.
*/
template<typename T>
- utils::enable_if_t<std::is_base_of<enum_tag, T>::value, T> to_enum(const T &v) const
+ std::enable_if_t<std::is_base_of<enum_tag, T>::value, T> to_enum(const T &v) const
{
return T::string_to_enum(this->str(), v);
}
@@ -223,14 +210,14 @@ public:
// These function prevent t_string creation in case of c["a"] == "b" comparisons.
// The templates are needed to prevent using these function in case of c["a"] == 0 comparisons.
template<typename T>
- utils::enable_if_t<std::is_same<const std::string, utils::add_const_t<T>>::value, bool>
+ std::enable_if_t<std::is_same<const std::string, std::add_const_t<T>>::value, bool>
friend operator==(const config_attribute_value &val, const T &str)
{
return val.equals(str);
}
template<typename T>
- utils::enable_if_t<std::is_same<const char*, T>::value, bool>
+ std::enable_if_t<std::is_same<const char*, T>::value, bool>
friend operator==(const config_attribute_value& val, T str)
{
return val.equals(std::string(str));
diff --git a/src/config_cache.cpp b/src/config_cache.cpp
index a61a8a97b48..63c4106e323 100644
--- a/src/config_cache.cpp
+++ b/src/config_cache.cpp
@@ -27,7 +27,6 @@
#include <boost/algorithm/string/replace.hpp>
#include <boost/iostreams/filter/gzip.hpp>
-#include <SDL_platform.h>
static lg::log_domain log_cache("cache");
#define ERR_CACHE LOG_STREAM(err, log_cache)
@@ -46,10 +45,6 @@ void add_builtin_defines(preproc_map& target)
target["APPLE"] = preproc_define();
#endif
-#if defined(MOUSE_TOUCH_EMULATION) || defined(__IPHONEOS__)
- target["IPHONEOS"] = preproc_define();
-#endif
-
target["WESNOTH_VERSION"] = preproc_define(game_config::wesnoth_version.str());
}
diff --git a/src/controller_base.cpp b/src/controller_base.cpp
index 191a5348dac..b0606efba27 100644
--- a/src/controller_base.cpp
+++ b/src/controller_base.cpp
@@ -17,24 +17,22 @@
#include "display.hpp"
#include "events.hpp"
-#include "preferences/game.hpp"
+#include "game_config_manager.hpp"
#include "hotkey/command_executor.hpp"
+#include "hotkey/hotkey_command.hpp"
#include "log.hpp"
#include "map/map.hpp"
#include "mouse_handler_base.hpp"
#include "preferences/game.hpp"
#include "scripting/plugins/context.hpp"
#include "show_dialog.hpp" //gui::in_dialog
+#include "gui/core/event/handler.hpp" // gui2::is_in_dialog
#include "soundsource.hpp"
-#include "gui/core/timer.hpp"
-
static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)
-static const int long_touch_duration_ms = 800;
-
-controller_base::controller_base(const config& game_config)
- : game_config_(game_config)
+controller_base::controller_base()
+ : game_config_(game_config_manager::get()->game_config())
, key_()
, scrolling_(false)
, scroll_up_(false)
@@ -43,51 +41,11 @@ controller_base::controller_base(const config& game_config)
, scroll_right_(false)
, joystick_manager_()
, key_release_listener_(*this)
- , last_mouse_is_touch_(false)
- , long_touch_timer_(0)
{
}
controller_base::~controller_base()
{
- if(long_touch_timer_ != 0) {
- gui2::remove_timer(long_touch_timer_);
- long_touch_timer_ = 0;
- }
-}
-
-void controller_base::long_touch_callback(int x, int y)
-{
- if(long_touch_timer_ != 0 && !get_mouse_handler_base().dragging_started()) {
- int x_now;
- int y_now;
- uint32_t mouse_state = SDL_GetMouseState(&x_now, &y_now);
-
-#ifdef MOUSE_TOUCH_EMULATION
- if(mouse_state & SDL_BUTTON(SDL_BUTTON_RIGHT)) {
- // Monkey-patch touch controls again to make them look like left button.
- mouse_state = SDL_BUTTON(SDL_BUTTON_LEFT);
- }
-#endif
-
- // Workaround for double-menu b/c of slow events processing, or I don't know.
- int dx = x - x_now;
- int dy = y - y_now;
- int threshold = get_mouse_handler_base().drag_threshold();
- bool yes_actually_dragging = dx * dx + dy * dy >= threshold * threshold;
-
- if(!yes_actually_dragging
- && (mouse_state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0
- && sdl::point_in_rect(x_now, y_now, get_display().map_area()))
- {
- const theme::menu* const m = get_mouse_handler_base().gui().get_theme().context_menu();
- if(m != nullptr) {
- show_menu(get_display().get_theme().context_menu()->items(), x_now, y_now, true, get_display());
- }
- }
- }
-
- long_touch_timer_ = 0;
}
void controller_base::handle_event(const SDL_Event& event)
@@ -98,8 +56,6 @@ void controller_base::handle_event(const SDL_Event& event)
events::mouse_handler_base& mh_base = get_mouse_handler_base();
- SDL_Event new_event = {};
-
switch(event.type) {
case SDL_TEXTINPUT:
if(have_keyboard_focus()) {
@@ -140,90 +96,40 @@ void controller_base::handle_event(const SDL_Event& event)
break;
case SDL_JOYBUTTONDOWN:
+ process_keydown_event(event);
hotkey::jbutton_event(event, get_hotkey_command_executor());
break;
case SDL_JOYHATMOTION:
+ process_keydown_event(event);
hotkey::jhat_event(event, get_hotkey_command_executor());
break;
case SDL_MOUSEMOTION:
// Ignore old mouse motion events in the event queue
+ SDL_Event new_event;
if(SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION) > 0) {
while(SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION) > 0) {
};
- if(new_event.motion.which != SDL_TOUCH_MOUSEID) {
- mh_base.mouse_motion_event(new_event.motion, is_browsing());
- }
- } else {
- if(new_event.motion.which != SDL_TOUCH_MOUSEID) {
- mh_base.mouse_motion_event(event.motion, is_browsing());
- }
- }
- break;
-
- case SDL_FINGERMOTION:
- if(SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_FINGERMOTION, SDL_FINGERMOTION) > 0) {
- while(SDL_PeepEvents(&new_event, 1, SDL_GETEVENT, SDL_FINGERMOTION, SDL_FINGERMOTION) > 0) {
- };
- mh_base.touch_motion_event(new_event.tfinger, is_browsing());
+ mh_base.mouse_motion_event(new_event.motion, is_browsing());
} else {
- mh_base.touch_motion_event(event.tfinger, is_browsing());
+ mh_base.mouse_motion_event(event.motion, is_browsing());
}
break;
case SDL_MOUSEBUTTONDOWN:
- last_mouse_is_touch_ = event.button.which == SDL_TOUCH_MOUSEID;
-
- if(last_mouse_is_touch_ && long_touch_timer_ == 0) {
- long_touch_timer_ = gui2::add_timer(
- long_touch_duration_ms,
- std::bind(&controller_base::long_touch_callback, this, event.button.x, event.button.y));
- }
-
+ process_keydown_event(event);
mh_base.mouse_press(event.button, is_browsing());
hotkey::mbutton_event(event, get_hotkey_command_executor());
break;
- case SDL_FINGERDOWN:
- // handled by mouse case
- break;
-
case SDL_MOUSEBUTTONUP:
- if(long_touch_timer_ != 0) {
- gui2::remove_timer(long_touch_timer_);
- long_touch_timer_ = 0;
- }
-
- last_mouse_is_touch_ = event.button.which == SDL_TOUCH_MOUSEID;
-
mh_base.mouse_press(event.button, is_browsing());
if(mh_base.get_show_menu()) {
show_menu(get_display().get_theme().context_menu()->items(), event.button.x, event.button.y, true,
get_display());
}
break;
- case DOUBLE_CLICK_EVENT:
- {
- int x = static_cast<int>(reinterpret_cast<std::intptr_t>(event.user.data1));
- int y = static_cast<int>(reinterpret_cast<std::intptr_t>(event.user.data2));
- if(event.user.code == static_cast<int>(SDL_TOUCH_MOUSEID)
- // TODO: Move to right_click_show_menu?
- && sdl::point_in_rect(x, y, get_display().map_area())
- // TODO: This chain repeats in several places, move to a method.
- && get_display().get_theme().context_menu() != nullptr) {
- show_menu(get_display().get_theme().context_menu()->items(),
- x,
- y,
- true,
- get_display());
- }
- }
- break;
-
- case SDL_FINGERUP:
- // handled by mouse case
- break;
case SDL_MOUSEWHEEL:
#if defined(_WIN32) || defined(__APPLE__)
@@ -233,12 +139,6 @@ void controller_base::handle_event(const SDL_Event& event)
#endif
break;
- case TIMER_EVENT:
- gui2::execute_timer(reinterpret_cast<size_t>(event.user.data1));
- break;
-
- // TODO: Support finger specifically, like pan the map. For now, SDL's "shadow mouse" events will do.
- case SDL_MULTIGESTURE:
default:
break;
}
@@ -246,7 +146,7 @@ void controller_base::handle_event(const SDL_Event& event)
void controller_base::process(events::pump_info&)
{
- if(gui::in_dialog()) {
+ if(gui2::is_in_dialog()) {
return;
}
@@ -340,8 +240,8 @@ bool controller_base::handle_scroll(int mousex, int mousey, int mouse_flags, dou
}
// scroll with joystick
- dx += round_double(x_axis * scroll_speed);
- dy += round_double(y_axis * scroll_speed);
+ dx += std::round(x_axis * scroll_speed);
+ dy += std::round(y_axis * scroll_speed);
return get_display().scroll(dx, dy);
}
diff --git a/src/controller_base.hpp b/src/controller_base.hpp
index c9c340ee96f..d6224391391 100644
--- a/src/controller_base.hpp
+++ b/src/controller_base.hpp
@@ -63,7 +63,7 @@ class manager;
class controller_base : public video2::draw_layering, public events::pump_monitor
{
public:
- controller_base(const config& game_config);
+ controller_base();
virtual ~controller_base();
virtual void play_slice(bool is_delay_enabled = true);
@@ -154,14 +154,14 @@ protected:
// No action by default
}
- virtual void process(events::pump_info&) override;
-
/** Process keydown (only when the general map display does not have focus). */
virtual void process_focus_keydown_event(const SDL_Event& /*event*/)
{
// No action by default
}
+ virtual void process(events::pump_info&) override;
+
/** Process keydown (always). Overridden in derived classes */
virtual void process_keydown_event(const SDL_Event& /*event*/)
{
@@ -178,8 +178,6 @@ protected:
virtual void execute_action(const std::vector<std::string>& items_arg, int xloc, int yloc, bool context_menu);
virtual bool in_context_menu(hotkey::HOTKEY_COMMAND command) const;
-
- void long_touch_callback(int x, int y);
const config& game_config_;
@@ -215,8 +213,4 @@ private:
};
keyup_listener key_release_listener_;
-
- bool last_mouse_is_touch_;
- /** Context menu timer */
- size_t long_touch_timer_;
};
diff --git a/src/deprecation.cpp b/src/deprecation.cpp
index 9d5b43b55c7..de688408e28 100644
--- a/src/deprecation.cpp
+++ b/src/deprecation.cpp
@@ -14,7 +14,6 @@
#include "deprecation.hpp"
#include "formula/string_utils.hpp"
-#include "game_config.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "preferences/general.hpp"
@@ -62,7 +61,7 @@ std::string deprecated_message(
break;
default: // Not impossible, in case level was given an invalid value from a cast.
- utils::string_map err_params {{"level", std::to_string(int(level))}};
+ utils::string_map err_params {{"level", std::to_string(static_cast<int>(level))}};
// Note: This message is duplicated in data/lua/core.lua
// Any changes should be mirrorred there.
diff --git a/src/desktop/apple_battery_info.hpp b/src/desktop/apple_battery_info.hpp
deleted file mode 100644
index 45dcd19dab5..00000000000
--- a/src/desktop/apple_battery_info.hpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- Copyright (C) 2018 by Martin HrubÛ <hrubymar10@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#pragma once
-
-#include "battery_info.hpp"
-
-namespace desktop {
-namespace battery_info {
-namespace apple {
-
-bool does_device_have_battery();
-double get_battery_percentage();
-
-} // end namespace apple
-} // end namespace battery_info
-} // end namespace desktop
diff --git a/src/desktop/apple_battery_info.mm b/src/desktop/apple_battery_info.mm
deleted file mode 100644
index c45f8128783..00000000000
--- a/src/desktop/apple_battery_info.mm
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- Copyright (C) 2018 by Martin HrubÛ <hrubymar10@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#ifdef __APPLE__
-
-#include "apple_battery_info.hpp"
-
-#if defined(__APPLE__) && defined(__MACH__) && defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
-#define __IPHONEOS__ (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__*1000)
-#endif
-
-#if defined(__IPHONEOS__)
-
-#import <UIKit/UIDevice.h>
-
-#else
-
-#import <Foundation/Foundation.h>
-#import <IOKit/ps/IOPowerSources.h>
-#import <IOKit/ps/IOPSKeys.h>
-#import <IOKit/pwr_mgt/IOPM.h>
-
-#endif
-
-namespace desktop {
-namespace battery_info {
-namespace apple {
-
-bool does_device_have_battery() {
-#if defined(__IPHONEOS__)
- UIDevice.currentDevice.batteryMonitoringEnabled = YES;
- if (UIDevice.currentDevice.batteryState == UIDeviceBatteryStateUnknown) {
- return false;
- } else {
- return true;
- }
-#else
- if (get_battery_percentage() == -1) {
- return false;
- } else {
- return true;
- }
-#endif
-}
-
-#if !defined(__IPHONEOS__)
-inline NSDictionary* get_iops_battery_info() {
- //Code taken from https://github.com/Hammerspoon/hammerspoon/blob/master/extensions/battery/internal.m
- CFTypeRef info = IOPSCopyPowerSourcesInfo();
-
- if (info == NULL)
- return NULL;
-
-
- CFArrayRef list = IOPSCopyPowerSourcesList(info);
-
- if (list == NULL || !CFArrayGetCount(list)) {
- if (list)
- CFRelease(list);
-
- CFRelease(info);
- return NULL;
- }
-
- CFDictionaryRef battery = CFDictionaryCreateCopy(NULL, IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(list, 0)));
-
- CFRelease(list);
- CFRelease(info);
-
- return static_cast<NSDictionary*>(battery);
-}
-#endif
-
-double get_battery_percentage() {
-#if defined(__IPHONEOS__)
- return UIDevice.currentDevice.batteryLevel * 100;
-#else
- //Code taken from https://github.com/Hammerspoon/hammerspoon/blob/master/extensions/battery/internal.m
- NSDictionary* battery = get_iops_battery_info();
-
- NSNumber *maxCapacity = [battery objectForKey:@kIOPSMaxCapacityKey];
- NSNumber *currentCapacity = [battery objectForKey:@kIOPSCurrentCapacityKey];
-
- if (maxCapacity && currentCapacity) {
- return ([currentCapacity doubleValue] / [maxCapacity doubleValue]) * 100;
- } else {
- return -1;
- }
-#endif
-}
-
-} // end namespace apple
-} // end namespace battery_info
-} // end namespace desktop
-
-#endif //end __APPLE__
diff --git a/src/desktop/apple_version.hpp b/src/desktop/apple_version.hpp
index 8924cf38431..2c96f5c8593 100644
--- a/src/desktop/apple_version.hpp
+++ b/src/desktop/apple_version.hpp
@@ -14,7 +14,7 @@
#pragma once
-#include "version.hpp"
+#include "game_version.hpp"
#include <string>
diff --git a/src/desktop/apple_version.mm b/src/desktop/apple_version.mm
index 051840aaeb2..49e70e68e6c 100644
--- a/src/desktop/apple_version.mm
+++ b/src/desktop/apple_version.mm
@@ -22,44 +22,38 @@
#define __IPHONEOS__ (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__*1000)
#endif
-#import <Foundation/Foundation.h>
-
#if defined(__IPHONEOS__)
-#import <UIKit/UIKit.h>
+//TODO: Implement iOS version detection
+#else
+#import <Foundation/Foundation.h>
#endif
namespace desktop {
-namespace apple {
- std::string os_version() {
-
- //
- // Standard Apple version
- //
-
- std::string version_string = "";
-
- NSArray *version_array = [[[NSProcessInfo processInfo] operatingSystemVersionString] componentsSeparatedByString:@" "];
-
+ namespace apple {
+ std::string os_version() {
#if defined(__IPHONEOS__)
- std::string version_string = "iOS ";
+ //TODO: Implement iOS version detection
#else
- const version_info version_info([[version_array objectAtIndex:1] UTF8String]);
-
- if (version_info.major_version() == 10 && version_info.minor_version() < 12) {
- version_string = "Apple OS X ";
- } else {
- version_string = "Apple macOS ";
- }
+ std::string version_string = "Apple";
+ NSArray *version_array = [[[NSProcessInfo processInfo] operatingSystemVersionString] componentsSeparatedByString:@" "];
+
+ const version_info version_info([[version_array objectAtIndex:1] UTF8String]);
+
+ if (version_info.major_version() == 10 && version_info.minor_version() < 12) {
+ version_string += " OS X ";
+ } else {
+ version_string += " macOS ";
+ }
+
+ version_string += [[version_array objectAtIndex:1] UTF8String];
+ version_string += " (";
+ version_string += [[version_array objectAtIndex:3] UTF8String];
+
+ return version_string;
#endif
-
- version_string += [[version_array objectAtIndex:1] UTF8String];
- version_string += " (";
- version_string += [[version_array objectAtIndex:3] UTF8String];
-
- return version_string;
- }
-
-} // end namespace apple
+ }
+
+ } // end namespace apple
} // end namespace desktop
#endif //end __APPLE__
diff --git a/src/desktop/battery_info.cpp b/src/desktop/battery_info.cpp
deleted file mode 100644
index f77fbf261ab..00000000000
--- a/src/desktop/battery_info.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- Copyright (C) 2018 by Martin HrubÛ <hrubymar10@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#include "battery_info.hpp"
-
-#ifdef _WIN32
-#include "desktop/windows_battery_info.hpp"
-#endif
-
-#ifdef __APPLE__
-#include "apple_battery_info.hpp"
-#endif
-
-#ifdef HAVE_LIBDBUS
-#include "desktop/dbus_features.hpp"
-#endif
-
-namespace desktop {
-namespace battery_info {
-
-bool does_device_have_battery()
-{
-#if defined(_WIN32)
- return windows_battery_info::does_device_have_battery();
-#elif defined(__APPLE__)
- return desktop::battery_info::apple::does_device_have_battery();
-#elif defined(HAVE_LIBDBUS)
- return dbus::does_device_have_battery();
-#else
- return false;
-#endif
-}
-
-double get_battery_percentage()
-{
-#if defined(_WIN32)
- return windows_battery_info::get_battery_percentage();
-#elif defined(__APPLE__)
- return desktop::battery_info::apple::get_battery_percentage();
-#elif defined(HAVE_LIBDBUS)
- return dbus::get_battery_percentage();
-#else
- return -1;
-#endif
-}
-
-} // end namespace battery_info
-} // end namespace desktop
diff --git a/src/desktop/battery_info.hpp b/src/desktop/battery_info.hpp
deleted file mode 100644
index e31507303b7..00000000000
--- a/src/desktop/battery_info.hpp
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- Copyright (C) 2018 by Martin HrubÛ <hrubymar10@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#pragma once
-
-namespace desktop {
-namespace battery_info {
-
-/// @return true if the device has a battery, false otherwise.
-bool does_device_have_battery();
-/// @return battery charge as a number between 0 and 100.
-double get_battery_percentage();
-
-} // end namespace battery_info
-} // end namespace desktop
diff --git a/src/desktop/dbus_features.cpp b/src/desktop/dbus_notification.cpp
similarity index 77%
rename from src/desktop/dbus_features.cpp
rename to src/desktop/dbus_notification.cpp
index 8dfd6485744..a40dd8b513f 100644
--- a/src/desktop/dbus_features.cpp
+++ b/src/desktop/dbus_notification.cpp
@@ -12,14 +12,14 @@
See the COPYING file for more details.
*/
-#include "desktop/dbus_features.hpp"
+#include "desktop/dbus_notification.hpp"
#include "filesystem.hpp"
#include "game_config.hpp"
#include "log.hpp"
#ifndef HAVE_LIBDBUS
-#error "The HAVE_LIBDBUS symbol is not defined, you do not have lib dbus available, you should not be trying to compile dbus_features.cpp"
+#error "The HAVE_LIBDBUS symbol is not defined, you do not have lib dbus available, you should not be trying to compile dbus_notification.cpp"
#endif
#include <dbus/dbus.h>
@@ -28,8 +28,6 @@
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <cstdlib>
-#include <functional>
-#include <memory>
#include <string>
#pragma GCC diagnostic ignored "-Wold-style-cast"
@@ -98,7 +96,7 @@ DBusHandlerResult filter_dbus_signal(DBusConnection *, DBusMessage *buf, void *)
return DBUS_HANDLER_RESULT_HANDLED;
}
-DBusConnection *get_dbus_session_bus()
+DBusConnection *get_dbus_connection()
{
static bool initted = false;
static DBusConnection *connection = nullptr;
@@ -127,21 +125,6 @@ DBusConnection *get_dbus_session_bus()
return connection;
}
-DBusConnection *get_dbus_system_bus()
-{
- static DBusConnection *connection = nullptr;
-
- if (connection == nullptr)
- {
- DBusError err;
- dbus_error_init(&err);
- connection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
- dbus_error_free(&err);
- }
-
- return connection;
-}
-
uint32_t send_dbus_notification(DBusConnection *connection, uint32_t replaces_id,
const std::string &owner, const std::string &message)
{
@@ -213,48 +196,6 @@ uint32_t send_dbus_notification(DBusConnection *connection, uint32_t replaces_id
return id;
}
-template<typename T>
-T get_power_source_property(const std::string &name, T fallback)
-{
- DBusConnection *connection = get_dbus_system_bus();
- if (!connection) return fallback;
-
- std::unique_ptr<DBusMessage, std::function<void(DBusMessage*)>> msg(dbus_message_new_method_call(
- "org.freedesktop.UPower",
- "/org/freedesktop/UPower/devices/DisplayDevice",
- "org.freedesktop.DBus.Properties",
- "Get"),
- dbus_message_unref);
-
- const char *interface_name = "org.freedesktop.UPower.Device";
- const char *property_name = name.data();
- dbus_message_append_args(msg.get(),
- DBUS_TYPE_STRING, &interface_name,
- DBUS_TYPE_STRING, &property_name,
- DBUS_TYPE_INVALID);
-
- DBusError err;
- dbus_error_init(&err);
-
- std::unique_ptr<DBusMessage, std::function<void(DBusMessage*)>> ret(dbus_connection_send_with_reply_and_block(
- connection, msg.get(), 1000, &err), dbus_message_unref);
- if (ret == nullptr) {
- DBG_DU << "Failed to query power source properties: " << err.message << '\n';
- dbus_error_free(&err);
- return fallback;
- }
-
- // The value is returned as a variant. We need to recurse into it to read the underlying value.
- DBusMessageIter iter;
- dbus_message_iter_init(ret.get(), &iter);
- DBusMessageIter sub_iter;
- dbus_message_iter_recurse(&iter, &sub_iter);
- T value;
- dbus_message_iter_get_basic(&sub_iter, &value);
-
- return value;
-}
-
} // end anonymous namespace
namespace dbus {
@@ -263,7 +204,7 @@ const size_t MAX_MSG_LINES = 5;
void send_notification(const std::string & owner, const std::string & message, bool with_history)
{
- DBusConnection *connection = get_dbus_session_bus();
+ DBusConnection *connection = get_dbus_connection();
if (!connection) return;
wnotify_by_owner & noticias = notifications.get<by_owner>();
@@ -302,14 +243,4 @@ void send_notification(const std::string & owner, const std::string & message, b
}
}
-bool does_device_have_battery()
-{
- return get_power_source_property<uint32_t>("Type", 0) == 2;
-}
-
-double get_battery_percentage()
-{
- return get_power_source_property<double>("Percentage", 0.0);
-}
-
} // end namespace dbus
diff --git a/src/desktop/dbus_features.hpp b/src/desktop/dbus_notification.hpp
similarity index 90%
rename from src/desktop/dbus_features.hpp
rename to src/desktop/dbus_notification.hpp
index 609977d6795..ba9e817a4ea 100644
--- a/src/desktop/dbus_features.hpp
+++ b/src/desktop/dbus_notification.hpp
@@ -18,6 +18,4 @@
namespace dbus {
void send_notification(const std::string& owner, const std::string& message, bool with_history);
- bool does_device_have_battery();
- double get_battery_percentage();
}
diff --git a/src/desktop/notifications.cpp b/src/desktop/notifications.cpp
index dde2ee3739e..1f233433745 100644
--- a/src/desktop/notifications.cpp
+++ b/src/desktop/notifications.cpp
@@ -20,7 +20,7 @@
#include "video.hpp" //CVideo::get_singleton().window_state()
#ifdef HAVE_LIBDBUS
-#include "desktop/dbus_features.hpp"
+#include "desktop/dbus_notification.hpp"
#endif
#ifdef __APPLE__
diff --git a/src/desktop/windows_battery_info.cpp b/src/desktop/windows_battery_info.cpp
deleted file mode 100644
index 027f99a9c8f..00000000000
--- a/src/desktop/windows_battery_info.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- Copyright (C) 2018 by Jyrki Vesterinen <sandgtx@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#include "desktop/windows_battery_info.hpp"
-
-#include <windows.h>
-
-bool windows_battery_info::does_device_have_battery()
-{
- SYSTEM_POWER_STATUS power_status;
- BOOL success = GetSystemPowerStatus(&power_status);
- if(success) {
- return !(power_status.BatteryFlag & 128);
- } else {
- return false;
- }
-}
-
-double windows_battery_info::get_battery_percentage()
-{
- SYSTEM_POWER_STATUS power_status;
- BOOL success = GetSystemPowerStatus(&power_status);
- if(success) {
- return power_status.BatteryLifePercent;
- } else {
- return 0.0;
- }
-}
diff --git a/src/desktop/windows_battery_info.hpp b/src/desktop/windows_battery_info.hpp
deleted file mode 100644
index 49fcbdbfa92..00000000000
--- a/src/desktop/windows_battery_info.hpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- Copyright (C) 2018 by Jyrki Vesterinen <sandgtx@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
- */
-
-#pragma once
-
-class windows_battery_info
-{
-public:
- static bool does_device_have_battery();
- static double get_battery_percentage();
-};
diff --git a/src/desktop/windows_tray_notification.cpp b/src/desktop/windows_tray_notification.cpp
index 947fb49388f..9740e695870 100644
--- a/src/desktop/windows_tray_notification.cpp
+++ b/src/desktop/windows_tray_notification.cpp
@@ -135,9 +135,7 @@ bool windows_tray_notification::create_tray_icon()
nid->uCallbackMessage = WM_TRAYNOTIFY;
nid->uID = ICON_ID;
nid->hIcon = icon;
-#if _WIN32_WINNT >= 0x600
nid->hBalloonIcon = icon;
-#endif
lstrcpyW(nid->szTip, wtip.c_str());
// creating icon notification
@@ -198,7 +196,7 @@ void windows_tray_notification::switch_to_wesnoth_window()
std::wstring windows_tray_notification::string_to_wstring(const std::string& string, size_t maxlength)
{
- utf16::string u16_string = unicode_cast<utf16::string>(string);
+ std::u16string u16_string = unicode_cast<std::u16string>(string);
if(u16_string.size() > maxlength) {
if((u16_string[maxlength-1] & 0xDC00) == 0xD800)
u16_string.resize(maxlength - 1);
diff --git a/src/desktop/windows_tray_notification.hpp b/src/desktop/windows_tray_notification.hpp
index d91175d8f3b..33be56688d6 100644
--- a/src/desktop/windows_tray_notification.hpp
+++ b/src/desktop/windows_tray_notification.hpp
@@ -22,7 +22,7 @@
#endif
//defines that mingw misses
#ifndef _WIN32_IE
- #define _WIN32_IE 0x0600 //specifying target platform to be Windows XP and higher
+ #define _WIN32_IE _WIN32_WINNT_WIN7 //specifying target platform to be Windows 7 and higher
#endif
#ifndef NIIF_USER
#define NIIF_USER 0x00000004
diff --git a/src/display.cpp b/src/display.cpp
index 460be50608c..50af8e297ce 100644
--- a/src/display.cpp
+++ b/src/display.cpp
@@ -94,7 +94,7 @@ void display::parse_team_overlays()
const team& prev_team = playing_team() == 0
? dc_->teams().back()
: dc_->get_team(playing_team());
- for (const game_display::overlay_map::value_type i : *overlays_) {
+ for (const game_display::overlay_map::value_type i : get_overlays()) {
const overlay& ov = i.second;
if (!ov.team_name.empty() &&
((ov.team_name.find(curr_team.team_name()) + 1) != 0) !=
@@ -115,7 +115,7 @@ void display::add_overlay(const map_location& loc, const std::string& img, const
get_location_y(loc) + hex_size() / 2, halo, loc);
}
- overlays_->emplace(loc, overlay(img, halo, halo_handle, team_name, item_id, visible_under_fog));
+ get_overlays().emplace(loc, overlay(img, halo, halo_handle, team_name, item_id, visible_under_fog));
}
}
@@ -124,7 +124,7 @@ void display::remove_overlay(const map_location& loc)
/* This code no longer needed because of RAII in halo::handles
if (halo_man_) {
typedef overlay_map::const_iterator Itor;
- std::pair<Itor,Itor> itors = overlays_->equal_range(loc);
+ std::pair<Itor,Itor> itors = get_overlays().equal_range(loc);
while(itors.first != itors.second) {
halo_man_->remove(itors.first->second.halo_handle);
++itors.first;
@@ -132,7 +132,7 @@ void display::remove_overlay(const map_location& loc)
}
*/
- overlays_->erase(loc);
+ get_overlays().erase(loc);
}
void display::remove_single_overlay(const map_location& loc, const std::string& toDelete)
@@ -140,14 +140,14 @@ void display::remove_single_overlay(const map_location& loc, const std::string&
//Iterate through the values with key of loc
typedef overlay_map::iterator Itor;
overlay_map::iterator iteratorCopy;
- std::pair<Itor,Itor> itors = overlays_->equal_range(loc);
+ std::pair<Itor,Itor> itors = get_overlays().equal_range(loc);
while(itors.first != itors.second) {
//If image or halo of overlay struct matches toDelete, remove the overlay
if(itors.first->second.image == toDelete || itors.first->second.halo == toDelete || itors.first->second.id == toDelete) {
iteratorCopy = itors.first;
++itors.first;
//Not needed because of RAII --> halo_man_->remove(iteratorCopy->second.halo_handle);
- overlays_->erase(iteratorCopy);
+ get_overlays().erase(iteratorCopy);
}
else {
++itors.first;
@@ -182,7 +182,7 @@ display::display(const display_context * dc, std::weak_ptr<wb::manager> wb, repo
turbo_speed_(2),
turbo_(false),
invalidateGameStatus_(true),
- map_labels_(new map_labels(0)),
+ map_labels_(new map_labels(nullptr)),
reports_object_(&reports_object),
scroll_event_("scrolled"),
complete_redraw_event_("completely_redrawn"),
@@ -213,7 +213,6 @@ display::display(const display_context * dc, std::weak_ptr<wb::manager> wb, repo
reach_map_(),
reach_map_old_(),
reach_map_changed_(true),
- overlays_(nullptr),
fps_handle_(0),
invalidated_hexes_(0),
drawn_hexes_(0),
@@ -282,8 +281,6 @@ void display::set_theme(config theme_cfg) {
action_buttons_.clear();
create_buttons();
invalidate_theme();
- rebuild_all();
- redraw_everything();
}
void display::init_flags() {
@@ -1506,8 +1503,12 @@ static void draw_background(surface screen, const SDL_Rect& area, const std::str
}
void display::draw_text_in_hex(const map_location& loc,
- const drawing_layer layer, const std::string& text,
- size_t font_size, color_t color, double x_in_hex, double y_in_hex)
+ const drawing_layer layer,
+ const std::string& text,
+ size_t font_size,
+ color_t color,
+ double x_in_hex,
+ double y_in_hex)
{
if (text.empty()) return;
@@ -1674,7 +1675,7 @@ void display::draw_init()
void display::draw_wrap(bool update, bool force)
{
static int time_between_draws = preferences::draw_delay();
- if(time_between_draws < 0) {
+ if(time_between_draws == 0) {
time_between_draws = 1000 / screen_.current_refresh_rate();
}
@@ -1844,7 +1845,7 @@ void display::draw_minimap_units()
for(const auto& u : dc_->units()) {
if (fogged(u.get_location()) ||
(dc_->teams()[currentTeam_].is_enemy(u.side()) &&
- u.invisible(u.get_location(), *dc_)) ||
+ u.invisible(u.get_location())) ||
u.get_hidden()) {
continue;
}
@@ -1879,10 +1880,10 @@ void display::draw_minimap_units()
double u_h = yscaling;
SDL_Rect r {
- minimap_location_.x + round_double(u_x)
- , minimap_location_.y + round_double(u_y)
- , round_double(u_w)
- , round_double(u_h)
+ minimap_location_.x + int(std::round(u_x))
+ , minimap_location_.y + int(std::round(u_y))
+ , int(std::round(u_w))
+ , int(std::round(u_h))
};
sdl::fill_rectangle(r, col);
@@ -2036,11 +2037,11 @@ bool display::set_zoom(unsigned int amount, const bool validate_value_and_set_in
const SDL_Rect& area = map_area();
- //Turn the zoom factor to a double in order to avoid rounding errors.
- double zoom_factor = double(new_zoom) / double(zoom_);
+ // Turn the zoom factor to a double in order to avoid rounding errors.
+ double zoom_factor = static_cast<double>(new_zoom) / static_cast<double>(zoom_);
- xpos_ = round_double(((xpos_ + area.w / 2) * zoom_factor) - (area.w / 2));
- ypos_ = round_double(((ypos_ + area.h / 2) * zoom_factor) - (area.h / 2));
+ xpos_ = std::round(((xpos_ + area.w / 2) * zoom_factor) - (area.w / 2));
+ ypos_ = std::round(((ypos_ + area.h / 2) * zoom_factor) - (area.h / 2));
zoom_ = new_zoom;
bounds_check_position(xpos_, ypos_);
@@ -2117,7 +2118,7 @@ void display::scroll_to_xy(int screenxpos, int screenypos, SCROLL_TYPE scroll_ty
int x_old = 0;
int y_old = 0;
- const double dist_total = hypot(xmove, ymove);
+ const double dist_total = std::hypot(xmove, ymove);
double dist_moved = 0.0;
int t_prev = SDL_GetTicks();
@@ -2156,8 +2157,8 @@ void display::scroll_to_xy(int screenxpos, int screenypos, SCROLL_TYPE scroll_ty
dist_moved += velocity * dt;
if (dist_moved > dist_total) dist_moved = dist_total;
- int x_new = round_double(xmove * dist_moved / dist_total);
- int y_new = round_double(ymove * dist_moved / dist_total);
+ int x_new = std::round(xmove * dist_moved / dist_total);
+ int y_new = std::round(ymove * dist_moved / dist_total);
int dx = x_new - x_old;
int dy = y_new - y_old;
@@ -2240,7 +2241,7 @@ void display::scroll_to_tiles(const std::vector<map_location>::const_iterator &
if (scroll_type == ONSCREEN || scroll_type == ONSCREEN_WARP) {
SDL_Rect r = map_area();
- int spacing = round_double(add_spacing*hex_size());
+ int spacing = std::round(add_spacing * hex_size());
r.x += spacing;
r.y += spacing;
r.w -= 2*spacing;
@@ -2589,7 +2590,7 @@ void display::draw_hex(const map_location& loc) {
if(!shrouded(loc)) {
typedef overlay_map::const_iterator Itor;
- std::pair<Itor,Itor> overlays = overlays_->equal_range(loc);
+ std::pair<Itor,Itor> overlays = get_overlays().equal_range(loc);
const bool have_overlays = overlays.first != overlays.second;
if(have_overlays) {
@@ -2597,8 +2598,12 @@ void display::draw_hex(const map_location& loc) {
image::light_string lt = image::get_light_string(-1, tod_col.r, tod_col.g, tod_col.b);
for( ; overlays.first != overlays.second; ++overlays.first) {
+ const std::string& current_team_name = get_teams()[viewing_team()].team_name();
+ const std::vector<std::string>& current_team_names = utils::split(current_team_name);
+ const std::vector<std::string>& team_names = utils::split(overlays.first->second.team_name);
if ((overlays.first->second.team_name.empty() ||
- overlays.first->second.team_name.find(dc_->teams()[viewing_team()].team_name()) != std::string::npos)
+ std::find_first_of(team_names.begin(), team_names.end(),
+ current_team_names.begin(), current_team_names.end()) != team_names.end())
&& !(fogged(loc) && !overlays.first->second.visible_in_fog))
{
@@ -3086,56 +3091,23 @@ void display::invalidate_animations()
}
}
-#ifndef _OPENMP
- for (const unit & u : dc_->units()) {
+ for(const unit& u : dc_->units()) {
u.anim_comp().refresh();
}
for (const unit* u : *fake_unit_man_) {
u->anim_comp().refresh();
}
-#else
- std::vector<const unit *> open_mp_list;
- for (const unit & u : dc_->units()) {
- open_mp_list.push_back(&u);
- }
- // Note that it is an important assumption of the
- // system that the fake units are added to the list
- // after the real units, so that e.g. whiteboard
- // planned moves are drawn over the real units.
- for (const unit* u : *fake_unit_man_) {
- open_mp_list.push_back(u);
- }
-
- // openMP can't iterate over size_t
- const int omp_iterations = open_mp_list.size();
- //#pragma omp parallel for shared(open_mp_list)
- //this loop must not be parallelized. refresh is not thread-safe,
- //for one, unit filters are not thread safe. this is because,
- //adding new "scoped" wml variables is not thread safe. lua itself
- //is not thread safe. when this loop was parallelized, assertion
- //failures were reported in windows openmp builds.
- for (int i = 0; i < omp_iterations; i++) {
- open_mp_list[i]->anim_comp().refresh();
- }
-#endif
bool new_inval;
do {
new_inval = false;
-#ifndef _OPENMP
for (const unit & u : dc_->units()) {
new_inval |= u.anim_comp().invalidate(*this);
}
for (const unit* u : *fake_unit_man_) {
new_inval |= u->anim_comp().invalidate(*this);
}
-#else
- #pragma omp parallel for reduction(|:new_inval) shared(open_mp_list)
- for (int i = 0; i < omp_iterations; i++) {
- new_inval |= open_mp_list[i]->anim_comp().invalidate(*this);
- }
-#endif
} while (new_inval);
}
diff --git a/src/display.hpp b/src/display.hpp
index f27c230beb4..21b71b713b7 100644
--- a/src/display.hpp
+++ b/src/display.hpp
@@ -39,6 +39,7 @@ class map_labels;
class arrow;
class reports;
class team;
+struct overlay;
namespace halo {
class manager;
@@ -51,6 +52,7 @@ namespace wb {
#include "animated.hpp"
#include "display_context.hpp"
#include "font/standard_colors.hpp"
+#include "game_config.hpp"
#include "picture.hpp" //only needed for enums (!)
#include "key.hpp"
#include "time_of_day.hpp"
@@ -60,8 +62,6 @@ namespace wb {
#include "video.hpp"
#include "widgets/button.hpp"
-#include "overlay.hpp"
-
#include <boost/circular_buffer.hpp>
#include "utils/functional.hpp"
@@ -254,7 +254,10 @@ public:
static int hex_size(){ return zoom_; }
/** Returns the current zoom factor. */
- static double get_zoom_factor() { return double(zoom_)/double(game_config::tile_size); }
+ static double get_zoom_factor()
+ {
+ return static_cast<double>(zoom_) / static_cast<double>(game_config::tile_size);
+ }
/**
* given x,y co-ordinates of an onscreen pixel, will return the
@@ -1025,11 +1028,9 @@ protected:
typedef std::multimap<map_location, overlay> overlay_map;
-private:
-
-
- overlay_map* overlays_;
+ virtual overlay_map& get_overlays() = 0;
+private:
/** Handle for the label which displays frames per second. */
int fps_handle_;
/** Count work done for the debug info displayed under fps */
@@ -1059,9 +1060,6 @@ private:
bool dirty_;
-public:
- void replace_overlay_map(overlay_map* overlays) { overlays_ = overlays; }
-
protected:
static display * singleton_;
};
diff --git a/src/display_chat_manager.cpp b/src/display_chat_manager.cpp
index 1d6da0e8da0..b88c9feb125 100644
--- a/src/display_chat_manager.cpp
+++ b/src/display_chat_manager.cpp
@@ -25,6 +25,7 @@
#include "serialization/string_utils.hpp"
#include "color.hpp"
#include "preferences/credentials.hpp"
+#include "serialization/utf8_exception.hpp"
#include <SDL_timer.h>
@@ -103,7 +104,7 @@ void display_chat_manager::add_chat_message(const time_t& time, const std::strin
try {
// We've had a joker who send an invalid utf-8 message to crash clients
// so now catch the exception and ignore the message.
- msg = my_disp_.video().faked() ? "" : font::word_wrap_text(msg,font::SIZE_15,my_disp_.map_outside_area().w*3/4);
+ msg = my_disp_.video().faked() ? "" : font::word_wrap_text(msg,font::SIZE_NORMAL,my_disp_.map_outside_area().w*3/4);
} catch (utf8::invalid_utf8_exception&) {
ERR_NG << "Invalid utf-8 found, chat message is ignored." << std::endl;
return;
diff --git a/src/display_context.cpp b/src/display_context.cpp
index 91304e10c68..6b6abb3516d 100644
--- a/src/display_context.cpp
+++ b/src/display_context.cpp
@@ -47,7 +47,7 @@ bool display_context::would_be_discovered(const map_location & loc, int side_num
if(see_all) {
return true;
} else if (!get_team(side_num).fogged(u_loc)
- && !u.invisible(u_loc, *this, true)) {
+ && !u.invisible(u_loc, true)) {
return true;
}
}
@@ -59,7 +59,7 @@ const unit * display_context::get_visible_unit(const map_location & loc, const t
{
if (!map().on_board(loc)) return nullptr;
const unit_map::const_iterator u = units().find(loc);
- if (!u.valid() || !u->is_visible_to_team(current_team, *this, see_all)) {
+ if (!u.valid() || !u->is_visible_to_team(current_team, see_all)) {
return nullptr;
}
return &*u;
diff --git a/src/editor/action/action.cpp b/src/editor/action/action.cpp
index 66159078be6..d10e3f0d350 100644
--- a/src/editor/action/action.cpp
+++ b/src/editor/action/action.cpp
@@ -195,7 +195,7 @@ void editor_action_paste::extend(const editor_map& map, const std::set<map_locat
editor_action_paste* editor_action_paste::perform(map_context& mc) const
{
map_fragment mf(mc.map(), paste_.get_offset_area(offset_));
- std::unique_ptr<editor_action_paste> undo(new editor_action_paste(mf));
+ auto undo = std::make_unique<editor_action_paste>(mf);
perform_without_undo(mc);
return undo.release();
@@ -303,7 +303,7 @@ IMPLEMENT_ACTION(apply_mask)
void editor_action_apply_mask::perform_without_undo(map_context& mc) const
{
- mc.map().overlay(mask_, config(), {0, 0});
+ mc.map().overlay(mask_, {0, 0, wml_loc()});
mc.set_needs_terrain_rebuild();
}
diff --git a/src/editor/action/mouse/mouse_action_unit.cpp b/src/editor/action/mouse/mouse_action_unit.cpp
index 70ffb9f4d55..6ef9cbed591 100644
--- a/src/editor/action/mouse/mouse_action_unit.cpp
+++ b/src/editor/action/mouse/mouse_action_unit.cpp
@@ -106,7 +106,7 @@ editor_action* mouse_action_unit::up_left(editor_display& disp, int x, int y)
return nullptr;
}
- unit_type type = unit_palette_.selected_fg_item();
+ const unit_type& type = unit_palette_.selected_fg_item();
// Does this serve a purpose other than making sure the type is built?
// (Calling unit_types.build_unit_type(type) would now accomplish that
diff --git a/src/editor/controller/editor_controller.cpp b/src/editor/controller/editor_controller.cpp
index 4e25d187611..2ca33b15aba 100644
--- a/src/editor/controller/editor_controller.cpp
+++ b/src/editor/controller/editor_controller.cpp
@@ -61,13 +61,13 @@ static std::vector<std::string> saved_windows_;
namespace editor {
-editor_controller::editor_controller(const config &game_config)
- : controller_base(game_config)
+editor_controller::editor_controller()
+ : controller_base()
, mouse_handler_base()
, quit_confirmation(std::bind(&editor_controller::quit_confirm, this))
, active_menu_(editor::MAP)
, reports_(new reports())
- , gui_(new editor_display(*this, *reports_, controller_base::get_theme(game_config, "editor")))
+ , gui_(new editor_display(*this, *reports_, controller_base::get_theme(game_config_, "editor")))
, tods_()
, context_manager_(new context_manager(*gui_.get(), game_config_))
, toolkit_(nullptr)
@@ -80,11 +80,11 @@ editor_controller::editor_controller(const config &game_config)
{
init_gui();
toolkit_.reset(new editor_toolkit(*gui_.get(), key_, game_config_, *context_manager_.get()));
- help_manager_.reset(new help::help_manager(&game_config));
+ help_manager_.reset(new help::help_manager(&game_config_));
context_manager_->locs_ = toolkit_->get_palette_manager()->location_palette_.get();
context_manager_->switch_context(0, true);
- init_tods(game_config);
- init_music(game_config);
+ init_tods(game_config_);
+ init_music(game_config_);
get_current_map_context().set_starting_position_labels(gui());
cursor::set(cursor::NORMAL);
@@ -1071,7 +1071,7 @@ void editor_controller::show_menu(const std::vector<config>& items_arg, int xloc
active_menu_ = editor::UNIT_FACING;
auto pos = items.erase(items.begin());
int dir = 0;
- std::generate_n(std::inserter<std::vector<config>>(items, pos), int(map_location::NDIRECTIONS), [&dir]() -> config {
+ std::generate_n(std::inserter<std::vector<config>>(items, pos), static_cast<int>(map_location::NDIRECTIONS), [&dir]() -> config {
return config {"label", map_location::write_translated_direction(map_location::DIRECTION(dir++))};
});
}
@@ -1290,11 +1290,6 @@ void editor_controller::mouse_motion(int x, int y, const bool /*browse*/,
gui().highlight_hex(hex_clicked);
}
-void editor_controller::touch_motion(int /* x */, int /* y */, const bool /* browse */, bool /* update */, map_location /* new_loc */)
-{
- // Not implemented at all. Sorry, it's a very low priority for iOS port.
-}
-
bool editor_controller::allow_mouse_wheel_scroll(int x, int y)
{
return get_current_map_context().map().on_board_with_border(gui().hex_clicked_on(x,y));
diff --git a/src/editor/controller/editor_controller.hpp b/src/editor/controller/editor_controller.hpp
index d37b07b9a42..845b6aeb9ce 100644
--- a/src/editor/controller/editor_controller.hpp
+++ b/src/editor/controller/editor_controller.hpp
@@ -79,7 +79,7 @@ class editor_controller : public controller_base,
* to the map can be retrieved between the main loop's end and the controller's
* destruction.
*/
- explicit editor_controller(const config &game_config);
+ editor_controller();
~editor_controller();
@@ -154,7 +154,6 @@ class editor_controller : public controller_base,
/* mouse_handler_base overrides */
void mouse_motion(int x, int y, const bool browse, bool update, map_location new_loc = map_location::null_location()) override;
- void touch_motion(int x, int y, const bool browse, bool update=false, map_location new_loc = map_location::null_location()) override;
editor_display& gui() override { return *gui_; }
const editor_display& gui() const override { return *gui_; }
bool allow_mouse_wheel_scroll(int x, int y) override;
diff --git a/src/editor/editor_display.cpp b/src/editor/editor_display.cpp
index 83474072091..75a26b50df6 100644
--- a/src/editor/editor_display.cpp
+++ b/src/editor/editor_display.cpp
@@ -16,6 +16,7 @@
#include "editor/controller/editor_controller.hpp"
#include "editor/editor_display.hpp"
#include "lexical_cast.hpp"
+#include "overlay.hpp"
#include "reports.hpp"
#include "team.hpp"
#include "terrain/builder.hpp"
@@ -127,4 +128,9 @@ const time_of_day& editor_display::get_time_of_day(const map_location& /*loc*/)
return controller_.get_current_map_context().get_time_manager()->get_time_of_day();
}
+display::overlay_map& editor_display::get_overlays()
+{
+ return controller_.get_current_map_context().get_overlays();
+}
+
} //end namespace editor
diff --git a/src/editor/editor_display.hpp b/src/editor/editor_display.hpp
index 6ec2b88e61e..86a9d66209d 100644
--- a/src/editor/editor_display.hpp
+++ b/src/editor/editor_display.hpp
@@ -50,6 +50,9 @@ protected:
void draw_hex(const map_location& loc) override;
+ /** Inherited from display. */
+ virtual overlay_map& get_overlays() override;
+
const SDL_Rect& get_clip_rect() override;
void draw_sidebar() override;
diff --git a/src/editor/editor_main.cpp b/src/editor/editor_main.cpp
index ee8670a135a..b6f1574ee85 100644
--- a/src/editor/editor_main.cpp
+++ b/src/editor/editor_main.cpp
@@ -25,7 +25,7 @@ lg::log_domain log_editor("editor");
namespace editor {
-EXIT_STATUS start(const config& game_conf, const std::string& filename /* = "" */,
+EXIT_STATUS start(const std::string& filename /* = "" */,
bool take_screenshot /* = false */, const std::string& screenshot_filename /* = "map_screenshot.bmp" */)
{
EXIT_STATUS e = EXIT_ERROR;
@@ -33,7 +33,7 @@ EXIT_STATUS start(const config& game_conf, const std::string& filename /* = "" *
hotkey::scope_changer h_;
hotkey::deactivate_all_scopes();
hotkey::set_scope_active(hotkey::SCOPE_EDITOR);
- editor_controller editor(game_conf);
+ editor_controller editor;
if (!filename.empty() && filesystem::file_exists (filename)) {
if (filesystem::is_directory(filename)) {
editor.context_manager_->set_default_dir(filename);
diff --git a/src/editor/editor_main.hpp b/src/editor/editor_main.hpp
index 0722a348c1e..bec02896836 100644
--- a/src/editor/editor_main.hpp
+++ b/src/editor/editor_main.hpp
@@ -33,6 +33,6 @@ enum EXIT_STATUS {
* go back to the titlescreen or quit to desktop altogether)
*/
-EXIT_STATUS start(const config& game_config, const std::string& filename = "", bool take_screenshot = false, const std::string& screenshot_filename = "map_screenshot.bmp");
+EXIT_STATUS start(const std::string& filename = "", bool take_screenshot = false, const std::string& screenshot_filename = "map_screenshot.bmp");
} //end namespace editor
diff --git a/src/editor/map/context_manager.cpp b/src/editor/map/context_manager.cpp
index 25b1e94608d..429197f2cce 100644
--- a/src/editor/map/context_manager.cpp
+++ b/src/editor/map/context_manager.cpp
@@ -99,9 +99,6 @@ void context_manager::refresh_on_context_change()
// TODO register the tod_manager with the gui?
resources::tod_manager = get_map_context().get_time_manager();
-
- gui().replace_overlay_map(&get_map_context().get_overlays());
-
resources::classification = &get_map_context().get_classification();
gui().init_flags();
@@ -701,9 +698,8 @@ void context_manager::generate_map_dialog()
gui2::dialogs::editor_generate_map dialog(map_generators_);
dialog.select_map_generator(last_map_generator_);
- dialog.show();
- if(dialog.get_retval() == gui2::retval::OK) {
+ if(dialog.show()) {
std::string map_string;
map_generator* const map_generator = dialog.get_selected_map_generator();
try {
diff --git a/src/editor/palette/editor_palettes.cpp b/src/editor/palette/editor_palettes.cpp
index 30655ced33b..81fbc5d6171 100644
--- a/src/editor/palette/editor_palettes.cpp
+++ b/src/editor/palette/editor_palettes.cpp
@@ -333,7 +333,7 @@ void editor_palette<Item>::draw_contents()
// Force compilation of the following template instantiations
template class editor_palette<t_translation::terrain_code>;
-template class editor_palette<unit_type>;
+template class editor_palette<const unit_type&>;
template class editor_palette<overlay>;
} // end namespace editor
diff --git a/src/editor/palette/unit_palette.cpp b/src/editor/palette/unit_palette.cpp
index 5f2214a4ed3..0304da854b9 100644
--- a/src/editor/palette/unit_palette.cpp
+++ b/src/editor/palette/unit_palette.cpp
@@ -97,8 +97,8 @@ void unit_palette::draw_item(const unit_type& u, surface& image, std::stringstre
unit_palette::unit_palette(editor_display &gui, const config& cfg,
editor_toolkit &toolkit)
//TODO avoid magic numbers
- : editor_palette<unit_type>(gui, cfg, 36, 4, toolkit),
- selected_bg_items_()
+ : editor_palette<const unit_type&>(gui, cfg, 36, 4, toolkit)
+ , selected_bg_items_()
{
}
diff --git a/src/editor/palette/unit_palette.hpp b/src/editor/palette/unit_palette.hpp
index b75aa98f092..a5c241826f9 100644
--- a/src/editor/palette/unit_palette.hpp
+++ b/src/editor/palette/unit_palette.hpp
@@ -29,7 +29,7 @@ class editor_toolkit;
//std::string get_selected_terrain();
/** Palette where the terrain to be drawn can be selected. */
-class unit_palette : public editor_palette<unit_type> {
+class unit_palette : public editor_palette<const unit_type&> {
public:
unit_palette(editor_display &gui,
diff --git a/src/events.cpp b/src/events.cpp
index b7995752728..226ecace4ff 100644
--- a/src/events.cpp
+++ b/src/events.cpp
@@ -45,10 +45,9 @@ struct invoked_function_data
{
explicit invoked_function_data(const std::function<void(void)>& func)
: f(func)
- , finished()
+ , finished(false)
, thrown_exception()
{
- finished = false;
}
/** The actual function to call. */
@@ -464,7 +463,7 @@ void pump()
events.push_back(temp_event);
}
- std::vector<SDL_Event>::iterator ev_it = events.begin();
+ auto ev_it = events.begin();
for(int i = 1; i < begin_ignoring; ++i) {
if(is_input(*ev_it)) {
// ignore user input events that occurred before the window was activated
@@ -474,14 +473,15 @@ void pump()
}
}
- std::vector<SDL_Event>::iterator ev_end = events.end();
bool resize_found = false;
- for(ev_it = events.begin(); ev_it != ev_end; ++ev_it) {
- SDL_Event& event = *ev_it;
+ for(const SDL_Event& event : boost::adaptors::reverse(events)) {
if(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
resize_found = true;
last_resize_event = event;
last_resize_event_used = false;
+
+ // Since we're working backwards, the first resize event found is the last in the list.
+ break;
}
}
@@ -504,73 +504,11 @@ void pump()
events.erase(first_draw_event + 1, events.end());
}
- ev_end = events.end();
-
- for(ev_it = events.begin(); ev_it != ev_end; ++ev_it) {
+ for(const SDL_Event& event : events) {
for(context& c : event_contexts) {
c.add_staging_handlers();
}
- SDL_Event& event = *ev_it;
-
-#ifdef MOUSE_TOUCH_EMULATION
- switch (event.type) {
- // TODO: Implement SDL_MULTIGESTURE. Some day.
- case SDL_MOUSEMOTION:
- if(event.motion.which != SDL_TOUCH_MOUSEID && event.motion.state == 0) {
- return;
- }
-
- if(event.motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT))
- {
- SDL_Rect r = CVideo::get_singleton().screen_area();
-
- // TODO: Check if SDL_FINGERMOTION is actually signaled for COMPLETE motions (I doubt, but tbs)
- SDL_Event touch_event;
- touch_event.type = SDL_FINGERMOTION;
- touch_event.tfinger.type = SDL_FINGERMOTION;
- touch_event.tfinger.timestamp = event.motion.timestamp;
- touch_event.tfinger.touchId = 1;
- touch_event.tfinger.fingerId = 1;
- touch_event.tfinger.dx = static_cast<float>(event.motion.xrel) / r.w;
- touch_event.tfinger.dy = static_cast<float>(event.motion.yrel) / r.h;
- touch_event.tfinger.x = static_cast<float>(event.motion.x) / r.w;
- touch_event.tfinger.y = static_cast<float>(event.motion.y) / r.h;
- touch_event.tfinger.pressure = 1;
- ::SDL_PushEvent(&touch_event);
-
- event.motion.state = SDL_BUTTON(SDL_BUTTON_LEFT);
- event.motion.which = SDL_TOUCH_MOUSEID;
- }
- break;
- case SDL_MOUSEBUTTONDOWN:
- case SDL_MOUSEBUTTONUP:
- if(event.button.button == SDL_BUTTON_RIGHT)
- {
- event.button.button = SDL_BUTTON_LEFT;
- event.button.which = SDL_TOUCH_MOUSEID;
-
- SDL_Rect r = CVideo::get_singleton().screen_area();
- SDL_Event touch_event;
- touch_event.type = (event.type == SDL_MOUSEBUTTONDOWN) ? SDL_FINGERDOWN : SDL_FINGERUP;
- touch_event.tfinger.type = touch_event.type;
- touch_event.tfinger.timestamp = event.button.timestamp;
- touch_event.tfinger.touchId = 1;
- touch_event.tfinger.fingerId = 1;
- touch_event.tfinger.dx = 0;
- touch_event.tfinger.dy = 0;
- touch_event.tfinger.x = static_cast<float>(event.button.x) / r.w;
- touch_event.tfinger.y = static_cast<float>(event.button.y) / r.h;
- touch_event.tfinger.pressure = 1;
- ::SDL_PushEvent(&touch_event);
-
- }
- break;
- default:
- break;
- }
-#endif
-
switch(event.type) {
case SDL_WINDOWEVENT:
switch(event.window.event) {
@@ -617,19 +555,15 @@ void pump()
case SDL_MOUSEBUTTONDOWN: {
// Always make sure a cursor is displayed if the mouse moves or if the user clicks
cursor::set_focus(true);
- if(event.button.button == SDL_BUTTON_LEFT || event.button.which == SDL_TOUCH_MOUSEID) {
+ if(event.button.button == SDL_BUTTON_LEFT) {
static const int DoubleClickTime = 500;
-#ifdef __IPHONEOS__
- static const int DoubleClickMaxMove = 15;
-#else
static const int DoubleClickMaxMove = 3;
-#endif
if(last_mouse_down >= 0 && info.ticks() - last_mouse_down < DoubleClickTime
&& std::abs(event.button.x - last_click_x) < DoubleClickMaxMove
&& std::abs(event.button.y - last_click_y) < DoubleClickMaxMove
) {
- sdl::UserEvent user_event(DOUBLE_CLICK_EVENT, event.button.which, event.button.x, event.button.y);
+ sdl::UserEvent user_event(DOUBLE_CLICK_EVENT, event.button.x, event.button.y);
::SDL_PushEvent(reinterpret_cast<SDL_Event*>(&user_event));
}
diff --git a/src/filesystem_boost.cpp b/src/filesystem.cpp
similarity index 97%
rename from src/filesystem_boost.cpp
rename to src/filesystem.cpp
index 7b27717af71..92bbadc00d7 100644
--- a/src/filesystem_boost.cpp
+++ b/src/filesystem.cpp
@@ -52,15 +52,6 @@
#include <algorithm>
#include <set>
-// Copied from boost::predef, as it's there only since 1.55.
-#if defined(__APPLE__) && defined(__MACH__) && defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
-
-#define WESNOTH_BOOST_OS_IOS (__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__*1000)
-#include <SDL_filesystem.h>
-
-#endif
-
-
static lg::log_domain log_filesystem("filesystem");
#define DBG_FS LOG_STREAM(debug, log_filesystem)
#define LOG_FS LOG_STREAM(info, log_filesystem)
@@ -601,12 +592,9 @@ void set_user_data_dir(std::string newprefdir)
newprefdir = "Wesnoth" + get_version_path_suffix();
}
- wchar_t docs_path[MAX_PATH];
+ PWSTR docs_path = nullptr;
+ HRESULT res = SHGetKnownFolderPath(FOLDERID_Documents, KF_FLAG_CREATE, nullptr, &docs_path);
- HRESULT res = SHGetFolderPathW(nullptr,
- CSIDL_PERSONAL | CSIDL_FLAG_CREATE, nullptr,
- SHGFP_TYPE_CURRENT,
- docs_path);
if(res != S_OK) {
//
// Crummy fallback path full of pain and suffering.
@@ -621,20 +609,14 @@ void set_user_data_dir(std::string newprefdir)
user_data_dir = games_path / newprefdir;
}
+
+ CoTaskMemFree(docs_path);
}
#else /*_WIN32*/
std::string backupprefdir = ".wesnoth" + get_version_path_suffix();
-#ifdef WESNOTH_BOOST_OS_IOS
- char *sdl_pref_path = SDL_GetPrefPath("wesnoth.org", "iWesnoth");
- if(sdl_pref_path) {
- backupprefdir = std::string(sdl_pref_path) + backupprefdir;
- SDL_free(sdl_pref_path);
- }
-#endif
-
#ifdef _X11
const char* home_str = getenv("HOME");
@@ -906,8 +888,7 @@ filesystem::scoped_istream istream_file(const std::string& fname, bool treat_fai
return s;
}
- return filesystem::scoped_istream(
- new boost::iostreams::stream<boost::iostreams::file_descriptor_source>(fd, 4096, 0));
+ return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_source>>(fd, 4096, 0);
} catch(const std::exception&) {
if(treat_failure_as_error) {
ERR_FS << "Could not open '" << fname << "' for reading.\n";
@@ -925,8 +906,7 @@ filesystem::scoped_ostream ostream_file(const std::string& fname, bool create_di
#if 1
try {
boost::iostreams::file_descriptor_sink fd(bfs::path(fname), std::ios_base::binary);
- return filesystem::scoped_ostream(
- new boost::iostreams::stream<boost::iostreams::file_descriptor_sink>(fd, 4096, 0));
+ return std::make_unique<boost::iostreams::stream<boost::iostreams::file_descriptor_sink>>(fd, 4096, 0);
} catch(const BOOST_IOSTREAMS_FAILURE& e) {
// If this operation failed because the parent directory didn't exist, create the parent directory and
// retry.
@@ -952,8 +932,8 @@ void write_file(const std::string& fname, const std::string& data)
char buf[block_size];
for(size_t i = 0; i < data.size(); i += block_size) {
- const size_t bytes = std::min<size_t>(block_size,data.size() - i);
- std::copy(data.begin() + i, data.begin() + i + bytes,buf);
+ const size_t bytes = std::min<size_t>(block_size, data.size() - i);
+ std::copy(data.begin() + i, data.begin() + i + bytes, buf);
os->write(buf, bytes);
if(os->bad()) {
diff --git a/src/floating_textbox.cpp b/src/floating_textbox.cpp
index e42ea97c22b..900c6025f7b 100644
--- a/src/floating_textbox.cpp
+++ b/src/floating_textbox.cpp
@@ -1,7 +1,7 @@
/*
Copyright (C) 2006 - 2018 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
wesnoth playturn Copyright (C) 2003 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/floating_textbox.hpp b/src/floating_textbox.hpp
index 6e88a15667e..f25336fb0ad 100644
--- a/src/floating_textbox.hpp
+++ b/src/floating_textbox.hpp
@@ -1,7 +1,7 @@
/*
Copyright (C) 2006 - 2018 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
wesnoth playturn Copyright (C) 2003 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/font_description.hpp b/src/font/font_description.hpp
index 9e3de758959..a97e00386da 100644
--- a/src/font/font_description.hpp
+++ b/src/font/font_description.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2015 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/font_id.hpp b/src/font/font_id.hpp
index 719eabe0c46..03451f90848 100644
--- a/src/font/font_id.hpp
+++ b/src/font/font_id.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2016 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/marked-up_text.cpp b/src/font/marked-up_text.cpp
index 79b9d2cf7e7..2493b08c406 100644
--- a/src/font/marked-up_text.cpp
+++ b/src/font/marked-up_text.cpp
@@ -224,7 +224,7 @@ bool is_format_char(char c)
}
}
-bool is_cjk_char(const ucs4::char_t ch)
+bool is_cjk_char(const char32_t ch)
{
/**
* You can check these range at http://unicode.org/charts/
@@ -320,7 +320,7 @@ namespace {
* CJK µáçþé╣þ¼ªÕÅÀ (CJK punctuations)
* http://www.unicode.org/charts/PDF/U3000.pdf
*/
-inline bool no_break_after(const ucs4::char_t ch)
+inline bool no_break_after(const char32_t ch)
{
return
/**
@@ -341,7 +341,7 @@ inline bool no_break_after(const ucs4::char_t ch)
ch == 0x3016 || ch == 0x301a || ch == 0x301d;
}
-inline bool no_break_before(const ucs4::char_t ch)
+inline bool no_break_before(const char32_t ch)
{
return
/**
@@ -378,7 +378,7 @@ inline bool no_break_before(const ucs4::char_t ch)
ch == 0x301b || ch == 0x301e;
}
-inline bool break_before(const ucs4::char_t ch)
+inline bool break_before(const char32_t ch)
{
if(no_break_before(ch))
return false;
@@ -386,7 +386,7 @@ inline bool break_before(const ucs4::char_t ch)
return is_cjk_char(ch);
}
-inline bool break_after(const ucs4::char_t ch)
+inline bool break_after(const char32_t ch)
{
if(no_break_after(ch))
return false;
@@ -420,7 +420,7 @@ std::string word_wrap_text(const std::string& unwrapped_text, int font_size,
if(start_of_line) {
line_width = 0;
format_string.clear();
- while(ch != end && *ch < static_cast<ucs4::char_t>(0x100)
+ while(ch != end && *ch < static_cast<char32_t>(0x100)
&& is_format_char(*ch) && !ch.next_is_end()) {
format_string.append(ch.substr().first, ch.substr().second);
@@ -443,7 +443,7 @@ std::string word_wrap_text(const std::string& unwrapped_text, int font_size,
current_word = *ch;
++ch;
} else {
- ucs4::char_t previous = 0;
+ char32_t previous = 0;
for(;ch != utf8::iterator::end(unwrapped_text) &&
*ch != ' ' && *ch != '\n'; ++ch) {
diff --git a/src/font/marked-up_text.hpp b/src/font/marked-up_text.hpp
index 6171aa271b5..ab900f3466e 100644
--- a/src/font/marked-up_text.hpp
+++ b/src/font/marked-up_text.hpp
@@ -22,7 +22,6 @@ class CVideo;
class surface;
#include <string>
-#include "serialization/unicode_types.hpp"
#include <SDL_rect.h>
@@ -84,12 +83,12 @@ std::string del_tags(const std::string& text);
bool is_format_char(char c);
/**
- * Determine if a ucs4::char_t is a CJK character
+ * Determine if a char32_t is a CJK character
*
* @retval true Input-char is a CJK char
* @retval false Input-char is a not CJK char.
*/
-bool is_cjk_char(const ucs4::char_t ch);
+bool is_cjk_char(const char32_t ch);
/**
* Wrap text.
diff --git a/src/font/sdl_ttf.cpp b/src/font/sdl_ttf.cpp
index ffe588335a4..c7f09152402 100644
--- a/src/font/sdl_ttf.cpp
+++ b/src/font/sdl_ttf.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2016 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/sdl_ttf.hpp b/src/font/sdl_ttf.hpp
index 060e6e6a75b..cccd0f2f485 100644
--- a/src/font/sdl_ttf.hpp
+++ b/src/font/sdl_ttf.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/standard_colors.hpp b/src/font/standard_colors.hpp
index 850171baa14..f013b722f03 100644
--- a/src/font/standard_colors.hpp
+++ b/src/font/standard_colors.hpp
@@ -19,7 +19,7 @@
namespace font {
//
-// TODO: these should probably all be constexpr
+// TODO: these should probably all be CONSTEXPR
//
extern const color_t
diff --git a/src/font/text.cpp b/src/font/text.cpp
index 025df308fac..6d20cf8c02b 100644
--- a/src/font/text.cpp
+++ b/src/font/text.cpp
@@ -132,21 +132,21 @@ unsigned pango_text::insert_text(const unsigned offset, const std::string& text)
if (length_ + len > maximum_length_) {
len = maximum_length_ - length_;
}
- const utf8::string insert = text.substr(0, utf8::index(text, len));
- utf8::string tmp = text_;
+ const std::string insert = text.substr(0, utf8::index(text, len));
+ std::string tmp = text_;
this->set_text(utf8::insert(tmp, offset, insert), false);
// report back how many characters were actually inserted (e.g. to move the cursor selection)
return len;
}
-bool pango_text::insert_unicode(const unsigned offset, ucs4::char_t unicode)
+bool pango_text::insert_unicode(const unsigned offset, char32_t unicode)
{
- return this->insert_unicode(offset, ucs4::string(1, unicode)) == 1;
+ return this->insert_unicode(offset, std::u32string(1, unicode)) == 1;
}
-unsigned pango_text::insert_unicode(const unsigned offset, const ucs4::string& unicode)
+unsigned pango_text::insert_unicode(const unsigned offset, const std::u32string& unicode)
{
- const utf8::string insert = unicode_cast<utf8::string>(unicode);
+ const std::string insert = unicode_cast<std::string>(unicode);
return this->insert_text(offset, insert);
}
@@ -289,8 +289,8 @@ bool pango_text::set_text(const std::string& text, const bool markedup)
layout_.reset(pango_layout_new(context_.get()));
}
- const ucs4::string wide = unicode_cast<ucs4::string>(text);
- const std::string narrow = unicode_cast<utf8::string>(wide);
+ const std::u32string wide = unicode_cast<std::u32string>(text);
+ const std::string narrow = unicode_cast<std::string>(wide);
if(text != narrow) {
ERR_GUI_L << "pango_text::" << __func__
<< " text '" << text
@@ -439,7 +439,7 @@ pango_text& pango_text::set_maximum_length(const size_t maximum_length)
if(maximum_length != maximum_length_) {
maximum_length_ = maximum_length;
if(length_ > maximum_length_) {
- utf8::string tmp = text_;
+ std::string tmp = text_;
this->set_text(utf8::truncate(tmp, maximum_length_), false);
}
}
@@ -862,4 +862,10 @@ void pango_text::copy_layout_properties(PangoLayout& src, PangoLayout& dst)
pango_layout_set_ellipsize(&dst, pango_layout_get_ellipsize(&src));
}
+pango_text& get_text_renderer()
+{
+ static pango_text text_renderer;
+ return text_renderer;
+}
+
} // namespace font
diff --git a/src/font/text.hpp b/src/font/text.hpp
index 145f0c519e3..0d14d9dd78a 100644
--- a/src/font/text.hpp
+++ b/src/font/text.hpp
@@ -18,7 +18,6 @@
#include "color.hpp"
#include "sdl/surface.hpp"
#include "serialization/string_utils.hpp"
-#include "serialization/unicode_types.hpp"
#include <pango/pango.h>
#include <pango/pangocairo.h>
@@ -119,7 +118,7 @@ public:
*
* @returns True upon success, false otherwise.
*/
- bool insert_unicode(const unsigned offset, ucs4::char_t unicode);
+ bool insert_unicode(const unsigned offset, char32_t unicode);
/**
* Inserts unicode text.
@@ -130,7 +129,7 @@ public:
* @returns The number of characters inserted.
*/
unsigned insert_unicode(
- const unsigned offset, const ucs4::string& unicode);
+ const unsigned offset, const std::u32string& unicode);
/***** ***** ***** ***** Font flags ***** ***** ***** *****/
@@ -447,4 +446,13 @@ private:
void format_links(std::string& text, const std::vector<std::string>& links) const;
};
+/**
+ * Returns a reference to a static pango_text object.
+ *
+ * Since the class is essentially a render pipeline, there's no need for individual
+ * areas of the game to own their own renderers. Not to mention it isn't a trivial
+ * class; constructing one is likely to be expensive.
+ */
+pango_text& get_text_renderer();
+
} // namespace font
diff --git a/src/font/text_cache.cpp b/src/font/text_cache.cpp
index 0a9f0479288..d617db0917d 100644
--- a/src/font/text_cache.cpp
+++ b/src/font/text_cache.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2016 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/text_surface.cpp b/src/font/text_surface.cpp
index 941b7d63ce5..dc664c2281e 100644
--- a/src/font/text_surface.cpp
+++ b/src/font/text_surface.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2016 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/font/text_surface.hpp b/src/font/text_surface.hpp
index c76f15bdb32..db5a1f041c6 100644
--- a/src/font/text_surface.hpp
+++ b/src/font/text_surface.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2016 - 2018 by Chris Beck<render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/format_time_summary.cpp b/src/format_time_summary.cpp
index 494e3843524..16213013b89 100644
--- a/src/format_time_summary.cpp
+++ b/src/format_time_summary.cpp
@@ -22,19 +22,19 @@ namespace utils {
std::string format_time_summary(time_t t) {
time_t curtime = time(nullptr);
- const struct tm* timeptr = localtime(&curtime);
+ const std::tm* timeptr = std::localtime(&curtime);
if(timeptr == nullptr) {
return "";
}
- const struct tm current_time = *timeptr;
+ const std::tm current_time = *timeptr;
- timeptr = localtime(&t);
+ timeptr = std::localtime(&t);
if(timeptr == nullptr) {
return "";
}
- const struct tm save_time = *timeptr;
+ const std::tm save_time = *timeptr;
std::string format_string;
diff --git a/src/formula/function.cpp b/src/formula/function.cpp
index 9d677811625..e3c812018bf 100644
--- a/src/formula/function.cpp
+++ b/src/formula/function.cpp
@@ -491,21 +491,21 @@ DEFINE_WFL_FUNCTION(str_lower, 1, 1)
DEFINE_WFL_FUNCTION(sin, 1, 1)
{
const double angle = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = sin(angle * pi<double>() / 180.0);
+ const double result = std::sin(angle * pi<double>() / 180.0);
return variant(result, variant::DECIMAL_VARIANT);
}
DEFINE_WFL_FUNCTION(cos, 1, 1)
{
const double angle = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = cos(angle * pi<double>() / 180.0);
+ const double result = std::cos(angle * pi<double>() / 180.0);
return variant(result, variant::DECIMAL_VARIANT);
}
DEFINE_WFL_FUNCTION(tan, 1, 1)
{
const double angle = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = tan(angle * pi<double>() / 180.0);
+ const double result = std::tan(angle * pi<double>() / 180.0);
if(std::isnan(result) || result <= INT_MIN || result >= INT_MAX) {
return variant();
}
@@ -516,7 +516,7 @@ DEFINE_WFL_FUNCTION(tan, 1, 1)
DEFINE_WFL_FUNCTION(asin, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = asin(num) * 180.0 / pi<double>();
+ const double result = std::asin(num) * 180.0 / pi<double>();
if(std::isnan(result)) {
return variant();
}
@@ -527,7 +527,7 @@ DEFINE_WFL_FUNCTION(asin, 1, 1)
DEFINE_WFL_FUNCTION(acos, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = acos(num) * 180.0 / pi<double>();
+ const double result = std::acos(num) * 180.0 / pi<double>();
if(std::isnan(result)) {
return variant();
}
@@ -538,14 +538,14 @@ DEFINE_WFL_FUNCTION(acos, 1, 1)
DEFINE_WFL_FUNCTION(atan, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = atan(num) * 180.0 / pi<double>();
+ const double result = std::atan(num) * 180.0 / pi<double>();
return variant(result, variant::DECIMAL_VARIANT);
}
DEFINE_WFL_FUNCTION(sqrt, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = sqrt(num);
+ const double result = std::sqrt(num);
if(std::isnan(result)) {
return variant();
}
@@ -556,7 +556,7 @@ DEFINE_WFL_FUNCTION(sqrt, 1, 1)
DEFINE_WFL_FUNCTION(cbrt, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = num < 0 ? -pow(-num, 1.0 / 3.0) : pow(num, 1.0 / 3.0);
+ const double result = num < 0 ? -std::pow(-num, 1.0 / 3.0) : std::pow(num, 1.0 / 3.0);
return variant(result, variant::DECIMAL_VARIANT);
}
@@ -564,7 +564,7 @@ DEFINE_WFL_FUNCTION(root, 2, 2)
{
const double base = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
const double root = args()[1]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = base < 0 && fmod(root, 2) == 1 ? -pow(-base, 1.0 / root) : pow(base, 1.0 / root);
+ const double result = base < 0 && std::fmod(root, 2) == 1 ? -std::pow(-base, 1.0 / root) : std::pow(base, 1.0 / root);
if(std::isnan(result)) {
return variant();
}
@@ -576,7 +576,7 @@ DEFINE_WFL_FUNCTION(log, 1, 2)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
if(args().size() == 1) {
- const double result = log(num);
+ const double result = std::log(num);
if(std::isnan(result)) {
return variant();
}
@@ -585,7 +585,7 @@ DEFINE_WFL_FUNCTION(log, 1, 2)
}
const double base = args()[1]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = log(num) / log(base);
+ const double result = std::log(num) / std::log(base);
if(std::isnan(result)) {
return variant();
}
@@ -596,7 +596,7 @@ DEFINE_WFL_FUNCTION(log, 1, 2)
DEFINE_WFL_FUNCTION(exp, 1, 1)
{
const double num = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
- const double result = exp(num);
+ const double result = std::exp(num);
if(result == 0 || result >= INT_MAX) {
// These are range errors rather than NaNs,
// but I figure it's better than returning INT_MIN.
@@ -617,7 +617,7 @@ DEFINE_WFL_FUNCTION(hypot, 2, 2)
{
const double x = args()[0]->evaluate(variables, fdb).as_decimal() / 1000.0;
const double y = args()[1]->evaluate(variables, fdb).as_decimal() / 1000.0;
- return variant(hypot(x, y), variant::DECIMAL_VARIANT);
+ return variant(std::hypot(x, y), variant::DECIMAL_VARIANT);
}
DEFINE_WFL_FUNCTION(index_of, 2, 2)
@@ -677,7 +677,7 @@ DEFINE_WFL_FUNCTION(wave, 1, 1)
{
const int value = args()[0]->evaluate(variables, fdb).as_int() % 1000;
const double angle = 2.0 * pi<double>() * (static_cast<double>(value) / 1000.0);
- return variant(static_cast<int>(sin(angle) * 1000.0));
+ return variant(static_cast<int>(std::sin(angle) * 1000.0));
}
namespace
@@ -1368,7 +1368,7 @@ formula_function_expression::formula_function_expression(const std::string& name
, star_arg_(-1)
{
for(size_t n = 0; n != arg_names_.size(); ++n) {
- if(arg_names_[n].empty() == false && arg_names_[n].back() == '*') {
+ if(arg_names_.empty() == false && arg_names_[n].back() == '*') {
arg_names_[n].resize(arg_names_[n].size() - 1);
star_arg_ = n;
break;
diff --git a/src/formula/string_utils.cpp b/src/formula/string_utils.cpp
index 0559742353e..cb7a3010b74 100644
--- a/src/formula/string_utils.cpp
+++ b/src/formula/string_utils.cpp
@@ -71,7 +71,7 @@ static std::string do_interpolation(const std::string &str, const variable_set&
// For the next iteration of the loop, search for more '$'
// (not from the same place because sometimes the '$' is not replaced)
- rfind_dollars_sign_from = int(var_begin_loc) - 1;
+ rfind_dollars_sign_from = static_cast<int>(var_begin_loc) - 1;
const std::string::iterator var_begin = res.begin() + var_begin_loc;
diff --git a/src/formula/tokenizer.cpp b/src/formula/tokenizer.cpp
index 6a18f17201e..b88ae98fa9a 100644
--- a/src/formula/tokenizer.cpp
+++ b/src/formula/tokenizer.cpp
@@ -24,7 +24,7 @@ namespace tokenizer
namespace {
-void raise_exception(iterator& i1, iterator i2, std::string str) {
+NORETURN void raise_exception(iterator& i1, iterator i2, std::string str) {
std::ostringstream expr;
while( (i1 != i2) && (*i1 != '\n') ) {
if( (*i1 != '\t') )
@@ -283,8 +283,7 @@ token get_token(iterator& i1, const iterator i2) {
raise_exception(it, i2, std::string() );
}
}
- raise_exception(it, i2, std::string() );
- return token();
+ raise_exception(it, i2, std::string());
}
}
diff --git a/src/formula/variant.cpp b/src/formula/variant.cpp
index ef9b35673a8..68cd8c6443a 100644
--- a/src/formula/variant.cpp
+++ b/src/formula/variant.cpp
@@ -469,7 +469,7 @@ variant variant::operator^(const variant& v) const
{
if(is_decimal() || v.is_decimal()) {
- double res = pow(as_decimal() / 1000.0 , v.as_decimal() / 1000.0);
+ double res = std::pow(as_decimal() / 1000.0 , v.as_decimal() / 1000.0);
if(std::isnan(res)) {
return variant();
@@ -478,7 +478,7 @@ variant variant::operator^(const variant& v) const
return variant(res, DECIMAL_VARIANT);
}
- return variant(static_cast<int>(round_portable(pow(static_cast<double>(as_int()), v.as_int()))));
+ return variant(static_cast<int>(std::round(std::pow(static_cast<double>(as_int()), v.as_int()))));
}
variant variant::operator-() const
diff --git a/src/game_board.cpp b/src/game_board.cpp
index b37e0d5f362..b67d4c254b1 100644
--- a/src/game_board.cpp
+++ b/src/game_board.cpp
@@ -170,7 +170,7 @@ unit_map::iterator game_board::find_visible_unit(const map_location &loc,
{
if (!map_->on_board(loc)) return units_.end();
unit_map::iterator u = units_.find(loc);
- if (!u.valid() || !u->is_visible_to_team(current_team, *this, see_all))
+ if (!u.valid() || !u->is_visible_to_team(current_team, see_all))
return units_.end();
return u;
}
@@ -179,7 +179,7 @@ bool game_board::has_visible_unit(const map_location & loc, const team& current_
{
if (!map_->on_board(loc)) return false;
unit_map::const_iterator u = units_.find(loc);
- if (!u.valid() || !u->is_visible_to_team(current_team, *this, see_all))
+ if (!u.valid() || !u->is_visible_to_team(current_team, see_all))
return false;
return true;
}
@@ -283,12 +283,6 @@ boost::optional<std::string> game_board::replace_map(const gamemap & newmap) {
return ret;
}
-
-
-void game_board::overlay_map(const gamemap & mask_map, const config & cfg, map_location loc) {
- map_->overlay(mask_map, cfg, loc);
-}
-
bool game_board::change_terrain(const map_location &loc, const std::string &t_str,
const std::string & mode_str, bool replace_if_failed)
{
diff --git a/src/game_board.hpp b/src/game_board.hpp
index 3267e27923b..2a1e1e4a314 100644
--- a/src/game_board.hpp
+++ b/src/game_board.hpp
@@ -155,8 +155,7 @@ public:
// Manipulator from actionwml
bool try_add_unit_to_recall_list(const map_location& loc, const unit_ptr u);
- boost::optional<std::string> replace_map (const gamemap & r);
- void overlay_map (const gamemap & o, const config & cfg, map_location loc);
+ boost::optional<std::string> replace_map(const gamemap & r);
bool change_terrain(const map_location &loc, const std::string &t,
const std::string & mode, bool replace_if_failed); //used only by lua
diff --git a/src/game_classification.cpp b/src/game_classification.cpp
index dea12370f4d..aa5759d4c64 100644
--- a/src/game_classification.cpp
+++ b/src/game_classification.cpp
@@ -15,9 +15,9 @@
#include "game_classification.hpp"
#include "config.hpp"
-#include "game_config.hpp"
#include "log.hpp"
#include "serialization/string_utils.hpp"
+#include "game_version.hpp"
static lg::log_domain log_engine("engine");
#define ERR_NG LOG_STREAM(err, log_engine)
@@ -96,7 +96,7 @@ config game_classification::to_config() const
{
config cfg;
cfg["label"] = label;
- cfg["version"] = game_config::version;
+ cfg["version"] = game_config::wesnoth_version.str();
cfg["campaign_type"] = campaign_type.to_string();
cfg["campaign_define"] = campaign_define;
cfg["campaign_extra_defines"] = utils::join(campaign_xtra_defines);
diff --git a/src/game_config.cpp b/src/game_config.cpp
index d59cc163b50..3e739e2408a 100644
--- a/src/game_config.cpp
+++ b/src/game_config.cpp
@@ -23,9 +23,6 @@
#include "game_version.hpp"
#include "wesconfig.h"
#include "serialization/string_utils.hpp"
-#ifdef LOAD_REVISION
-#include "revision.h"
-#endif
static lg::log_domain log_engine("engine");
#define LOG_NG LOG_STREAM(info, log_engine)
@@ -33,24 +30,9 @@ static lg::log_domain log_engine("engine");
namespace game_config
{
-
//
-// Path and revision info
+// Path info
//
-const std::string version = VERSION;
-
-const version_info wesnoth_version(VERSION);
-const version_info min_savegame_version(MIN_SAVEGAME_VERSION);
-const version_info test_version("test");
-
-#ifdef REVISION
-const std::string revision = VERSION " (" REVISION ")";
-#elif defined(VCS_SHORT_HASH) && defined(VCS_WC_MODIFIED)
-const std::string revision = std::string(VERSION) + " (" + VCS_SHORT_HASH + (VCS_WC_MODIFIED ? "-Modified" : "-Clean") + ")";
-#else
-const std::string revision = VERSION;
-#endif
-
#ifdef WESNOTH_PATH
std::string path = WESNOTH_PATH;
#else
@@ -73,6 +55,7 @@ int village_income = 1;
int village_support = 1;
int recall_cost = 20;
int kill_experience = 8;
+int combat_experience = 1;
int poison_amount = 8;
int rest_heal_amount = 2;
@@ -212,9 +195,6 @@ std::string
// orbs and hp/xp bar
orb,
energy,
- // top bar icons
- battery_icon,
- time_icon,
// flags
flag,
flag_icon,
@@ -298,6 +278,7 @@ void load_config(const config &v)
rest_heal_amount = v["rest_heal_amount"].to_int(2);
recall_cost = v["recall_cost"].to_int(20);
kill_experience = v["kill_experience"].to_int(8);
+ combat_experience= v["combat_experience"].to_int(1);
lobby_refresh = v["lobby_refresh"].to_int(2000);
default_terrain = v["default_terrain"].str();
tile_size = v["tile_size"].to_int(72);
@@ -347,9 +328,6 @@ void load_config(const config &v)
orb = i["orb"].str();
energy = i["energy"].str();
- battery_icon = i["battery_icon"].str();
- time_icon = i["time_icon"].str();
-
flag = i["flag"].str();
flag_icon = i["flag_icon"].str();
diff --git a/src/game_config.hpp b/src/game_config.hpp
index b0bc8ee4eb4..1021b102b4f 100644
--- a/src/game_config.hpp
+++ b/src/game_config.hpp
@@ -15,7 +15,6 @@
#pragma once
class config;
-class version_info;
class color_range;
#include "color.hpp"
@@ -35,11 +34,10 @@ namespace game_config
extern int rest_heal_amount;
extern int recall_cost;
extern int kill_experience;
+ extern int combat_experience;
extern unsigned int tile_size;
extern unsigned lobby_network_timer;
extern unsigned lobby_refresh;
- extern const std::string version;
- extern const std::string revision;
extern const std::string default_title_string;
extern std::string default_terrain;
@@ -50,6 +48,11 @@ namespace game_config
return level ? kill_experience * level : kill_experience / 2;
}
+ inline int combat_xp(int level)
+ {
+ return combat_experience * level;
+ }
+
extern std::string wesnoth_program_dir;
/** Default percentage gold carried over to the next scenario. */
@@ -101,9 +104,6 @@ namespace game_config
// orbs and hp/xp bar
orb,
energy,
- // top bar icons
- battery_icon,
- time_icon,
// flags
flag,
flag_icon,
@@ -192,9 +192,5 @@ namespace game_config
color_t red_to_green(int val, bool for_text = true);
color_t blue_to_white(int val, bool for_text = true);
- extern const version_info wesnoth_version;
- extern const version_info min_savegame_version;
- extern const version_info test_version;
-
std::string get_default_title_string();
}
diff --git a/src/game_display.cpp b/src/game_display.cpp
index 85eca501edd..3428cff0835 100644
--- a/src/game_display.cpp
+++ b/src/game_display.cpp
@@ -43,6 +43,7 @@
#include "units/unit.hpp"
#include "units/drawer.hpp"
#include "whiteboard/manager.hpp"
+#include "overlay.hpp"
static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)
@@ -79,7 +80,6 @@ game_display::game_display(game_board& board, std::weak_ptr<wb::manager> wb,
mode_(RUNNING),
needs_rebuild_(false)
{
- replace_overlay_map(&overlay_map_);
video().clear_screen();
}
@@ -200,7 +200,7 @@ void game_display::scroll_to_leader(int side, SCROLL_TYPE scroll_type,bool force
{
unit_map::const_iterator leader = dc_->units().find_leader(side);
- if(leader.valid() && leader->is_visible_to_team(dc_->get_team(viewing_side()), *dc_, false)) {
+ if(leader.valid() && leader->is_visible_to_team(dc_->get_team(viewing_side()), false)) {
scroll_to_tile(leader->get_location(), scroll_type, true, force);
}
}
@@ -370,7 +370,6 @@ void game_display::draw_sidebar()
return;
refresh_report("report_clock");
- refresh_report("report_battery");
refresh_report("report_countdown");
if (invalidateGameStatus_)
@@ -672,3 +671,8 @@ bool game_display::maybe_rebuild() {
}
return false;
}
+
+display::overlay_map& game_display::get_overlays()
+{
+ return overlay_map_;
+}
diff --git a/src/game_display.hpp b/src/game_display.hpp
index 7196aa364aa..136834c9db5 100644
--- a/src/game_display.hpp
+++ b/src/game_display.hpp
@@ -142,6 +142,9 @@ protected:
virtual void draw_hex(const map_location& loc) override;
+ /** Inherited from display. */
+ virtual overlay_map& get_overlays() override;
+
public:
/** Set the attack direction indicator. */
void set_attack_indicator(const map_location& src, const map_location& dst);
diff --git a/src/game_end_exceptions.cpp b/src/game_end_exceptions.cpp
index b3c9ad35a4b..8a37db9ccb2 100644
--- a/src/game_end_exceptions.cpp
+++ b/src/game_end_exceptions.cpp
@@ -16,7 +16,6 @@
#include "game_end_exceptions.hpp"
#include "config.hpp"
-#include "game_config.hpp"
transient_end_level::transient_end_level()
: carryover_report(true)
diff --git a/src/game_events/action_wml.cpp b/src/game_events/action_wml.cpp
index d2565319f61..33fbfe99991 100644
--- a/src/game_events/action_wml.cpp
+++ b/src/game_events/action_wml.cpp
@@ -61,6 +61,7 @@
#include "units/filter.hpp"
#include "wml_exception.hpp"
#include "whiteboard/manager.hpp"
+#include "deprecation.hpp"
#include <boost/regex.hpp>
@@ -401,6 +402,7 @@ WML_HANDLER_FUNCTION(move_units_fake,, cfg)
events::command_disabler command_disabler;
LOG_NG << "Processing [move_units_fake]\n";
+ const bool force_scroll = cfg["force_scroll"].to_bool();
const vconfig::child_list unit_cfgs = cfg.get_children("fake_unit");
size_t num_units = unit_cfgs.size();
std::vector<fake_unit_ptr > units;
@@ -440,7 +442,7 @@ WML_HANDLER_FUNCTION(move_units_fake,, cfg)
DBG_NG << "Moving unit " << un << ", doing step " << step << '\n';
path_step[0] = paths[un][step - 1];
path_step[1] = paths[un][step];
- unit_display::move_unit(path_step, units[un].get_unit_ptr());
+ unit_display::move_unit(path_step, units[un].get_unit_ptr(), true, map_location::NDIRECTIONS, force_scroll);
units[un]->set_location(path_step[1]);
units[un]->anim_comp().set_standing(false);
}
@@ -466,10 +468,11 @@ WML_HANDLER_FUNCTION(recall,, cfg)
*/
temp_config["x"] = "recall";
temp_config["y"] = "recall";
+ temp_config.remove_attribute("location_id");
vconfig unit_filter_cfg(temp_config);
const vconfig & leader_filter = cfg.child("secondary_unit");
- for(int index = 0; index < int(resources::gameboard->teams().size()); ++index) {
+ for(int index = 0; index < static_cast<int>(resources::gameboard->teams().size()); ++index) {
LOG_NG << "for side " << index + 1 << "...\n";
const std::string player_id = resources::gameboard->teams()[index].save_id_or_number();
@@ -492,7 +495,14 @@ WML_HANDLER_FUNCTION(recall,, cfg)
const unit_ptr to_recruit = *u;
const unit* pass_check = to_recruit.get();
if(!cfg["check_passability"].to_bool(true)) pass_check = nullptr;
- const map_location cfg_loc = cfg_to_loc(cfg);
+ map_location cfg_loc = cfg_to_loc(cfg);
+ if(cfg.has_attribute("location_id")) {
+ const auto& special_locs = resources::gameboard->map().special_locations().left;
+ const auto& iter = special_locs.find(cfg["location_id"]);
+ if(iter != special_locs.end()) {
+ cfg_loc = iter->second;
+ }
+ }
/// @todo fendrin: comment this monster
for (unit_map::const_unit_iterator leader : leaders) {
@@ -599,11 +609,14 @@ WML_HANDLER_FUNCTION(replace_map,, cfg)
if(!cfg["map_file"].empty()) {
config file_cfg = mp_sync::get_user_choice("map_data", map_choice(cfg["map_file"].str()));
map.read(file_cfg["map_data"].str(), false);
+ } else if(!cfg["map_data"].empty()) {
+ map.read(cfg["map_data"], false);
} else {
+ deprecated_message("[replace_map]map=", DEP_LEVEL::INDEFINITE, "1.16", "Use map_data= instead.");
map.read(cfg["map"], false);
}
} catch(const incorrect_map_format_error&) {
- const std::string log_map_name = cfg["map"].empty() ? cfg["file"] : std::string("from inline data");
+ const std::string log_map_name = cfg["map"].empty() ? cfg["map_file"] : std::string("from inline data");
lg::wml_error() << "replace_map: Unable to load map " << log_map_name << std::endl;
return;
} catch(const wml_exception& e) {
@@ -849,41 +862,6 @@ WML_HANDLER_FUNCTION(store_time_of_day,, cfg)
}
}
-/// Creating a mask of the terrain
-WML_HANDLER_FUNCTION(terrain_mask,, cfg)
-{
- map_location loc = cfg_to_loc(cfg, 1, 1);
-
- gamemap mask_map(resources::gameboard->map().tdata(), "");
-
- try {
- if(!cfg["mask_file"].empty()) {
- const std::string& maskfile = filesystem::get_wml_location(cfg["mask_file"].str());
-
- if(filesystem::file_exists(maskfile)) {
- mask_map.read(filesystem::read_file(maskfile), false);
- } else {
- throw incorrect_map_format_error("Invalid file path");
- }
- } else {
- mask_map.read(cfg["mask"], false);
- }
- } catch(const incorrect_map_format_error&) {
- ERR_NG << "terrain mask is in the incorrect format, and couldn't be applied" << std::endl;
- return;
- } catch(const wml_exception& e) {
- e.show();
- return;
- }
-
- if (!cfg["border"].to_bool(true)) {
- mask_map.add_fog_border();
- }
-
- resources::gameboard->overlay_map(mask_map, cfg.get_parsed_config(), loc);
- game_display::get_singleton()->needs_rebuild(true);
-}
-
WML_HANDLER_FUNCTION(tunnel,, cfg)
{
const bool remove = cfg["remove"].to_bool(false);
diff --git a/src/game_events/manager.cpp b/src/game_events/manager.cpp
index fe60233fd21..a7a62a7b6b9 100644
--- a/src/game_events/manager.cpp
+++ b/src/game_events/manager.cpp
@@ -139,12 +139,12 @@ void manager::write_events(config& cfg) const
continue;
}
- // This function may be invoked mid-event, such as via [inspect] (the inspector writes
- // the events to a local config) or if an out-of-sync error happens in MP. In that case,
- // it's possible for the currently running event is already disabled. That would happen
- // if it's a first-time-only event; those are disabled before their actions are run. In
- // that case, skip disabled events. If invoked from outside an event, however, there
- // should be no disabled events in the list, so assert if one is found.
+ // Silently skip disabled events if this function is invoked mid-event, such as via
+ // [inspect] (the inspector writes the events to a local config) or if an out-of-sync
+ // error occurs in MP. If the event in question is first-time-only, it will already
+ // have been flagged as disabled by this point (such events are disabled before their
+ // actions are run). If a disabled event is encountered outside an event context,
+ // however, assert. That means something went wrong with event list cleanup.
if(eh->disabled() && is_event_running()) {
continue;
} else {
diff --git a/src/game_initialization/configure_engine.cpp b/src/game_initialization/configure_engine.cpp
index d2a63fda2ae..d492cbca315 100644
--- a/src/game_initialization/configure_engine.cpp
+++ b/src/game_initialization/configure_engine.cpp
@@ -14,7 +14,6 @@
#include "game_initialization/configure_engine.hpp"
#include "formula/string_utils.hpp"
-#include "game_config_manager.hpp"
#include "mp_game_settings.hpp"
#include "preferences/credentials.hpp"
#include "preferences/game.hpp"
diff --git a/src/game_initialization/connect_engine.cpp b/src/game_initialization/connect_engine.cpp
index 76305f4fb4f..5b88532231d 100644
--- a/src/game_initialization/connect_engine.cpp
+++ b/src/game_initialization/connect_engine.cpp
@@ -23,8 +23,8 @@
#include "log.hpp"
#include "map/map.hpp"
#include "mt_rng.hpp"
-#include "team.hpp"
#include "tod_manager.hpp"
+#include "team.hpp"
#include "wesnothd_connection.hpp"
#include <cstdlib>
diff --git a/src/game_initialization/lobby_data.cpp b/src/game_initialization/lobby_data.cpp
index c3c1d7a53fd..8a9b89c63b5 100644
--- a/src/game_initialization/lobby_data.cpp
+++ b/src/game_initialization/lobby_data.cpp
@@ -22,6 +22,7 @@
#include "font/pango/escape.hpp"
#include "formatter.hpp"
#include "formula/string_utils.hpp"
+#include "game_config_manager.hpp"
#include "gettext.hpp"
#include "lexical_cast.hpp"
#include "log.hpp"
@@ -194,7 +195,7 @@ std::string make_game_type_marker(std::string text, bool color_for_missing)
} // end anon namespace
-game_info::game_info(const config& game, const config& game_config, const std::vector<std::string>& installed_addons)
+game_info::game_info(const config& game, const std::vector<std::string>& installed_addons)
: id(game["id"])
, map_data(game["map_data"])
, name(font::escape_text(game["name"]))
@@ -230,6 +231,8 @@ game_info::game_info(const config& game, const config& game_config, const std::v
, required_addons()
, addons_outcome(SATISFIED)
{
+ const config& game_config = game_config_manager::get()->game_config();
+
// Parse the list of addons required to join this game.
for(const config& addon : game.child_range("addon")) {
if(addon.has_attribute("id")) {
@@ -304,7 +307,7 @@ game_info::game_info(const config& game, const config& game_config, const std::v
}
}
- std::sort(mod_info.begin(), mod_info.end(), [](const std::pair<std::string, bool>& lhs, const std::pair<std::string, bool>& rhs) {
+ std::sort(mod_info.begin(), mod_info.end(), [](const auto& lhs, const auto& rhs) {
return translation::icompare(lhs.first, rhs.first) < 0;
});
diff --git a/src/game_initialization/lobby_data.hpp b/src/game_initialization/lobby_data.hpp
index a374f3a6f0c..cb04c1723ef 100644
--- a/src/game_initialization/lobby_data.hpp
+++ b/src/game_initialization/lobby_data.hpp
@@ -14,6 +14,7 @@
#pragma once
+#include <ctime>
#include <set>
#include <deque>
#include <functional>
@@ -136,7 +137,7 @@ struct user_info
*/
struct game_info
{
- game_info(const config& c, const config& game_config, const std::vector<std::string>& installed_addons);
+ game_info(const config& c, const std::vector<std::string>& installed_addons);
bool can_join() const;
bool can_observe() const;
diff --git a/src/game_initialization/lobby_info.cpp b/src/game_initialization/lobby_info.cpp
index e0eefe5aa47..dc7cb5483c2 100644
--- a/src/game_initialization/lobby_info.cpp
+++ b/src/game_initialization/lobby_info.cpp
@@ -35,9 +35,8 @@ static lg::log_domain log_lobby("lobby");
namespace mp
{
-lobby_info::lobby_info(const config& game_config, const std::vector<std::string>& installed_addons)
- : game_config_(game_config)
- , installed_addons_(installed_addons)
+lobby_info::lobby_info(const std::vector<std::string>& installed_addons)
+ : installed_addons_(installed_addons)
, gamelist_()
, gamelist_initialized_(false)
, rooms_()
@@ -116,7 +115,7 @@ void lobby_info::process_gamelist(const config& data)
games_by_id_.clear();
for(const auto& c : gamelist_.child("gamelist").child_range("game")) {
- game_info game(c, game_config_, installed_addons_);
+ game_info game(c, installed_addons_);
games_by_id_.emplace(game.id, std::move(game));
}
@@ -176,12 +175,12 @@ bool lobby_info::process_gamelist_diff_impl(const config& data)
// is replaced by game_info::UPDATED below. See also
// https://github.com/wesnoth/wesnoth/blob/1.14/src/server/server.cpp#L149
if(current_i == games_by_id_.end()) {
- games_by_id_.emplace(game_id, game_info(c, game_config_, installed_addons_));
+ games_by_id_.emplace(game_id, game_info(c, installed_addons_));
continue;
}
// Had a game with that id, so update it and mark it as such
- current_i->second = game_info(c, game_config_, installed_addons_);
+ current_i->second = game_info(c, installed_addons_);
current_i->second.display_status = game_info::UPDATED;
} else if(diff_result == "deleted") {
if(current_i == games_by_id_.end()) {
diff --git a/src/game_initialization/lobby_info.hpp b/src/game_initialization/lobby_info.hpp
index ce3b6e5cd0a..2c9c47ef7ab 100644
--- a/src/game_initialization/lobby_info.hpp
+++ b/src/game_initialization/lobby_info.hpp
@@ -30,7 +30,7 @@ namespace mp
class lobby_info
{
public:
- explicit lobby_info(const config& game_config, const std::vector<std::string>& installed_addons);
+ explicit lobby_info(const std::vector<std::string>& installed_addons);
typedef std::map<int, game_info> game_info_map;
@@ -149,8 +149,6 @@ public:
private:
void process_userlist();
- const config& game_config_;
-
const std::vector<std::string>& installed_addons_;
config gamelist_;
diff --git a/src/game_initialization/mp_game_utils.cpp b/src/game_initialization/mp_game_utils.cpp
index 56c2dcd1847..ef78cabcb6f 100644
--- a/src/game_initialization/mp_game_utils.cpp
+++ b/src/game_initialization/mp_game_utils.cpp
@@ -15,11 +15,11 @@
#include "config.hpp"
#include "formula/string_utils.hpp"
-#include "game_config.hpp"
#include "game_config_manager.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "saved_game.hpp"
+#include "game_version.hpp"
#include "wesnothd_connection_error.hpp"
static lg::log_domain log_engine("engine");
@@ -125,7 +125,7 @@ config initial_level_config(saved_game& state)
}
// This will force connecting clients to be using the same version number as us.
- level["version"] = game_config::version;
+ level["version"] = game_config::wesnoth_version.str();
return level;
}
diff --git a/src/game_initialization/multiplayer.cpp b/src/game_initialization/multiplayer.cpp
index d052e1dd0db..dd3f93f7557 100644
--- a/src/game_initialization/multiplayer.cpp
+++ b/src/game_initialization/multiplayer.cpp
@@ -54,7 +54,7 @@ std::pair<wesnothd_connection_ptr, config> open_connection(std::string host)
{
DBG_MP << "opening connection" << std::endl;
- wesnothd_connection_ptr sock;
+ wesnothd_connection_ptr sock(nullptr);
if(host.empty()) {
return std::make_pair(std::move(sock), config());
}
@@ -76,7 +76,7 @@ std::pair<wesnothd_connection_ptr, config> open_connection(std::string host)
shown_hosts.emplace(host, port);
// Initializes the connection to the server.
- sock = wesnothd_connection::create(host, std::to_string(port));
+ sock = std::make_unique<wesnothd_connection>(host, std::to_string(port));
if(!sock) {
return std::make_pair(std::move(sock), config());
}
@@ -119,7 +119,7 @@ std::pair<wesnothd_connection_ptr, config> open_connection(std::string host)
utils::string_map i18n_symbols;
i18n_symbols["required_version"] = version;
- i18n_symbols["your_version"] = game_config::version;
+ i18n_symbols["your_version"] = game_config::wesnoth_version.str();
const std::string errorstring = VGETTEXT("The server accepts versions '$required_version', but you are using version '$your_version'", i18n_symbols);
throw wesnothd_error(errorstring);
@@ -139,8 +139,8 @@ std::pair<wesnothd_connection_ptr, config> open_connection(std::string host)
gui2::dialogs::loading_screen::progress(loading_stage::redirect);
// Open a new connection with the new host and port.
- sock = wesnothd_connection_ptr();
- sock = wesnothd_connection::create(host, std::to_string(port));
+ sock.reset();
+ sock = std::make_unique<wesnothd_connection>(host, std::to_string(port));
// Wait for new handshake.
while(!sock->handshake_finished()) {
@@ -155,7 +155,7 @@ std::pair<wesnothd_connection_ptr, config> open_connection(std::string host)
if(data.has_child("version")) {
config cfg;
config res;
- cfg["version"] = game_config::version;
+ cfg["version"] = game_config::wesnoth_version.str();
res.add_child("version", std::move(cfg));
sock->send_data(res);
}
@@ -416,7 +416,7 @@ void enter_wait_mode(mp_workflow_helper_ptr helper, int game_id, bool observe)
statistics::fresh_stats();
- std::unique_ptr<mp_campaign_info> campaign_info(new mp_campaign_info(*helper->connection));
+ auto campaign_info = std::make_unique<mp_campaign_info>(*helper->connection);
campaign_info->is_host = false;
if(helper->lobby_info->get_game_by_id(game_id)) {
@@ -442,7 +442,7 @@ void enter_wait_mode(mp_workflow_helper_ptr helper, int game_id, bool observe)
}
if(dlg_ok) {
- campaign_controller controller(helper->state, helper->game_config, game_config_manager::get()->terrain_types());
+ campaign_controller controller(helper->state, game_config_manager::get()->terrain_types());
controller.set_mp_info(campaign_info.get());
controller.play_game();
}
@@ -473,7 +473,7 @@ void enter_staging_mode(mp_workflow_helper_ptr helper)
} // end connect_engine_ptr, dlg scope
if(dlg_ok) {
- campaign_controller controller(helper->state, helper->game_config, game_config_manager::get()->terrain_types());
+ campaign_controller controller(helper->state, game_config_manager::get()->terrain_types());
controller.set_mp_info(campaign_info.get());
controller.play_game();
}
@@ -527,7 +527,7 @@ bool enter_lobby_mode(mp_workflow_helper_ptr helper, const std::vector<std::stri
sound::stop_music();
}
- mp::lobby_info li(helper->game_config, installed_addons);
+ mp::lobby_info li(installed_addons);
helper->lobby_info = &li;
if(!initial_lobby_config.empty()) {
@@ -639,17 +639,17 @@ void start_client(const config& game_config, saved_game& state, const std::strin
} while(re_enter);
}
-bool goto_mp_connect(ng::connect_engine& engine, const config& game_config, wesnothd_connection* connection)
+bool goto_mp_connect(ng::connect_engine& engine, wesnothd_connection* connection)
{
- lobby_info li(game_config, {});
+ lobby_info li({});
gui2::dialogs::mp_staging dlg(engine, li, connection);
return dlg.show();
}
-bool goto_mp_wait(saved_game& state, const config& game_config, wesnothd_connection* connection, bool observe)
+bool goto_mp_wait(saved_game& state, wesnothd_connection* connection, bool observe)
{
- lobby_info li(game_config, std::vector<std::string>());
+ lobby_info li({});
gui2::dialogs::mp_join_game dlg(state, li, *connection, false, observe);
@@ -672,7 +672,7 @@ void start_local_game(const config& game_config, saved_game& state)
preferences::set_message_private(false);
// TODO: should lobby_info take a nullptr in this case, or should we pass the installed_addons data here too?
- lobby_info li(game_config, {});
+ lobby_info li({});
mp_workflow_helper_ptr workflow_helper = std::make_shared<mp_workflow_helper>(game_config, state, nullptr, &li);
enter_create_mode(workflow_helper);
@@ -774,7 +774,7 @@ void start_local_game_commandline(const config& game_config, saved_game& state,
unsigned int repeat = (cmdline_opts.multiplayer_repeat) ? *cmdline_opts.multiplayer_repeat : 1;
for(unsigned int i = 0; i < repeat; i++){
saved_game state_copy(state);
- campaign_controller controller(state_copy, game_config, game_config_manager::get()->terrain_types());
+ campaign_controller controller(state_copy, game_config_manager::get()->terrain_types());
controller.play_game();
}
}
diff --git a/src/game_initialization/multiplayer.hpp b/src/game_initialization/multiplayer.hpp
index c654211760e..d5b1347d4db 100644
--- a/src/game_initialization/multiplayer.hpp
+++ b/src/game_initialization/multiplayer.hpp
@@ -57,13 +57,12 @@ void start_client(const config& game_config,
* Opens mp::connect screen and sets game state according to the
* changes made.
*/
-bool goto_mp_connect(ng::connect_engine& engine,
- const config& game_config, wesnothd_connection* connection);
+bool goto_mp_connect(ng::connect_engine& engine, wesnothd_connection* connection);
/**
* Opens mp::wait screen and sets game state according to the
* changes made.
*/
-bool goto_mp_wait(saved_game& state, const config& game_config, wesnothd_connection* connection, bool observe);
+bool goto_mp_wait(saved_game& state, wesnothd_connection* connection, bool observe);
}
diff --git a/src/game_initialization/playcampaign.cpp b/src/game_initialization/playcampaign.cpp
index cfe74f72014..0cf99d71b8f 100644
--- a/src/game_initialization/playcampaign.cpp
+++ b/src/game_initialization/playcampaign.cpp
@@ -186,15 +186,16 @@ void campaign_controller::show_carryover_message(playsingle_controller& playcont
LEVEL_RESULT campaign_controller::playsingle_scenario(end_level_data &end_level)
{
- playsingle_controller playcontroller(is_replay_ ? state_.get_replay_starting_point() : state_.get_starting_point(), state_, game_config_, tdata_, false);
+ playsingle_controller playcontroller(is_replay_ ? state_.get_replay_starting_point() : state_.get_starting_point(),
+ state_, tdata_, false);
+
LOG_NG << "created objects... " << (SDL_GetTicks() - playcontroller.get_ticks()) << "\n";
if(is_replay_) {
playcontroller.enable_replay(is_unit_test_);
}
LEVEL_RESULT res = playcontroller.play_scenario(is_replay_ ? state_.get_replay_starting_point() : state_.get_starting_point());
- if (res == LEVEL_RESULT::QUIT)
- {
+ if (res == LEVEL_RESULT::QUIT) {
return LEVEL_RESULT::QUIT;
}
if(!is_unit_test_)
@@ -220,8 +221,7 @@ LEVEL_RESULT campaign_controller::playsingle_scenario(end_level_data &end_level)
LEVEL_RESULT campaign_controller::playmp_scenario(end_level_data &end_level)
{
- playmp_controller playcontroller(state_.get_starting_point(), state_,
- game_config_, tdata_, mp_info_);
+ playmp_controller playcontroller(state_.get_starting_point(), state_, tdata_, mp_info_);
LEVEL_RESULT res = playcontroller.play_scenario(state_.get_starting_point());
//Check if the player started as mp client and changed to host
@@ -352,7 +352,7 @@ LEVEL_RESULT campaign_controller::play_game()
if (mp_info_ && !mp_info_->is_host) {
// Opens join game dialog to get a new gamestate.
- if(!mp::goto_mp_wait(state_, game_config_, &mp_info_->connection, res == LEVEL_RESULT::OBSERVER_END)) {
+ if(!mp::goto_mp_wait(state_, &mp_info_->connection, res == LEVEL_RESULT::OBSERVER_END)) {
return LEVEL_RESULT::QUIT;
}
@@ -374,7 +374,7 @@ LEVEL_RESULT campaign_controller::play_game()
if (!connect_engine->can_start_game() || (game_config::debug && game_type == game_classification::CAMPAIGN_TYPE::MULTIPLAYER)) {
// Opens staging dialog to allow users to make an adjustments for scenario.
- if(!mp::goto_mp_connect(*connect_engine, game_config_, mp_info_ ? &mp_info_->connection : nullptr)) {
+ if(!mp::goto_mp_connect(*connect_engine, mp_info_ ? &mp_info_->connection : nullptr)) {
return LEVEL_RESULT::QUIT;
}
} else {
diff --git a/src/game_initialization/playcampaign.hpp b/src/game_initialization/playcampaign.hpp
index 598b5453f4f..0554aca4fa7 100644
--- a/src/game_initialization/playcampaign.hpp
+++ b/src/game_initialization/playcampaign.hpp
@@ -57,15 +57,13 @@ struct mp_campaign_info
class campaign_controller
{
saved_game& state_;
- const config& game_config_;
const ter_data_cache & tdata_;
const bool is_unit_test_;
bool is_replay_;
mp_campaign_info* mp_info_;
public:
- campaign_controller(saved_game& state, const config& game_config, const ter_data_cache & tdata, bool is_unit_test = false)
+ campaign_controller(saved_game& state, const ter_data_cache & tdata, bool is_unit_test = false)
: state_(state)
- , game_config_(game_config)
, tdata_(tdata)
, is_unit_test_(is_unit_test)
, is_replay_(false)
diff --git a/src/game_launcher.cpp b/src/game_launcher.cpp
index e9cdfd7bd71..4e068be47ed 100644
--- a/src/game_launcher.cpp
+++ b/src/game_launcher.cpp
@@ -493,7 +493,7 @@ bool game_launcher::play_test()
load_game_config_for_game(state_.classification());
try {
- campaign_controller ccontroller(state_, game_config_manager::get()->game_config(), game_config_manager::get()->terrain_types());
+ campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
ccontroller.play_game();
} catch(const savegame::load_game_exception &e) {
load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
@@ -527,7 +527,7 @@ int game_launcher::unit_test()
load_game_config_for_game(state_.classification());
try {
- campaign_controller ccontroller(state_, game_config_manager::get()->game_config(), game_config_manager::get()->terrain_types(), true);
+ campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types(), true);
LEVEL_RESULT res = ccontroller.play_game();
if (!(res == LEVEL_RESULT::VICTORY) || lg::broke_strict()) {
return 1;
@@ -553,7 +553,7 @@ int game_launcher::unit_test()
}
try {
- campaign_controller ccontroller(state_, game_config_manager::get()->game_config(), game_config_manager::get()->terrain_types(), true);
+ campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types(), true);
LEVEL_RESULT res = ccontroller.play_replay();
if (!(res == LEVEL_RESULT::VICTORY) || lg::broke_strict()) {
std::cerr << "Observed failure on replay" << std::endl;
@@ -577,8 +577,7 @@ bool game_launcher::play_screenshot_mode()
::init_textdomains(game_config_manager::get()->game_config());
- editor::start(game_config_manager::get()->game_config(),
- screenshot_map_, true, screenshot_filename_);
+ editor::start(screenshot_map_, true, screenshot_filename_);
return false;
}
@@ -945,9 +944,9 @@ bool game_launcher::play_multiplayer_commandline()
bool game_launcher::change_language()
{
- gui2::dialogs::language_selection dlg;
- dlg.show();
- if (dlg.get_retval() != gui2::retval::OK) return false;
+ if(!gui2::dialogs::language_selection::execute()) {
+ return false;
+ }
if (!(cmdline_opts_.nogui || cmdline_opts_.headless_unit_test)) {
video().set_window_title(game_config::get_default_title_string());
@@ -984,7 +983,7 @@ void game_launcher::launch_game(RELOAD_GAME_DATA reload)
});
try {
- campaign_controller ccontroller(state_, game_config_manager::get()->game_config(), game_config_manager::get()->terrain_types());
+ campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
LEVEL_RESULT result = ccontroller.play_game();
ai::manager::singleton_ = nullptr;
// don't show The End for multiplayer scenario
@@ -1012,7 +1011,7 @@ void game_launcher::play_replay()
{
assert(!load_data_);
try {
- campaign_controller ccontroller(state_, game_config_manager::get()->game_config(), game_config_manager::get()->terrain_types());
+ campaign_controller ccontroller(state_, game_config_manager::get()->terrain_types());
ccontroller.play_replay();
} catch (const savegame::load_game_exception &e) {
load_data_.reset(new savegame::load_game_metadata(std::move(e.data_)));
@@ -1029,8 +1028,7 @@ editor::EXIT_STATUS game_launcher::start_editor(const std::string& filename)
::init_textdomains(game_config_manager::get()->game_config());
- editor::EXIT_STATUS res = editor::start(
- game_config_manager::get()->game_config(), filename);
+ editor::EXIT_STATUS res = editor::start(filename);
if(res != editor::EXIT_RELOAD_DATA)
return res;
diff --git a/src/game_launcher.hpp b/src/game_launcher.hpp
index c2f073a7a50..586c71ba95b 100644
--- a/src/game_launcher.hpp
+++ b/src/game_launcher.hpp
@@ -19,7 +19,7 @@
#include "font/font_config.hpp" // for manager
#include "preferences/game.hpp" // for manager
#include "hotkey/hotkey_manager.hpp" // for manager
-#include "picture.hpp" // for manager
+#include "picture.hpp" // for manager
#include "saved_game.hpp" // for saved_game
#include "sound.hpp" // for music_thinker
diff --git a/src/game_state.cpp b/src/game_state.cpp
index cca987cc708..fa0868013dd 100644
--- a/src/game_state.cpp
+++ b/src/game_state.cpp
@@ -161,7 +161,7 @@ void game_state::place_sides_in_preferred_locations(const config& level)
std::set<int> placed;
std::set<map_location> positions_taken;
- for (std::vector<placing_info>::const_iterator i = placings.begin(); i != placings.end() && int(placed.size()) != side_num - 1; ++i) {
+ for (std::vector<placing_info>::const_iterator i = placings.begin(); i != placings.end() && static_cast<int>(placed.size()) != side_num - 1; ++i) {
if(placed.count(i->side) == 0 && positions_taken.count(i->pos) == 0) {
placed.insert(i->side);
positions_taken.insert(i->pos);
diff --git a/src/game_version.cpp b/src/game_version.cpp
index 07186ed2924..285aedd91d0 100644
--- a/src/game_version.cpp
+++ b/src/game_version.cpp
@@ -13,8 +13,14 @@
*/
#include "game_version.hpp"
+
#include "lexical_cast.hpp"
#include "serialization/string_utils.hpp"
+#include "wesconfig.h"
+
+#ifdef LOAD_REVISION
+#include "revision.h"
+#endif
#include <cassert>
#include <functional>
@@ -22,6 +28,22 @@
#include <boost/algorithm/string.hpp>
+namespace game_config
+{
+const version_info wesnoth_version(VERSION);
+const version_info min_savegame_version(MIN_SAVEGAME_VERSION);
+const version_info test_version("test");
+
+#ifdef REVISION
+const std::string revision = VERSION " (" REVISION ")";
+#elif defined(VCS_SHORT_HASH) && defined(VCS_WC_MODIFIED)
+const std::string revision = std::string(VERSION) + " (" + VCS_SHORT_HASH + (VCS_WC_MODIFIED ? "-Modified" : "-Clean") + ")";
+#else
+const std::string revision = VERSION;
+#endif
+
+} // namespace game_config
+
version_info::version_info()
: nums_(3,0), special_(""), special_separator_('\0')
{
diff --git a/src/game_version.hpp b/src/game_version.hpp
index a2e972af566..34867c7e43b 100644
--- a/src/game_version.hpp
+++ b/src/game_version.hpp
@@ -204,3 +204,13 @@ enum VERSION_COMP_OP {
VERSION_COMP_OP parse_version_op(const std::string& op_str);
bool do_version_check(const version_info& a, VERSION_COMP_OP op, const version_info& b);
+
+namespace game_config
+{
+extern const version_info wesnoth_version;
+extern const version_info min_savegame_version;
+extern const version_info test_version;
+
+extern const std::string revision;
+
+} // namespace game_config
diff --git a/src/generators/cave_map_generator.cpp b/src/generators/cave_map_generator.cpp
index 5a6097691a4..779f2d6679a 100644
--- a/src/generators/cave_map_generator.cpp
+++ b/src/generators/cave_map_generator.cpp
@@ -104,8 +104,8 @@ cave_map_generator::cave_map_generator_job::cave_map_generator_job(const cave_ma
uint32_t seed = randomseed.get_ptr() ? *randomseed.get_ptr() : seed_rng::next_seed();
rng_.seed(seed);
LOG_NG << "creating random cave with seed: " << seed << '\n';
- flipx_ = int(rng_() % 100) < params.flipx_chance_;
- flipy_ = int(rng_() % 100) < params.flipy_chance_;
+ flipx_ = static_cast<int>(rng_() % 100) < params.flipx_chance_;
+ flipy_ = static_cast<int>(rng_() % 100) < params.flipy_chance_;
LOG_NG << "creating scenario....\n";
generate_chambers();
@@ -135,7 +135,7 @@ void cave_map_generator::cave_map_generator_job::build_chamber(map_location loc,
adjacent_loc_array_t adj;
get_adjacent_tiles(loc,adj.data());
for(size_t n = 0; n < adj.size(); ++n) {
- if(int(rng_() % 100) < (100l - static_cast<long>(jagged))) {
+ if(static_cast<int>(rng_() % 100) < (100l - static_cast<long>(jagged))) {
build_chamber(adj[n],locs,size-1,jagged);
}
}
@@ -146,7 +146,7 @@ void cave_map_generator::cave_map_generator_job::generate_chambers()
for (const config &ch : params.cfg_.child_range("chamber"))
{
// If there is only a chance of the chamber appearing, deal with that here.
- if (ch.has_attribute("chance") && int(rng_() % 100) < ch["chance"].to_int()) {
+ if (ch.has_attribute("chance") && static_cast<int>(rng_() % 100) < ch["chance"].to_int()) {
continue;
}
@@ -301,7 +301,7 @@ double passage_path_calculator::cost(const map_location& loc, const double) cons
}
if(windiness_ > 1) {
- res *= double(rng_()%windiness_);
+ res *= static_cast<double>(rng_()%windiness_);
}
return res;
@@ -310,7 +310,7 @@ double passage_path_calculator::cost(const map_location& loc, const double) cons
void cave_map_generator::cave_map_generator_job::place_passage(const passage& p)
{
const std::string& chance = p.cfg["chance"];
- if(!chance.empty() && int(rng_()%100) < std::stoi(chance)) {
+ if(!chance.empty() && static_cast<int>(rng_()%100) < std::stoi(chance)) {
return;
}
@@ -341,7 +341,7 @@ void cave_map_generator::cave_map_generator_job::set_terrain(map_location loc, c
if(c == params.clear_ || c == params.wall_ || c == params.village_) {
// Change this terrain.
- if ( t == params.clear_ && int(rng_() % 1000) < params.village_density_ )
+ if ( t == params.clear_ && static_cast<int>(rng_() % 1000) < params.village_density_ )
// Override with a village.
c = params.village_;
else
diff --git a/src/generators/cave_map_generator.hpp b/src/generators/cave_map_generator.hpp
index dc7c4cc1542..a9acc295acc 100644
--- a/src/generators/cave_map_generator.hpp
+++ b/src/generators/cave_map_generator.hpp
@@ -45,7 +45,7 @@ private:
chamber()
: center()
, locs()
- , items(0)
+ , items(nullptr)
{
}
diff --git a/src/generators/default_map_generator_job.cpp b/src/generators/default_map_generator_job.cpp
index ea4e4b91d90..19a696b261b 100644
--- a/src/generators/default_map_generator_job.cpp
+++ b/src/generators/default_map_generator_job.cpp
@@ -302,14 +302,14 @@ height_map default_map_generator_job::generate_height_map(size_t width, size_t h
// Is this a negative hill? (i.e. a valley)
bool is_valley = false;
- int x1 = island_size > 0 ? center_x - island_size + (rng_()%(island_size*2)) : int(rng_()%width);
- int y1 = island_size > 0 ? center_y - island_size + (rng_()%(island_size*2)) : int(rng_()%height);
+ int x1 = island_size > 0 ? center_x - island_size + (rng_()%(island_size*2)) : static_cast<int>(rng_()%width);
+ int y1 = island_size > 0 ? center_y - island_size + (rng_()%(island_size*2)) : static_cast<int>(rng_()%height);
// We have to check whether this is actually a valley
if(island_size != 0) {
- const size_t diffx = std::abs(x1 - int(center_x));
- const size_t diffy = std::abs(y1 - int(center_y));
- const size_t dist = size_t(std::sqrt(double(diffx*diffx + diffy*diffy)));
+ const size_t diffx = std::abs(x1 - static_cast<int>(center_x));
+ const size_t diffy = std::abs(y1 - static_cast<int>(center_y));
+ const size_t dist = size_t(std::sqrt(static_cast<double>(diffx*diffx + diffy*diffy)));
is_valley = dist > island_size;
}
@@ -326,7 +326,7 @@ height_map default_map_generator_job::generate_height_map(size_t width, size_t h
const int xdiff = (x2-x1);
const int ydiff = (y2-y1);
- const int hill_height = radius - int(std::sqrt(double(xdiff*xdiff + ydiff*ydiff)));
+ const int hill_height = radius - static_cast<int>(std::sqrt(static_cast<double>(xdiff*xdiff + ydiff*ydiff)));
if(hill_height > 0) {
if(is_valley) {
@@ -1014,7 +1014,7 @@ std::string default_map_generator_job::default_generate_map(generator_data data,
dst.x += data.width/3 - 1;
dst.y += data.height/3 - 1;
- if(data.link_castles && road < int(castles.size() * castles.size())) {
+ if(data.link_castles && road < static_cast<int>(castles.size() * castles.size())) {
const size_t src_castle = road/castles.size();
const size_t dst_castle = road%castles.size();
if(src_castle >= dst_castle) {
diff --git a/src/generic_event.cpp b/src/generic_event.cpp
index fe6006f5177..5953dfa4b11 100644
--- a/src/generic_event.cpp
+++ b/src/generic_event.cpp
@@ -57,20 +57,13 @@ bool generic_event::detach_handler(observer* obs){
//make sure observers are not notified right now
if (!notify_active_){
- change_handler_ = true;
- try{
- std::vector<observer*>::iterator it = std::find(observers_.begin(), observers_.end(), obs);
- if (it == observers_.end()){
- handler_detached = false;
- }
- else{
- observers_.erase(it);
- handler_detached = true;
- }
+ auto it = std::find(observers_.begin(), observers_.end(), obs);
+ if (it == observers_.end()){
+ handler_detached = false;
}
- catch (...){
- change_handler_ = false;
- throw;
+ else{
+ observers_.erase(it);
+ handler_detached = true;
}
change_handler_ = false;
}
diff --git a/src/gettext_boost.cpp b/src/gettext.cpp
similarity index 98%
rename from src/gettext_boost.cpp
rename to src/gettext.cpp
index a6d8fc90af9..ad550b49635 100644
--- a/src/gettext_boost.cpp
+++ b/src/gettext.cpp
@@ -25,8 +25,6 @@
#include <locale>
#include <mutex>
#include <boost/locale.hpp>
-// including boost/thread fixes linking of boost locale for msvc on boost 1.60
-#include <boost/thread.hpp>
#include <set>
#if defined(__GNUC__)
@@ -507,21 +505,12 @@ int icompare(const std::string& s1, const std::string& s2)
#endif
}
-void init()
-{
-}
-
std::string strftime(const std::string& format, const std::tm* time)
{
std::basic_ostringstream<char> dummy;
std::lock_guard<std::mutex> lock(get_mutex());
dummy.imbue(get_manager().get_locale());
- // See utils/io.hpp for explanation of this check
-#if HAVE_PUT_TIME
dummy << std::put_time(time, format.c_str());
-#else
- dummy << bl::as::ftime(format) << mktime(const_cast<std::tm*>(time));
-#endif
return dummy.str();
}
diff --git a/src/gettext.hpp b/src/gettext.hpp
index 2237c4d5689..ee134ecf649 100644
--- a/src/gettext.hpp
+++ b/src/gettext.hpp
@@ -47,7 +47,9 @@
# define GETTEXT_DOMAIN ""
#endif
-#if defined(__GNUCC__) || defined(__clang__) || defined(__MINGW32__)
+#ifdef HAVE_CXX17
+#define UNUSEDNOWARN [[maybe_unused]]
+#elif defined(__GNUCC__) || defined(__clang__) || defined(__MINGW32__)
#define UNUSEDNOWARN __attribute__((unused))
#else
#define UNUSEDNOWARN
@@ -61,11 +63,11 @@ namespace translation
//const char* sngettext(const char *singular, const char *plural, int n);
std::string dsngettext(const char * domainname, const char *singular, const char *plural, int n);
- inline UNUSEDNOWARN static std::string gettext(const char* str)
+ UNUSEDNOWARN inline static std::string gettext(const char* str)
{ return translation::dgettext(GETTEXT_DOMAIN, str); }
- inline UNUSEDNOWARN static std::string sgettext(const char* str)
+ UNUSEDNOWARN inline static std::string sgettext(const char* str)
{ return translation::dsgettext(GETTEXT_DOMAIN, str); }
- inline UNUSEDNOWARN static std::string sngettext(const char* str1, const char* str2, int n)
+ UNUSEDNOWARN inline static std::string sngettext(const char* str1, const char* str2, int n)
{ return translation::dsngettext(GETTEXT_DOMAIN, str1, str2 , n); }
@@ -74,8 +76,6 @@ namespace translation
void set_language(const std::string& language, const std::vector<std::string>* alternates);
- void init();
-
/** Case-sensitive lexicographical comparison. */
int compare(const std::string& s1,const std::string& s2);
@@ -86,11 +86,11 @@ namespace translation
}
//#define _(String) translation::dsgettext(GETTEXT_DOMAIN,String)
-inline static UNUSEDNOWARN std::string _(const char* str)
+UNUSEDNOWARN inline static std::string _(const char* str)
{ return translation::dsgettext(GETTEXT_DOMAIN, str); }
//#define _n(String1, String2, Int) translation::dsngettext(GETTEXT_DOMAIN, String1,String2,Int)
-inline UNUSEDNOWARN static std::string _n(const char* str1, const char* str2, int n)
+UNUSEDNOWARN inline static std::string _n(const char* str1, const char* str2, int n)
{ return translation::dsngettext(GETTEXT_DOMAIN, str1, str2, n); }
#define gettext_noop(String) String
diff --git a/src/global.hpp b/src/global.hpp
index 342c6f55a38..b580cd6b8c3 100644
--- a/src/global.hpp
+++ b/src/global.hpp
@@ -16,10 +16,8 @@
#ifdef _MSC_VER
-// Enable C99 support for VC14
-#if _MSC_VER>=1900
+// Enable C99 support
#define STDC99
-#endif
#endif //_MSC_VER
@@ -45,18 +43,11 @@
// Some C++11 features are not available on all supported platforms
#if defined(_MSC_VER)
-#define HAVE_PUT_TIME 1
// MSVC supports these starting in MSVC 2015
#if _MSC_VER >= 1900
#define HAVE_REF_QUALIFIERS 1
#define HAVE_INHERITING_CTORS 1
-#define CONSTEXPR constexpr
-#define NOEXCEPT noexcept
-#define NORETURN [[noreturn]]
#else
-#define CONSTEXPR
-#define NOEXCEPT throw()
-#define NORETURN __declspec(noreturn)
#endif
// MSVC supports these starting in 2017?
// Some sources claim MSVC 2015 supports them, but let's be safe...
@@ -75,43 +66,19 @@
#if defined(__clang__)
#include <ciso646> // To ensure standard library version macros are defined
-// If it's libc++, no problem. Otherwise, attempt to detect libstdc++ version (needs GCC 5.1 or higher)
-// by testing for the existence of a header added in that version.
-#if defined(_LIBCPP_VERSION) || __has_include(<experimental/any>) || __has_include(<any>)
-#define HAVE_PUT_TIME 1
-#else
-#define HAVE_PUT_TIME 0
-#endif
// Clang has convenient feature detection macros \o/
#define HAVE_REF_QUALIFIERS __has_feature(cxx_reference_qualified_functions)
#define HAVE_INHERITING_CTORS __has_feature(cxx_inheriting_constructors)
// All supported versions of clang have these
-#define NORETURN [[noreturn]]
#define FALLTHROUGH [[clang::fallthrough]]
// Use GCC-style attribute because the __has_cpp_attribute feature-checking macro doesn't exist in clang 3.5
#define DEPRECATED(reason) __attribute__((deprecated(reason)))
-#if __has_feature(cxx_constexpr)
-#define CONSTEXPR constexpr
-#else
-#define CONSTEXPR
-#endif
-
-#if __has_feature(cxx_noexcept)
-#define NOEXCEPT noexcept
-#else
-#define NOEXCEPT throw()
-#endif
#endif
#if defined(__GNUC__) && !defined(__clang__)
-// GCC 5 required for this
-#define HAVE_PUT_TIME (__GNUC__ >= 5)
// GCC supports these from 4.8 up
-#define CONSTEXPR constexpr
-#define NOEXCEPT noexcept
-#define NORETURN [[noreturn]]
#define HAVE_REF_QUALIFIERS 1
#define HAVE_INHERITING_CTORS 1
diff --git a/src/gui/auxiliary/iterator/iterator.hpp b/src/gui/auxiliary/iterator/iterator.hpp
index 9a2c8f41c8d..70523a64e3b 100644
--- a/src/gui/auxiliary/iterator/iterator.hpp
+++ b/src/gui/auxiliary/iterator/iterator.hpp
@@ -101,8 +101,22 @@ public:
{
return &(operator*());
}
+
+ /** See @ref operator*. */
+ widget* get()
+ {
+ return operator->();
+ }
};
+/* Helper aliases templates. */
+
+template<bool visit_self, bool visit_internal, bool visit_child>
+using top_down_iterator = iterator<policy::order::top_down<visit_self, visit_internal, visit_child>>;
+
+template<bool visit_self, bool visit_internal, bool visit_child>
+using bottom_up_iterator = iterator<policy::order::bottom_up<visit_self, visit_internal, visit_child>>;
+
} // namespace iteration
} // namespace gui2
diff --git a/src/gui/auxiliary/iterator/walker_grid.cpp b/src/gui/auxiliary/iterator/walker_grid.cpp
index 78049b07157..4cfc7746171 100644
--- a/src/gui/auxiliary/iterator/walker_grid.cpp
+++ b/src/gui/auxiliary/iterator/walker_grid.cpp
@@ -16,6 +16,8 @@
#include "gui/auxiliary/iterator/walker_grid.hpp"
+#include "global.hpp"
+
#include <cassert>
namespace gui2
diff --git a/src/gui/auxiliary/iterator/walker_tree_node.cpp b/src/gui/auxiliary/iterator/walker_tree_node.cpp
index dbc4d52c89a..df9eb283414 100644
--- a/src/gui/auxiliary/iterator/walker_tree_node.cpp
+++ b/src/gui/auxiliary/iterator/walker_tree_node.cpp
@@ -16,6 +16,8 @@
#include "gui/auxiliary/iterator/walker_tree_node.hpp"
+#include "global.hpp"
+
#include <cassert>
namespace gui2
diff --git a/src/gui/auxiliary/iterator/walker_widget.cpp b/src/gui/auxiliary/iterator/walker_widget.cpp
index d9ac06f2b13..858f40f2935 100644
--- a/src/gui/auxiliary/iterator/walker_widget.cpp
+++ b/src/gui/auxiliary/iterator/walker_widget.cpp
@@ -16,9 +16,11 @@
#include "gui/auxiliary/iterator/walker_widget.hpp"
-#include <cassert>
+#include "global.hpp"
#include "gui/widgets/widget.hpp"
+#include <cassert>
+
namespace gui2
{
diff --git a/src/gui/auxiliary/old_markup.cpp b/src/gui/auxiliary/old_markup.cpp
index de4eb2cdbea..b5a26521ea2 100644
--- a/src/gui/auxiliary/old_markup.cpp
+++ b/src/gui/auxiliary/old_markup.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2008 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/gui/auxiliary/old_markup.hpp b/src/gui/auxiliary/old_markup.hpp
index a8152186999..265222b1a58 100644
--- a/src/gui/auxiliary/old_markup.hpp
+++ b/src/gui/auxiliary/old_markup.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2008 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/gui/core/canvas.cpp b/src/gui/core/canvas.cpp
index 66365ce073b..9aee502a77c 100644
--- a/src/gui/core/canvas.cpp
+++ b/src/gui/core/canvas.cpp
@@ -1280,7 +1280,7 @@ void text_shape::draw(surface& canvas,
return;
}
- static font::pango_text text_renderer;
+ font::pango_text& text_renderer = font::get_text_renderer();
text_renderer
.set_link_aware(link_aware_(variables))
@@ -1370,13 +1370,11 @@ canvas::canvas(canvas&& c)
, w_(c.w_)
, h_(c.h_)
, canvas_(std::move(c.canvas_))
- , renderer_(c.renderer_)
+ , renderer_(std::exchange(c.renderer_, nullptr))
, variables_(c.variables_)
, functions_(c.functions_)
, is_dirty_(c.is_dirty_)
{
- // Needed to ensure the other object doesn't destroy our software renderer prematurely.
- c.renderer_ = nullptr;
}
canvas::~canvas()
@@ -1499,13 +1497,18 @@ void canvas::parse_cfg(const config& cfg)
void canvas::clear_shapes(const bool force)
{
- auto conditional = [force](const shape_ptr s)->bool { return !s->immutable() && !force; };
+ if(force) {
+ shapes_.clear();
+ drawn_shapes_.clear();
+ } else {
+ auto conditional = [](const shape_ptr s)->bool { return !s->immutable(); };
- auto iter = std::remove_if(shapes_.begin(), shapes_.end(), conditional);
- shapes_.erase(iter, shapes_.end());
+ auto iter = std::remove_if(shapes_.begin(), shapes_.end(), conditional);
+ shapes_.erase(iter, shapes_.end());
- iter = std::remove_if(drawn_shapes_.begin(), drawn_shapes_.end(), conditional);
- drawn_shapes_.erase(iter, drawn_shapes_.end());
+ iter = std::remove_if(drawn_shapes_.begin(), drawn_shapes_.end(), conditional);
+ drawn_shapes_.erase(iter, drawn_shapes_.end());
+ }
}
void canvas::invalidate_cache()
diff --git a/src/gui/core/event/dispatcher.cpp b/src/gui/core/event/dispatcher.cpp
index 493a46a41b7..67801ac1a0c 100644
--- a/src/gui/core/event/dispatcher.cpp
+++ b/src/gui/core/event/dispatcher.cpp
@@ -31,8 +31,6 @@ dispatcher::dispatcher()
, signal_queue_()
, signal_mouse_queue_()
, signal_keyboard_queue_()
- , signal_touch_motion_queue_()
- , signal_touch_gesture_queue_()
, signal_notification_queue_()
, signal_message_queue_()
, connected_(false)
@@ -66,12 +64,6 @@ bool dispatcher::has_event(const ui_event event, const event_queue_type event_ty
<< find<set_event_mouse>(event, dispatcher_implementation
::has_handler(event_type, *this))
<< " keyboard "
- << find<set_event_touch_motion>(event, dispatcher_implementation
- ::has_handler(event_type, *this))
- << " touch_motion "
- << find<set_event_touch_gesture>(event, dispatcher_implementation
- ::has_handler(event_type, *this))
- << " touch_gesture "
<< find<set_event_keyboard>(event, dispatcher_implementation
::has_handler(event_type, *this))
<< " notification "
@@ -91,9 +83,7 @@ bool dispatcher::has_event(const ui_event event, const event_queue_type event_ty
event, dispatcher_implementation::has_handler(event_type, *this))
|| find<set_event_text_input>(
event, dispatcher_implementation::has_handler(event_type, *this))
- || find<set_event_touch_motion>(
- event, dispatcher_implementation::has_handler(event_type, *this))
- || find<set_event_touch_gesture>(
+ || find<set_event_touch>(
event, dispatcher_implementation::has_handler(event_type, *this))
|| find<set_event_notification>(
event, dispatcher_implementation::has_handler(event_type, *this))
@@ -158,24 +148,12 @@ bool dispatcher::fire(const ui_event event,
widget& target,
const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode)
+ const std::string& unicode)
{
assert(find<set_event_keyboard>(event, event_in_set()));
return fire_event<signal_keyboard_function>(event, this, &target, key, modifier, unicode);
}
-bool dispatcher::fire(const ui_event event, widget& target, const point& pos, const point& distance)
-{
- assert(find<set_event_touch_motion>(event, event_in_set()));
- return fire_event<signal_touch_motion_function>(event, this, &target, pos, distance);
-}
-
-bool dispatcher::fire(const ui_event event, widget& target, const point& center, float dTheta, float dDist, Uint8 numFingers)
-{
- assert(find<set_event_touch_gesture>(event, event_in_set()));
- return fire_event<signal_touch_gesture_function>(event, this, &target, center, dTheta, dDist, numFingers);
-}
-
bool dispatcher::fire(const ui_event event, widget& target, const SDL_Event& sdlevent)
{
assert(find<set_event_raw_event>(event, event_in_set()));
@@ -188,14 +166,19 @@ bool dispatcher::fire(const ui_event event, widget& target, const std::string& t
return fire_event<signal_text_input_function>(event, this, &target, text, start, len);
}
+bool dispatcher::fire(const ui_event event, widget& target, const point& pos, const point& distance)
+{
+ assert(find<set_event_touch>(event, event_in_set()));
+ return fire_event<signal_touch_function>(event, this, &target, pos, distance);
+}
+
bool dispatcher::fire(const ui_event event, widget& target, void*)
{
assert(find<set_event_notification>(event, event_in_set()));
return fire_event<signal_notification_function>(event, this, &target, nullptr);
}
-// TODO: is there any reason msg isn't a const reference?
-bool dispatcher::fire(const ui_event event, widget& target, message& msg)
+bool dispatcher::fire(const ui_event event, widget& target, const message& msg)
{
assert(find<set_event_message>(event, event_in_set()));
return fire_event<signal_message_function>(event, this, &target, msg);
@@ -251,6 +234,12 @@ void connect_signal_notify_modified(dispatcher& dispatcher, const signal_notific
dispatcher.connect_signal<NOTIFY_MODIFIED>(signal);
}
+void connect_signal_on_draw(dispatcher& dispatcher, const signal_function& signal)
+{
+ // TODO: evaluate whether draw events need go in this queue position.
+ dispatcher.connect_signal<DRAW>(signal, dispatcher::front_child);
+}
+
} // namespace event
} // namespace gui2
diff --git a/src/gui/core/event/dispatcher.hpp b/src/gui/core/event/dispatcher.hpp
index 0f29cb78b9e..d5cc324966d 100644
--- a/src/gui/core/event/dispatcher.hpp
+++ b/src/gui/core/event/dispatcher.hpp
@@ -16,10 +16,8 @@
#include "gui/core/event/handler.hpp"
#include "hotkey/hotkey_command.hpp"
-#include "serialization/unicode_types.hpp"
#include "utils/functional.hpp"
-#include "utils/type_trait_aliases.hpp"
#include <SDL_events.h>
@@ -77,33 +75,19 @@ typedef std::function<void(widget& dispatcher,
bool& halt,
const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode)> signal_keyboard_function;
+ const std::string& unicode)> signal_keyboard_function;
/**
* Callback function signature.
*
- * This function is used for the callbacks in set_event_touch_motion.
+ * This function is used for the callbacks in set_event_touch.
*/
typedef std::function<void(widget& dispatcher,
const ui_event event,
bool& handled,
bool& halt,
const point& pos,
- const point& distance)> signal_touch_motion_function;
-
-/**
- * Callback function signature.
- *
- * This function is used for the callbacks in set_event_touch_gesture.
- */
-typedef std::function<void(dispatcher& dispatcher,
- const ui_event event,
- bool& handled,
- bool& halt,
- const point& center,
- float dTheta,
- float dDist,
- Uint8 numFingers)> signal_touch_gesture_function;
+ const point& distance)> signal_touch_function;
/**
* Callback function signature.
@@ -127,7 +111,7 @@ typedef std::function<void(widget& dispatcher,
const ui_event event,
bool& handled,
bool& halt,
- message& message)> signal_message_function;
+ const message& message)> signal_message_function;
/**
* Callback function signature.
@@ -239,10 +223,10 @@ public:
widget& target,
const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode);
+ const std::string& unicode);
/**
- * Fires an event which takes touch-motion parameters.
+ * Fires an event which takes touch parameters.
*
* @param event The event to fire.
* @param target The widget that should receive the event.
@@ -253,23 +237,6 @@ public:
widget& target,
const point& pos,
const point& distance);
-
-
- /**
- * Fires an event which takes touch-gesture parameters.
- *
- * @param event The event to fire.
- * @param target The widget that should receive the event.
- * @param pos The location touched.
- * @param distance The distance moved.
- */
- bool fire(const ui_event event,
- widget& target,
- const point& center,
- float dTheta,
- float dDist,
- Uint8 numFingers);
-
/**
* Fires an event which takes notification parameters.
@@ -296,7 +263,7 @@ public:
*/
bool fire(const ui_event event,
widget& target,
- message& msg);
+ const message& msg);
/**
* Fires an event that's a raw SDL event
@@ -389,7 +356,7 @@ public:
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event, E>::value>
+ std::enable_if_t<has_key<set_event, E>::value>
connect_signal(const signal_function& signal,
const queue_position position = back_child)
{
@@ -407,7 +374,7 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event, E>::value>
+ std::enable_if_t<has_key<set_event, E>::value>
disconnect_signal(const signal_function& signal,
const queue_position position = back_child)
{
@@ -422,7 +389,7 @@ public:
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_mouse, E>::value>
+ std::enable_if_t<has_key<set_event_mouse, E>::value>
connect_signal(const signal_mouse_function& signal,
const queue_position position = back_child)
{
@@ -440,7 +407,7 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_mouse, E>::value>
+ std::enable_if_t<has_key<set_event_mouse, E>::value>
disconnect_signal(const signal_mouse_function& signal,
const queue_position position = back_child)
{
@@ -455,7 +422,7 @@ public:
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_keyboard, E>::value>
+ std::enable_if_t<has_key<set_event_keyboard, E>::value>
connect_signal(const signal_keyboard_function& signal,
const queue_position position = back_child)
{
@@ -473,7 +440,7 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_keyboard, E>::value>
+ std::enable_if_t<has_key<set_event_keyboard, E>::value>
disconnect_signal(const signal_keyboard_function& signal,
const queue_position position = back_child)
{
@@ -481,51 +448,18 @@ public:
}
/**
- * Connect a signal for callback in set_event_touch_motion.
- *
- * @tparam E The event the callback needs to react to.
- * @param signal The callback function.
- * @param position The position to place the callback.
- */
- template <ui_event E>
- utils::enable_if_t<has_key<set_event_touch_motion, E>::value>
- connect_signal(const signal_touch_motion_function& signal,
- const queue_position position = back_child)
- {
- signal_touch_motion_queue_.connect_signal(E, position, signal);
- }
-
- /**
- * Disconnect a signal for callback in set_event_touch.
- *
- * @tparam E The event the callback was used for.
- * @param signal The callback function.
- * @param position The place where the function was added.
- * Needed remove the event from the right
- * place. (The function doesn't care whether
- * was added in front or back.)
- */
- template <ui_event E>
- utils::enable_if_t<has_key<set_event_touch_motion, E>::value>
- disconnect_signal(const signal_touch_motion_function& signal,
- const queue_position position = back_child)
- {
- signal_touch_motion_queue_.disconnect_signal(E, position, signal);
- }
-
- /**
- * Connect a signal for callback in set_event_touch_gesture.
+ * Connect a signal for callback in set_event_touch.
*
* @tparam E The event the callback needs to react to.
* @param signal The callback function.
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_touch_gesture, E>::value>
- connect_signal(const signal_touch_gesture_function& signal,
+ std::enable_if_t<has_key<set_event_touch, E>::value>
+ connect_signal(const signal_touch_function& signal,
const queue_position position = back_child)
{
- signal_touch_gesture_queue_.connect_signal(E, position, signal);
+ signal_touch_queue_.connect_signal(E, position, signal);
}
/**
@@ -539,11 +473,11 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_touch_gesture, E>::value>
- disconnect_signal(const signal_touch_gesture_function& signal,
+ std::enable_if_t<has_key<set_event_touch, E>::value>
+ disconnect_signal(const signal_touch_function& signal,
const queue_position position = back_child)
{
- signal_touch_gesture_queue_.disconnect_signal(E, position, signal);
+ signal_touch_queue_.disconnect_signal(E, position, signal);
}
/**
@@ -557,7 +491,7 @@ public:
* and shouldn't be used.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_notification, E>::value>
+ std::enable_if_t<has_key<set_event_notification, E>::value>
connect_signal(const signal_notification_function& signal,
const queue_position position = back_child)
{
@@ -580,7 +514,7 @@ public:
* front_pre_child)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_notification, E>::value>
+ std::enable_if_t<has_key<set_event_notification, E>::value>
disconnect_signal(const signal_notification_function& signal,
const queue_position position = back_child)
{
@@ -598,7 +532,7 @@ public:
* and shouldn't be used.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_message, E>::value>
+ std::enable_if_t<has_key<set_event_message, E>::value>
connect_signal(const signal_message_function& signal,
const queue_position position = back_child)
{
@@ -621,7 +555,7 @@ public:
* front_pre_child)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_message, E>::value>
+ std::enable_if_t<has_key<set_event_message, E>::value>
disconnect_signal(const signal_message_function& signal,
const queue_position position = back_child)
{
@@ -636,7 +570,7 @@ public:
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_raw_event, E>::value>
+ std::enable_if_t<has_key<set_event_raw_event, E>::value>
connect_signal(const signal_raw_event_function& signal,
const queue_position position = back_child)
{
@@ -654,7 +588,7 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_raw_event, E>::value>
+ std::enable_if_t<has_key<set_event_raw_event, E>::value>
disconnect_signal(const signal_raw_event_function& signal,
const queue_position position = back_child)
{
@@ -669,7 +603,7 @@ public:
* @param position The position to place the callback.
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_text_input, E>::value>
+ std::enable_if_t<has_key<set_event_text_input, E>::value>
connect_signal(const signal_text_input_function& signal,
const queue_position position = back_child)
{
@@ -687,7 +621,7 @@ public:
* was added in front or back.)
*/
template <ui_event E>
- utils::enable_if_t<has_key<set_event_text_input, E>::value>
+ std::enable_if_t<has_key<set_event_text_input, E>::value>
disconnect_signal(const signal_text_input_function& signal,
const queue_position position = back_child)
{
@@ -890,10 +824,7 @@ private:
signal_queue<signal_keyboard_function> signal_keyboard_queue_;
/** Signal queue for callbacks in set_event_touch. */
- signal_queue<signal_touch_motion_function> signal_touch_motion_queue_;
-
- /** Signal queue for callbacks in set_event_touch. */
- signal_queue<signal_touch_gesture_function> signal_touch_gesture_queue_;
+ signal_queue<signal_touch_function> signal_touch_queue_;
/** Signal queue for callbacks in set_event_notification. */
signal_queue<signal_notification_function> signal_notification_queue_;
@@ -949,6 +880,9 @@ void connect_signal_mouse_left_double_click(dispatcher& dispatcher, const signal
/** Connects a signal handler for getting a notification upon modification. */
void connect_signal_notify_modified(dispatcher& dispatcher, const signal_notification_function& signal);
+/** Connects a signal handler for a callback when the widget is drawn. */
+void connect_signal_on_draw(dispatcher& dispatcher, const signal_function& signal);
+
} // namespace event
} // namespace gui2
diff --git a/src/gui/core/event/dispatcher_private.hpp b/src/gui/core/event/dispatcher_private.hpp
index 641cf7ecce8..34c38efc70d 100644
--- a/src/gui/core/event/dispatcher_private.hpp
+++ b/src/gui/core/event/dispatcher_private.hpp
@@ -17,7 +17,6 @@
#include "gui/core/event/dispatcher.hpp"
#include "gui/widgets/widget.hpp"
-#include "utils/type_trait_aliases.hpp"
#include <SDL_events.h>
@@ -61,7 +60,7 @@ struct dispatcher_implementation
* dispatcher::signal_type<FUNCTION> \
*/ \
template<typename F> \
- static utils::enable_if_t<std::is_same<F, FUNCTION>::value, dispatcher::signal_type<FUNCTION>>& \
+ static std::enable_if_t<std::is_same<F, FUNCTION>::value, dispatcher::signal_type<FUNCTION>>& \
event_signal(dispatcher& dispatcher, const ui_event event) \
{ \
return dispatcher.QUEUE.queue[event]; \
@@ -81,7 +80,7 @@ struct dispatcher_implementation
* dispatcher::signal_type<FUNCTION> \
*/ \
template<typename K> \
- static utils::enable_if_t<boost::mpl::has_key<SET, K>::value, dispatcher::signal_type<FUNCTION>>& \
+ static std::enable_if_t<boost::mpl::has_key<SET, K>::value, dispatcher::signal_type<FUNCTION>>& \
event_signal(dispatcher& dispatcher, const ui_event event) \
{ \
return dispatcher.QUEUE.queue[event]; \
@@ -106,8 +105,7 @@ struct dispatcher_implementation
IMPLEMENT_EVENT_SIGNAL_WRAPPER(mouse)
IMPLEMENT_EVENT_SIGNAL_WRAPPER(keyboard)
- IMPLEMENT_EVENT_SIGNAL_WRAPPER(touch_motion)
- IMPLEMENT_EVENT_SIGNAL_WRAPPER(touch_gesture)
+ IMPLEMENT_EVENT_SIGNAL_WRAPPER(touch)
IMPLEMENT_EVENT_SIGNAL_WRAPPER(notification)
IMPLEMENT_EVENT_SIGNAL_WRAPPER(message)
IMPLEMENT_EVENT_SIGNAL_WRAPPER(raw_event)
@@ -408,8 +406,7 @@ inline bool fire_event(const ui_event event,
/***** ***** ***** Pre ***** ***** *****/
for(auto& ritor_widget : boost::adaptors::reverse(event_chain)) {
- dispatcher::signal_type<T>& signal =
- dispatcher_implementation::event_signal<T>(*ritor_widget.first, ritor_widget.second);
+ auto& signal = dispatcher_implementation::event_signal<T>(*ritor_widget.first, ritor_widget.second);
for(auto& pre_func : signal.pre_child) {
pre_func(*dispatcher, ritor_widget.second, handled, halt, std::forward<F>(params)...);
@@ -427,8 +424,7 @@ inline bool fire_event(const ui_event event,
/***** ***** ***** Child ***** ***** *****/
if(w->has_event(event, dispatcher::child)) {
- dispatcher::signal_type<T>& signal =
- dispatcher_implementation::event_signal<T>(*w, event);
+ auto& signal = dispatcher_implementation::event_signal<T>(*w, event);
for(auto& func : signal.child) {
func(*dispatcher, event, handled, halt, std::forward<F>(params)...);
@@ -446,8 +442,7 @@ inline bool fire_event(const ui_event event,
/***** ***** ***** Post ***** ***** *****/
for(auto& itor_widget : event_chain) {
- dispatcher::signal_type<T>& signal =
- dispatcher_implementation::event_signal<T>(*itor_widget.first, itor_widget.second);
+ auto& signal = dispatcher_implementation::event_signal<T>(*itor_widget.first, itor_widget.second);
for(auto& post_func : signal.post_child) {
post_func(*dispatcher, itor_widget.second, handled, halt, std::forward<F>(params)...);
diff --git a/src/gui/core/event/distributor.cpp b/src/gui/core/event/distributor.cpp
index 5439398ed0f..d8fd5591c12 100644
--- a/src/gui/core/event/distributor.cpp
+++ b/src/gui/core/event/distributor.cpp
@@ -125,15 +125,6 @@ mouse_motion::mouse_motion(widget& owner,
_5),
queue_position);
- owner.connect_signal<event::SDL_TOUCH_MOTION>(
- std::bind(&mouse_motion::signal_handler_sdl_touch_motion,
- this,
- _2,
- _3,
- _5,
- _6),
- queue_position);
-
owner_.connect_signal<event::SDL_WHEEL_UP>(std::bind(
&mouse_motion::signal_handler_sdl_wheel, this, _2, _3, _5));
owner_.connect_signal<event::SDL_WHEEL_DOWN>(std::bind(
@@ -208,25 +199,6 @@ void mouse_motion::signal_handler_sdl_mouse_motion(const event::ui_event event,
handled = true;
}
-void mouse_motion::signal_handler_sdl_touch_motion(const event::ui_event event,
- bool& handled,
- const point& coordinate,
- const point& distance)
-{
- DBG_GUI_E << LOG_HEADER << event << ".\n";
-
- if(mouse_captured_) {
- assert(mouse_focus_);
- owner_.fire(event, *mouse_focus_, coordinate, distance);
- } else {
- widget* mouse_over = owner_.find_at(coordinate, true);
- if(mouse_over) {
- owner_.fire(event, *mouse_over, coordinate, distance);
- }
- }
- handled = true;
-}
-
void mouse_motion::signal_handler_sdl_wheel(const event::ui_event event,
bool& handled,
const point& coordinate)
@@ -344,14 +316,6 @@ void mouse_motion::mouse_leave()
void mouse_motion::start_hover_timer(widget* widget, const point& coordinate)
{
assert(widget);
-
-#ifdef __IPHONEOS__
- // Guessing a crash location in a nasty stack in gui2::execute_timer.
- // Either this or a long-touch menu.
- // Remove this when the crash in gui2::execute_timer() and gui2::timer_callback() is gone and try again.
- return;
-#endif
-
stop_hover_timer();
if(hover_shown_ || !widget->wants_mouse_hover()) {
@@ -744,17 +708,17 @@ void distributor::signal_handler_keyboard_internal(event::ui_event evt, P1&& p1,
}
}
-void distributor::signal_handler_sdl_key_down(const SDL_Keycode key, const SDL_Keymod modifier, const utf8::string& unicode)
+void distributor::signal_handler_sdl_key_down(const SDL_Keycode key, const SDL_Keymod modifier, const std::string& unicode)
{
signal_handler_keyboard_internal<signal_keyboard_function>(event::SDL_KEY_DOWN, key, modifier, unicode);
}
-void distributor::signal_handler_sdl_text_input(const utf8::string& unicode, int32_t start, int32_t end)
+void distributor::signal_handler_sdl_text_input(const std::string& unicode, int32_t start, int32_t end)
{
signal_handler_keyboard_internal<signal_text_input_function>(event::SDL_TEXT_INPUT, unicode, start, end);
}
-void distributor::signal_handler_sdl_text_editing(const utf8::string& unicode, int32_t start, int32_t end)
+void distributor::signal_handler_sdl_text_editing(const std::string& unicode, int32_t start, int32_t end)
{
signal_handler_keyboard_internal<signal_text_input_function>(event::SDL_TEXT_EDITING, unicode, start, end);
}
diff --git a/src/gui/core/event/distributor.hpp b/src/gui/core/event/distributor.hpp
index 5b06a76ff3e..e9ea46d152e 100644
--- a/src/gui/core/event/distributor.hpp
+++ b/src/gui/core/event/distributor.hpp
@@ -40,7 +40,6 @@
#include "gui/core/event/dispatcher.hpp"
#include "gui/core/event/handler.hpp"
#include "sdl/point.hpp"
-#include "serialization/unicode_types.hpp"
#include "video.hpp"
#include <string>
@@ -139,11 +138,6 @@ private:
bool& handled,
const point& coordinate);
- void signal_handler_sdl_touch_motion(const event::ui_event event,
- bool& handled,
- const point& coordinate,
- const point& distance);
-
void signal_handler_sdl_wheel(const event::ui_event event,
bool& handled,
const point& coordinate);
@@ -359,10 +353,10 @@ private:
void signal_handler_sdl_key_down(const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode);
+ const std::string& unicode);
- void signal_handler_sdl_text_input(const utf8::string& unicode, int32_t start, int32_t len);
- void signal_handler_sdl_text_editing(const utf8::string& unicode, int32_t start, int32_t len);
+ void signal_handler_sdl_text_input(const std::string& unicode, int32_t start, int32_t len);
+ void signal_handler_sdl_text_editing(const std::string& unicode, int32_t start, int32_t len);
template<typename Fcn, typename P1, typename P2, typename P3>
void signal_handler_keyboard_internal(event::ui_event evt, P1&& p1, P2&& p2, P3&& p3);
diff --git a/src/gui/core/event/handler.cpp b/src/gui/core/event/handler.cpp
index 72b8bf24759..58f5100ed3b 100644
--- a/src/gui/core/event/handler.cpp
+++ b/src/gui/core/event/handler.cpp
@@ -224,35 +224,12 @@ private:
dispatcher* keyboard_dispatcher();
/**
- * Fires a touch-moved event.
+ * Fires a generic touch event.
*
* @param position The position touched.
* @param distance The distance moved.
*/
void touch_motion(const point& position, const point& distance);
-
- /**
- * Fires a touch "finger down" event.
- *
- * @param position The position touched.
- */
- void touch_down(const point& position);
-
- /**
- * Fires a touch "finger up" event.
- *
- * @param position The position touched.
- */
- void touch_up(const point& position);
-
- /**
- * Fires a touch gesture event.
- * @param center the center of gesture
- * @param dTheta the amount that the fingers rotated during this motion
- * @param dDist the amount that the fingers pinched during this motion
- * @param numFingers the number of fingers used in the gesture
- */
- void touch_multi_gesture(const point& center, float dTheta, float dDist, Uint8 numFingers);
/**
* Handles a hat motion event.
@@ -295,7 +272,7 @@ private:
*/
void key_down(const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode);
+ const std::string& unicode);
/**
* Fires a text input event.
@@ -379,30 +356,17 @@ void sdl_event_handler::handle_event(const SDL_Event& event)
return;
}
- Uint8 button = event.button.button;
- CVideo& video = dynamic_cast<window&>(*dispatchers_.back()).video();
-
switch(event.type) {
case SDL_MOUSEMOTION:
-#ifdef MOUSE_TOUCH_EMULATION
- // There's no finger motion when it's not down.
- if (event.motion.state != 0)
-#endif
- {
- mouse(SDL_MOUSE_MOTION, {event.motion.x, event.motion.y});
- }
+ mouse(SDL_MOUSE_MOTION, {event.motion.x, event.motion.y});
break;
case SDL_MOUSEBUTTONDOWN:
- {
- mouse_button_down({event.button.x, event.button.y}, button);
- }
+ mouse_button_down({event.button.x, event.button.y}, event.button.button);
break;
case SDL_MOUSEBUTTONUP:
- {
- mouse_button_up({event.button.x, event.button.y}, button);
- }
+ mouse_button_up({event.button.x, event.button.y}, event.button.button);
break;
case SDL_MOUSEWHEEL:
@@ -478,33 +442,7 @@ void sdl_event_handler::handle_event(const SDL_Event& event)
break;
case SDL_FINGERMOTION:
- {
- SDL_Rect r = video.screen_area();
- touch_motion(point(event.tfinger.x * r.w, event.tfinger.y * r.h),
- point(event.tfinger.dx * r.w, event.tfinger.dy * r.h));
- }
- break;
-
- case SDL_FINGERUP:
- {
- SDL_Rect r = video.screen_area();
- touch_up(point(event.tfinger.x * r.w, event.tfinger.y * r.h));
- }
- break;
-
- case SDL_FINGERDOWN:
- {
- SDL_Rect r = video.screen_area();
- touch_down(point(event.tfinger.x * r.w, event.tfinger.y * r.h));
- }
- break;
-
- case SDL_MULTIGESTURE:
- {
- SDL_Rect r = video.screen_area();
- touch_multi_gesture(point(event.mgesture.x * r.w, event.mgesture.y * r.h),
- event.mgesture.dTheta, event.mgesture.dDist, event.mgesture.numFingers);
- }
+ touch_motion(point(event.tfinger.x, event.tfinger.y), point(event.tfinger.dx, event.tfinger.dy));
break;
#if(defined(_X11) && !defined(__APPLE__)) || defined(_WIN32)
@@ -516,6 +454,8 @@ void sdl_event_handler::handle_event(const SDL_Event& event)
// Silently ignored events.
case SDL_KEYUP:
case DOUBLE_CLICK_EVENT:
+ case SDL_FINGERUP:
+ case SDL_FINGERDOWN:
break;
default:
@@ -737,27 +677,6 @@ void sdl_event_handler::touch_motion(const point& position, const point& distanc
}
}
-void sdl_event_handler::touch_up(const point& position)
-{
- for(auto& dispatcher : boost::adaptors::reverse(dispatchers_)) {
- dispatcher->fire(SDL_TOUCH_UP, dynamic_cast<widget&>(*dispatcher), position);
- }
-}
-
-void sdl_event_handler::touch_down(const point& position)
-{
- for(auto& dispatcher : boost::adaptors::reverse(dispatchers_)) {
- dispatcher->fire(SDL_TOUCH_DOWN, dynamic_cast<widget&>(*dispatcher), position);
- }
-}
-
-void sdl_event_handler::touch_multi_gesture(const point& center, float dTheta, float dDist, Uint8 numFingers)
-{
- for(auto& dispatcher : boost::adaptors::reverse(dispatchers_)) {
- dispatcher->fire(SDL_TOUCH_MULTI_GESTURE, dynamic_cast<widget&>(*dispatcher), center, dTheta, dDist, numFingers);
- }
-}
-
void sdl_event_handler::hat_motion(const SDL_Event& event)
{
const hotkey::hotkey_ptr& hk = hotkey::get_hotkey(event);
@@ -831,7 +750,7 @@ bool sdl_event_handler::hotkey_pressed(const hotkey::hotkey_ptr key)
void sdl_event_handler::key_down(const SDL_Keycode key,
const SDL_Keymod modifier,
- const utf8::string& unicode)
+ const std::string& unicode)
{
DBG_GUI_E << "Firing: " << SDL_KEY_DOWN << ".\n";
@@ -1090,9 +1009,6 @@ std::ostream& operator<<(std::ostream& stream, const ui_event event)
case SDL_TOUCH_DOWN:
stream << "SDL touch down";
break;
- case SDL_TOUCH_MULTI_GESTURE:
- stream << "SDL multi-touch gesture";
- break;
case SDL_RAW_EVENT:
stream << "SDL raw event";
break;
diff --git a/src/gui/core/event/handler.hpp b/src/gui/core/event/handler.hpp
index a9bc8ec4210..59a71e7c3cf 100644
--- a/src/gui/core/event/handler.hpp
+++ b/src/gui/core/event/handler.hpp
@@ -116,7 +116,6 @@ enum ui_event {
SDL_TOUCH_MOTION,
SDL_TOUCH_UP,
SDL_TOUCH_DOWN,
- SDL_TOUCH_MULTI_GESTURE,
SDL_RAW_EVENT /**< Raw SDL event. */
};
@@ -169,9 +168,7 @@ typedef boost::mpl::set<boost::mpl::int_<SDL_VIDEO_RESIZE>,
boost::mpl::int_<SDL_WHEEL_UP>,
boost::mpl::int_<SDL_WHEEL_DOWN>,
boost::mpl::int_<SDL_WHEEL_LEFT>,
- boost::mpl::int_<SDL_WHEEL_RIGHT>,
- boost::mpl::int_<SDL_TOUCH_UP>,
- boost::mpl::int_<SDL_TOUCH_DOWN>> set_event_mouse;
+ boost::mpl::int_<SDL_WHEEL_RIGHT>> set_event_mouse;
/**
* Helper for catching use error of dispatcher::connect_signal.
@@ -184,18 +181,12 @@ typedef boost::mpl::set<boost::mpl::int_<SDL_KEY_DOWN>> set_event_keyboard;
/**
* Helper for catching use error of dispatcher::connect_signal.
*
- * This version is for callbacks of touch motion events.
+ * This version is for callbacks of touch events.
*/
-typedef boost::mpl::set<boost::mpl::int_<SDL_TOUCH_MOTION>>
-set_event_touch_motion;
-
-/**
- * Helper for catching use error of dispatcher::connect_signal.
- *
- * This version is for callbacks of touch gestures events.
- */
-typedef boost::mpl::set<boost::mpl::int_<SDL_TOUCH_MULTI_GESTURE>>
-set_event_touch_gesture;
+typedef boost::mpl::set<boost::mpl::int_<SDL_TOUCH_MOTION>,
+ boost::mpl::int_<SDL_TOUCH_UP>,
+ boost::mpl::int_<SDL_TOUCH_DOWN>>
+set_event_touch;
/**
* Helper for catching use error of dispatcher::connect_signal.
diff --git a/src/gui/core/event/message.hpp b/src/gui/core/event/message.hpp
index 32b99f70adb..c70754b71e2 100644
--- a/src/gui/core/event/message.hpp
+++ b/src/gui/core/event/message.hpp
@@ -22,7 +22,8 @@
#pragma once
#include "gui/widgets/helper.hpp"
-#include "sdl/point.hpp"
+
+#include <SDL_rect.h>
namespace gui2
{
diff --git a/src/gui/core/gui_definition.cpp b/src/gui/core/gui_definition.cpp
index d98bc0247d3..5376120039b 100644
--- a/src/gui/core/gui_definition.cpp
+++ b/src/gui/core/gui_definition.cpp
@@ -204,14 +204,7 @@ resolution_definition_ptr get_control(const std::string& control_type, const std
const auto& current_types = current_gui->second.widget_types;
const auto& default_types = default_gui->second.widget_types;
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- const auto widget_definitions = (control_type == "list")
- ? current_types.find("listbox")
- : current_types.find(control_type);
-#else
- const auto widget_definitions
- = current_types.find(control_type);
-#endif
+ const auto widget_definitions = current_types.find(control_type);
gui_definition::widget_definition_map_t::const_iterator control;
@@ -226,14 +219,7 @@ resolution_definition_ptr get_control(const std::string& control_type, const std
bool found_fallback = false;
if(current_gui != default_gui) {
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- auto default_widget_definitions = (control_type == "list")
- ? default_types.find("listbox")
- : default_types.find(control_type);
-#else
- auto default_widget_definitions
- = default_types.find(control_type);
-#endif
+ auto default_widget_definitions = default_types.find(control_type);
VALIDATE(widget_definitions != current_types.end(),
formatter() << "Type '" << control_type << "' is unknown.");
diff --git a/src/gui/core/timer.cpp b/src/gui/core/timer.cpp
index 1a6dc2f60f6..011d015cbff 100644
--- a/src/gui/core/timer.cpp
+++ b/src/gui/core/timer.cpp
@@ -20,7 +20,6 @@
#include <SDL_timer.h>
#include <map>
-#include <mutex>
namespace gui2
{
@@ -54,8 +53,6 @@ static std::map<size_t, timer>& get_timers()
*/
static size_t executing_id = 0;
-std::mutex timers_mutex;
-
/** Did somebody try to remove the timer during its execution? */
static bool executing_id_removed = false;
@@ -96,18 +93,11 @@ extern "C" {
static uint32_t timer_callback(uint32_t, void* id)
{
DBG_GUI_E << "Pushing timer event in queue.\n";
- // iTunes still reports a couple of crashes here. Cannot see a problem yet.
-
- Uint32 result;
- {
- std::lock_guard<std::mutex> lock(timers_mutex);
- std::map<size_t, timer>::iterator itor
- = get_timers().find(reinterpret_cast<size_t>(id));
- if(itor == get_timers().end()) {
- return 0;
- }
- result = itor->second.interval;
+ std::map<size_t, timer>::iterator itor
+ = get_timers().find(reinterpret_cast<size_t>(id));
+ if(itor == get_timers().end()) {
+ return 0;
}
SDL_Event event;
@@ -119,7 +109,7 @@ static uint32_t timer_callback(uint32_t, void* id)
SDL_PushEvent(&event);
- return result;
+ return itor->second.interval;
}
} // extern "C"
@@ -132,18 +122,13 @@ size_t add_timer(const uint32_t interval,
DBG_GUI_E << "Adding timer.\n";
- timer timer;
- {
- std::lock_guard<std::mutex> lock(timers_mutex);
-
- do {
- ++next_timer_id;
- } while(next_timer_id == 0 || get_timers().count(next_timer_id) > 0);
-
- timer.sdl_id = SDL_AddTimer(
- interval, timer_callback, reinterpret_cast<void*>(next_timer_id));
- }
+ do {
+ ++next_timer_id;
+ } while(next_timer_id == 0 || get_timers().find(next_timer_id) != get_timers().end());
+ timer timer;
+ timer.sdl_id = SDL_AddTimer(
+ interval, timer_callback, reinterpret_cast<void*>(next_timer_id));
if(timer.sdl_id == 0) {
WRN_GUI_E << "Failed to create an sdl timer." << std::endl;
return 0;
@@ -155,11 +140,7 @@ size_t add_timer(const uint32_t interval,
timer.callback = callback;
- {
- std::lock_guard<std::mutex> lock(timers_mutex);
-
- get_timers().emplace(next_timer_id, timer);
- }
+ get_timers().emplace(next_timer_id, timer);
DBG_GUI_E << "Added timer " << next_timer_id << ".\n";
return next_timer_id;
@@ -169,8 +150,6 @@ bool remove_timer(const size_t id)
{
DBG_GUI_E << "Removing timer " << id << ".\n";
- std::lock_guard<std::mutex> lock(timers_mutex);
-
std::map<size_t, timer>::iterator itor = get_timers().find(id);
if(itor == get_timers().end()) {
LOG_GUI_E << "Can't remove timer since it no longer exists.\n";
@@ -202,25 +181,20 @@ bool execute_timer(const size_t id)
{
DBG_GUI_E << "Executing timer " << id << ".\n";
- std::function<void(size_t)> callback = nullptr;
- {
- std::lock_guard<std::mutex> lock(timers_mutex);
-
- std::map<size_t, timer>::iterator itor = get_timers().find(id);
- if(itor == get_timers().end()) {
- LOG_GUI_E << "Can't execute timer since it no longer exists.\n";
- return false;
- }
-
- callback = itor->second.callback;
-
- if(itor->second.interval == 0) {
- get_timers().erase(itor);
- }
+ std::map<size_t, timer>::iterator itor = get_timers().find(id);
+ if(itor == get_timers().end()) {
+ LOG_GUI_E << "Can't execute timer since it no longer exists.\n";
+ return false;
}
- callback(id);
+ {
+ executor executor(id);
+ itor->second.callback(id);
+ }
+ if(!executing_id_removed && itor->second.interval == 0) {
+ get_timers().erase(itor);
+ }
return true;
}
diff --git a/src/gui/core/window_builder.hpp b/src/gui/core/window_builder.hpp
index 0dc6bb75aa2..8ea819c92a1 100644
--- a/src/gui/core/window_builder.hpp
+++ b/src/gui/core/window_builder.hpp
@@ -99,13 +99,12 @@ widget* build_single_widget_instance_helper(const std::string& type, const confi
* @tparam T The final widget type. The widget pointer will be
* cast to this.
*
- * @param type String ID of the widget type.
* @param cfg Data config to pass to the widget's builder.
*/
template<typename T>
-T* build_single_widget_instance(const std::string& type, const config& cfg = config())
+T* build_single_widget_instance(const config& cfg = config())
{
- return dynamic_cast<T*>(build_single_widget_instance_helper(type, cfg));
+ return dynamic_cast<T*>(build_single_widget_instance_helper(T::type(), cfg));
}
struct builder_grid : public builder_widget
diff --git a/src/gui/dialogs/addon/manager.cpp b/src/gui/dialogs/addon/manager.cpp
index 9344bafaa60..0661619af22 100644
--- a/src/gui/dialogs/addon/manager.cpp
+++ b/src/gui/dialogs/addon/manager.cpp
@@ -36,11 +36,7 @@
#include "gui/widgets/stacked_widget.hpp"
#include "gui/widgets/drawing.hpp"
#include "gui/widgets/image.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/pane.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/toggle_button.hpp"
@@ -60,7 +56,6 @@
#include <iomanip>
#include <sstream>
#include <stdexcept>
-#include "utils/io.hpp"
namespace gui2
{
@@ -849,7 +844,7 @@ static std::string format_addon_time(time_t time)
? "%Y-%m-%d %I:%M %p"
: "%Y-%m-%d %H:%M";
- ss << utils::put_time(std::localtime(&time), format);
+ ss << std::put_time(std::localtime(&time), format);
return ss.str();
}
diff --git a/src/gui/dialogs/addon/uninstall_list.cpp b/src/gui/dialogs/addon/uninstall_list.cpp
index 0b83d5a585d..893a8908780 100644
--- a/src/gui/dialogs/addon/uninstall_list.cpp
+++ b/src/gui/dialogs/addon/uninstall_list.cpp
@@ -16,11 +16,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/grid.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/toggle_button.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/advanced_graphics_options.cpp b/src/gui/dialogs/advanced_graphics_options.cpp
index 4465b1ff3e5..fbfeaa8f568 100644
--- a/src/gui/dialogs/advanced_graphics_options.cpp
+++ b/src/gui/dialogs/advanced_graphics_options.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2014 - 2018 by Chris Beck <render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/gui/dialogs/advanced_graphics_options.hpp b/src/gui/dialogs/advanced_graphics_options.hpp
index b0ebeefd4c1..62b538d155e 100644
--- a/src/gui/dialogs/advanced_graphics_options.hpp
+++ b/src/gui/dialogs/advanced_graphics_options.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2012 - 2018 by Chris Beck <render787@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/gui/dialogs/attack_predictions.cpp b/src/gui/dialogs/attack_predictions.cpp
index 7f658bd22d7..bd3dc31af25 100644
--- a/src/gui/dialogs/attack_predictions.cpp
+++ b/src/gui/dialogs/attack_predictions.cpp
@@ -126,8 +126,13 @@ void attack_predictions::set_data(window& window, const combatant_data& attacker
ss.str("");
// Set specials context (for safety, it should not have changed normally).
- const_attack_ptr weapon = attacker.stats_.weapon;
- auto ctx = weapon->specials_context(&attacker.unit_, &defender.unit_, attacker.unit_.get_location(), defender.unit_.get_location(), attacker.stats_.is_attacker, defender.stats_.weapon);
+ const_attack_ptr weapon = attacker.stats_.weapon, opp_weapon = defender.stats_.weapon;
+ auto ctx = weapon->specials_context(&attacker.unit_, &defender.unit_, attacker.unit_.get_location(), defender.unit_.get_location(), attacker.stats_.is_attacker, opp_weapon);
+ boost::optional<decltype(ctx)> opp_ctx;
+
+ if(opp_weapon) {
+ opp_ctx.emplace(opp_weapon->specials_context(&defender.unit_, &attacker.unit_, defender.unit_.get_location(), attacker.unit_.get_location(), defender.stats_.is_attacker, weapon));
+ }
// Get damage modifiers.
unit_ability_list dmg_specials = weapon->get_specials("damage");
@@ -182,7 +187,7 @@ void attack_predictions::set_data(window& window, const combatant_data& attacker
ss.str("");
// Resistance modifier.
- const int resistance_modifier = defender.unit_.damage_from(*weapon, !attacker.stats_.is_attacker, defender.unit_.get_location());
+ const int resistance_modifier = defender.unit_.damage_from(*weapon, !attacker.stats_.is_attacker, defender.unit_.get_location(), opp_weapon);
if(resistance_modifier != 100) {
if(attacker.stats_.is_attacker) {
ss << _("Defender resistance vs") << " ";
@@ -217,7 +222,7 @@ void attack_predictions::set_data(window& window, const combatant_data& attacker
}
// Leadership bonus.
- const int leadership_bonus = under_leadership(resources::gameboard->units(), attacker.unit_.get_location()).first;
+ const int leadership_bonus = under_leadership(resources::gameboard->units(), attacker.unit_.get_location(), weapon, opp_weapon).first;
if(leadership_bonus != 0) {
set_label_helper("leadership_modifier", utils::signed_percent(leadership_bonus));
diff --git a/src/gui/dialogs/campaign_difficulty.cpp b/src/gui/dialogs/campaign_difficulty.cpp
index 1cccb214dfa..08fdad042b5 100644
--- a/src/gui/dialogs/campaign_difficulty.cpp
+++ b/src/gui/dialogs/campaign_difficulty.cpp
@@ -22,11 +22,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/auxiliary/old_markup.hpp"
#include "preferences/game.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/window.hpp"
#include "log.hpp"
#include "serialization/string_utils.hpp"
@@ -136,16 +132,16 @@ void campaign_difficulty::pre_show(window& window)
item["use_markup"] = "true";
std::ostringstream ss;
- ss << d["label"] << "\n<small>";
-
- if(d["old_markup"].to_bool() || d["description"].empty()) {
- ss << d["description"];
- } else {
- ss << font::span_color(font::GRAY_COLOR) << "(" << d["description"].str() << ")</span>";
+ ss << d["label"];
+
+ if(!d["description"].empty()) {
+ if (!d["old_markup"].to_bool()) {
+ ss << "\n<small>" << font::span_color(font::GRAY_COLOR) << "(" << d["description"].str() << ")</span></small>";
+ } else {
+ ss << "\n<small>" << font::span_color(font::GRAY_COLOR) << d["description"] << "</span></small>";
+ }
}
- ss << "</small>";
-
item["label"] = ss.str();
data.emplace("label", item);
diff --git a/src/gui/dialogs/campaign_selection.cpp b/src/gui/dialogs/campaign_selection.cpp
index cc49059d6e7..9971f6bd599 100644
--- a/src/gui/dialogs/campaign_selection.cpp
+++ b/src/gui/dialogs/campaign_selection.cpp
@@ -19,11 +19,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/multi_page.hpp"
#include "gui/widgets/multimenu_button.hpp"
#include "gui/widgets/scroll_label.hpp"
diff --git a/src/gui/dialogs/chat_log.cpp b/src/gui/dialogs/chat_log.cpp
index 9c735d0aad3..3f747470a25 100644
--- a/src/gui/dialogs/chat_log.cpp
+++ b/src/gui/dialogs/chat_log.cpp
@@ -18,11 +18,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/core_selection.cpp b/src/gui/dialogs/core_selection.cpp
index 218b484a82a..38f228a7461 100644
--- a/src/gui/dialogs/core_selection.cpp
+++ b/src/gui/dialogs/core_selection.cpp
@@ -18,11 +18,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/image.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/multi_page.hpp"
#include "gui/widgets/scroll_label.hpp"
#include "gui/widgets/settings.hpp"
diff --git a/src/gui/dialogs/debug_clock.cpp b/src/gui/dialogs/debug_clock.cpp
index 804ec59b0a1..68e29d5c93d 100644
--- a/src/gui/dialogs/debug_clock.cpp
+++ b/src/gui/dialogs/debug_clock.cpp
@@ -104,8 +104,7 @@ void debug_clock::pre_show(window& window)
clock_ = find_widget<styled_widget>(&window, "clock", false, false);
signal_ = std::bind(&debug_clock::update_time, this, false);
- window.connect_signal<event::DRAW>(signal_,
- event::dispatcher::front_child);
+ connect_signal_on_draw(window, signal_);
time_.set_current_time();
update_time(true);
@@ -175,7 +174,7 @@ debug_clock::time::time() : hour(0), minute(0), second(0), millisecond(0)
void debug_clock::time::set_current_time()
{
time_t now = ::time(nullptr);
- tm* stamp = localtime(&now);
+ std::tm* stamp = std::localtime(&now);
hour = stamp->tm_hour;
minute = stamp->tm_min;
diff --git a/src/gui/dialogs/depcheck_select_new.cpp b/src/gui/dialogs/depcheck_select_new.cpp
index c8948fa150c..c3988dd48a0 100644
--- a/src/gui/dialogs/depcheck_select_new.cpp
+++ b/src/gui/dialogs/depcheck_select_new.cpp
@@ -19,11 +19,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gettext.hpp"
namespace gui2
diff --git a/src/gui/dialogs/drop_down_menu.cpp b/src/gui/dialogs/drop_down_menu.cpp
index 37a5320d6f8..a2f2b60046c 100644
--- a/src/gui/dialogs/drop_down_menu.cpp
+++ b/src/gui/dialogs/drop_down_menu.cpp
@@ -33,17 +33,58 @@ namespace gui2
{
namespace dialogs
{
-
REGISTER_DIALOG(drop_down_menu)
namespace
{
+ void click_callback(window& window, bool keep_open, const point& coordinate)
+ {
+ listbox& list = find_widget<listbox>(&window, "list", true);
+
+ /* Disregard clicks on scrollbars and toggle buttons so the dropdown menu can be scrolled or have an embedded
+ * toggle button selected without the menu closing.
+ *
+ * This works since this click_callback function is called before widgets' left-button-up handlers.
+ *
+ * Additionally, this is done before row deselection so selecting/deselecting a toggle button doesn't also leave
+ * the list with no row visually selected. Oddly, the visual deselection doesn't seem to cause any crashes, and
+ * the previously selected row is reselected when the menu is opened again. Still, it's odd to see your selection
+ * vanish.
+ */
+ if(list.vertical_scrollbar()->get_state() == scrollbar_base::PRESSED) {
+ return;
+ }
+
+ if(dynamic_cast<toggle_button*>(window.find_at(coordinate, true)) != nullptr) {
+ return;
+ }
+
+ /* FIXME: This dialog uses a listbox with 'has_minimum = false'. This allows a listbox to have 0 or 1 selections,
+ * and selecting the same entry toggles that entry's state (ie, if it was selected, it will be deselected). Because
+ * of this, selecting the same entry in the dropdown list essentially sets the list's selected row to -1, causing problems.
+ *
+ * In order to work around this, we first manually deselect the selected entry here. This handler is called *before*
+ * the listbox's click handler, and as such the selected item will remain toggled on when the click handler fires.
+ */
+ const int sel = list.get_selected_row();
+ if(sel >= 0) {
+ list.select_row(sel, false);
+ }
+
+ SDL_Rect rect = window.get_rectangle();
+ if(!sdl::point_in_rect(coordinate, rect)) {
+ window.set_retval(retval::CANCEL);
+ } else if(!keep_open) {
+ window.set_retval(retval::OK);
+ }
+ }
+
void callback_flip_embedded_toggle(window& window)
{
listbox& list = find_widget<listbox>(&window, "list", true);
/* If the currently selected row has a toggle button, toggle it.
- * Note this cannot be handled in mouse_up_callback since at that point the new row selection has not registered,
+ * Note this cannot be handled in click_callback since at that point the new row selection has not registered,
* meaning the currently selected row's button is toggled.
*/
grid* row_grid = list.get_row_grid(list.get_selected_row());
@@ -55,61 +96,9 @@ namespace
void resize_callback(window& window)
{
window.set_retval(retval::CANCEL);
- window.close();
}
}
-void drop_down_menu::mouse_up_callback(window& window, bool&, bool&, const point& coordinate)
-{
- if(!mouse_down_happened_) {
- return;
- }
-
- listbox& list = find_widget<listbox>(&window, "list", true);
-
- /* Disregard clicks on scrollbars and toggle buttons so the dropdown menu can be scrolled or have an embedded
- * toggle button selected without the menu closing.
- *
- * This works since this mouse_up_callback function is called before widgets' left-button-up handlers.
- *
- * Additionally, this is done before row deselection so selecting/deselecting a toggle button doesn't also leave
- * the list with no row visually selected. Oddly, the visial deselection doesn't seem to cause any crashes, and
- * the previously selected row is reselected when the menu is opened again. Still, it's odd to see your selection
- * vanish.
- */
- if(list.vertical_scrollbar()->get_state() == scrollbar_base::PRESSED) {
- return;
- }
-
- if(dynamic_cast<toggle_button*>(window.find_at(coordinate, true)) != nullptr) {
- return;
- }
-
- /* FIXME: This dialog uses a listbox with 'has_minimum = false'. This allows a listbox to have 0 or 1 selections,
- * and selecting the same entry toggles that entry's state (ie, if it was selected, it will be deselected). Because
- * of this, selecting the same entry in the dropdown list essentially sets the list's selected row to -1, causing problems.
- *
- * In order to work around this, we first manually deselect the selected entry here. This handler is called *before*
- * the listbox's click handler, and as such the selected item will remain toggled on when the click handler fires.
- */
- const int sel = list.get_selected_row();
- if(sel >= 0) {
- list.select_row(sel, false);
- }
-
- SDL_Rect rect = window.get_rectangle();
- if(!sdl::point_in_rect(coordinate, rect)) {
- window.set_retval(retval::CANCEL);
- } else if(!keep_open_) {
- window.set_retval(retval::OK);
- }
-}
-
-void drop_down_menu::mouse_down_callback()
-{
- mouse_down_happened_ = true;
-}
-
void drop_down_menu::pre_show(window& window)
{
window.set_variable("button_x", wfl::variant(button_pos_.x));
@@ -119,44 +108,53 @@ void drop_down_menu::pre_show(window& window)
listbox& list = find_widget<listbox>(&window, "list", true);
- std::map<std::string, string_map> data;
- string_map item;
-
+ /* Each row's config can have the following keys. Note the containing [entry]
+ * tag is for illustrative purposes and isn't actually present in the configs.
+ *
+ * [entry]
+ * icon = "path/to/image.png" | Column 1 OR
+ * checkbox = yes/no | Column 1
+ * image = "path/to/image.png" | Column 2 OR
+ * label = "text" | Column 2
+ * details = "text" | Column 3
+ * tooltip = "text" | Entire row
+ * [/entry]
+ */
for(const auto& entry : items_) {
- data.clear();
+ std::map<std::string, string_map> data;
+ string_map item;
+
+ const bool has_image_key = entry.has_attribute("image");
+ const bool has_ckbox_key = entry.has_attribute("checkbox");
+
+ //
+ // These widgets can be initialized here since they don't require widget type swapping.
+ //
+ item["use_markup"] = utils::bool_string(use_markup_);
- item["label"] = entry["icon"];
- data.emplace("icon", item);
+ if(!has_ckbox_key) {
+ item["label"] = entry["icon"];
+ data.emplace("icon", item);
+ }
- if(!entry.has_attribute("image")) {
+ if(!has_image_key) {
item["label"] = entry["label"];
- item["use_markup"] = utils::bool_string(use_markup_);
data.emplace("label", item);
}
if(entry.has_attribute("details")) {
item["label"] = entry["details"];
- item["use_markup"] = utils::bool_string(use_markup_);
data.emplace("details", item);
}
grid& new_row = list.add_row(data);
+ grid& mi_grid = find_widget<grid>(&new_row, "menu_item", false);
// Set the tooltip on the whole panel
find_widget<toggle_panel>(&new_row, "panel", false).set_tooltip(entry["tooltip"]);
- if(entry.has_attribute("image")) {
- image* img = build_single_widget_instance<image>("image");
- img->set_label(entry["image"]);
-
- grid* mi_grid = dynamic_cast<grid*>(new_row.find("menu_item", false));
- if(mi_grid) {
- mi_grid->swap_child("label", img, false);
- }
- }
-
- if(entry.has_attribute("checkbox")) {
- toggle_button* checkbox = build_single_widget_instance<toggle_button>("toggle_button");
+ if(has_ckbox_key) {
+ toggle_button* checkbox = build_single_widget_instance<toggle_button>();
checkbox->set_id("checkbox");
checkbox->set_value_bool(entry["checkbox"].to_bool(false));
@@ -164,10 +162,14 @@ void drop_down_menu::pre_show(window& window)
connect_signal_notify_modified(*checkbox, std::bind(callback_toggle_state_change_));
}
- grid* mi_grid = dynamic_cast<grid*>(new_row.find("menu_item", false));
- if(mi_grid) {
- mi_grid->swap_child("icon", checkbox, false);
- }
+ mi_grid.swap_child("icon", checkbox, false);
+ }
+
+ if(has_image_key) {
+ image* img = build_single_widget_instance<image>();
+ img->set_label(entry["image"]);
+
+ mi_grid.swap_child("label", img, false);
}
}
@@ -177,30 +179,25 @@ void drop_down_menu::pre_show(window& window)
window.keyboard_capture(&list);
- // Dismiss on click outside the window
+ // Dismiss on clicking outside the window.
window.connect_signal<event::SDL_LEFT_BUTTON_UP>(
- std::bind(&drop_down_menu::mouse_up_callback, this, std::ref(window), _3, _4, _5), event::dispatcher::front_child);
+ std::bind(&click_callback, std::ref(window), keep_open_, _5), event::dispatcher::front_child);
window.connect_signal<event::SDL_RIGHT_BUTTON_UP>(
- std::bind(&drop_down_menu::mouse_up_callback, this, std::ref(window), _3, _4, _5), event::dispatcher::front_child);
+ std::bind(&click_callback, std::ref(window), keep_open_, _5), event::dispatcher::front_child);
- window.connect_signal<event::SDL_LEFT_BUTTON_DOWN>(
- std::bind(&drop_down_menu::mouse_down_callback, this), event::dispatcher::front_child);
+ // Dismiss on resize.
+ window.connect_signal<event::SDL_VIDEO_RESIZE>(
+ std::bind(&resize_callback, std::ref(window)), event::dispatcher::front_child);
// Handle embedded button toggling.
- // For some reason this works as a listbox value callback but don't ask me why.
- // - vultraz, 2017-02-17
- connect_signal_notify_modified(list, std::bind(&callback_flip_embedded_toggle, std::ref(window)));
-
- // Dismiss on resize
- window.connect_signal<event::SDL_VIDEO_RESIZE>(std::bind(&resize_callback, std::ref(window)), event::dispatcher::front_child);
+ connect_signal_notify_modified(list,
+ std::bind(&callback_flip_embedded_toggle, std::ref(window)));
}
void drop_down_menu::post_show(window& window)
{
- listbox& list = find_widget<listbox>(&window, "list", true);
-
- selected_item_ = list.get_selected_row();
+ selected_item_ = find_widget<listbox>(&window, "list", true).get_selected_row();
}
boost::dynamic_bitset<> drop_down_menu::get_toggle_states() const
diff --git a/src/gui/dialogs/drop_down_menu.hpp b/src/gui/dialogs/drop_down_menu.hpp
index ef2ed30e717..0c11dc0826a 100644
--- a/src/gui/dialogs/drop_down_menu.hpp
+++ b/src/gui/dialogs/drop_down_menu.hpp
@@ -37,7 +37,6 @@ public:
, selected_item_(selected_item)
, use_markup_(use_markup)
, keep_open_(keep_open)
- , mouse_down_happened_(false)
, callback_toggle_state_change_(callback_toggle_state_change)
{
set_restore(true);
@@ -72,12 +71,6 @@ private:
*/
bool keep_open_;
- /**
- * When menu is invoked on a long-touch timer, a following mouse-up event will close it.
- * This flag prevents that: the menu will only be closed on a mouse-up that follows a mouse-down.
- * */
- bool mouse_down_happened_;
-
/**
* If toggle buttons are used, this callback is called whenever the state of any toggle
* button changes.
@@ -92,10 +85,6 @@ private:
/** Inherited from modal_dialog. */
virtual void post_show(window& window) override;
-
- void mouse_up_callback(window& window, bool&, bool&, const point& coordinate);
-
- void mouse_down_callback();
};
} // namespace dialogs
diff --git a/src/gui/dialogs/editor/generate_map.cpp b/src/gui/dialogs/editor/generate_map.cpp
index bbbc0012a0a..91a57885296 100644
--- a/src/gui/dialogs/editor/generate_map.cpp
+++ b/src/gui/dialogs/editor/generate_map.cpp
@@ -19,11 +19,7 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/editor/set_starting_position.cpp b/src/gui/dialogs/editor/set_starting_position.cpp
index 906844b0044..f14ea3b328a 100644
--- a/src/gui/dialogs/editor/set_starting_position.cpp
+++ b/src/gui/dialogs/editor/set_starting_position.cpp
@@ -20,11 +20,7 @@
#include "formula/string_utils.hpp"
#include "gettext.hpp"
#include "gui/auxiliary/find_widget.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "map/location.hpp"
diff --git a/src/gui/dialogs/end_credits.cpp b/src/gui/dialogs/end_credits.cpp
index 58255bb9760..02ca834718e 100644
--- a/src/gui/dialogs/end_credits.cpp
+++ b/src/gui/dialogs/end_credits.cpp
@@ -55,7 +55,7 @@ void end_credits::pre_show(window& window)
last_scroll_ = SDL_GetTicks() + 3000;
});
- window.connect_signal<event::DRAW>(std::bind(&end_credits::timer_callback, this), event::dispatcher::front_child);
+ connect_signal_on_draw(window, std::bind(&end_credits::timer_callback, this));
connect_signal_pre_key_press(window, std::bind(&end_credits::key_press_callback, this, _5));
diff --git a/src/gui/dialogs/file_dialog.cpp b/src/gui/dialogs/file_dialog.cpp
index ee711adada3..f977952dece 100644
--- a/src/gui/dialogs/file_dialog.cpp
+++ b/src/gui/dialogs/file_dialog.cpp
@@ -25,11 +25,7 @@
#include "gui/dialogs/message.hpp"
#include "gui/dialogs/transient_message.hpp"
#include "gui/widgets/button.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- #include "gui/widgets/list.hpp"
-#else
- #include "gui/widgets/listbox.hpp"
-#endif
+#include "gui/widgets/listbox.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/toggle_panel.hpp"
@@ -573,7 +569,7 @@ void file_dialog::sync_bookmarks_bar(window& window)
}
current_bookmark_ = -1;
} else {
- const int new_selection = int(std::distance(bookmark_paths_.begin(), it.base()) - 1);
+ const int new_selection = static_cast<int>(std::distance(bookmark_paths_.begin(), it.base()) - 1);
if(new_selection != current_bookmark_) {
assert(unsigned(new_selection) < bookmarks_bar.get_item_count());
if(current_bookmark_ >= 0) {
@@ -687,7 +683,7 @@ void file_dialog::on_bookmark_del_cmd(window& window)
assert(user_bookmarks_begin_ >= 0
&& current_bookmark_ >= 0
&& current_bookmark_ >= user_bookmarks_begin_
- && current_bookmark_ < int(bookmark_paths_.size()));
+ && current_bookmark_ < static_cast<int>(bookmark_paths_.size()));
listbox& bookmarks_bar = find_widget<listbox>(&window, "bookmarks", false);
desktop::remove_user_bookmark(current_bookmark_ - user_bookmarks_begin_);
diff --git a/src/gui/dialogs/game_load.cpp b/src/gui/dialogs/game_load.cpp
index 2f07e99c4a4..8424ee448d4 100644
--- a/src/gui/dialogs/game_load.cpp
+++ b/src/gui/dialogs/game_load.cpp
@@ -30,14 +30,10 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#include "gui/widgets/scroll_label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/minimap.hpp"
#include "gui/widgets/settings.hpp"
+#include "gui/widgets/scroll_label.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/toggle_button.hpp"
#include "gui/widgets/window.hpp"
@@ -152,7 +148,7 @@ void game_load::pre_show(window& window)
connect_signal_mouse_left_click(
find_widget<button>(&window, "browse_saves_folder", false),
- bind_void(&desktop::open_object, filesystem::get_saves_dir()));
+ std::bind(&desktop::open_object, filesystem::get_saves_dir()));
display_savegame(window);
}
diff --git a/src/gui/dialogs/game_stats.cpp b/src/gui/dialogs/game_stats.cpp
index 2f0755ca69a..abcd86dff70 100644
--- a/src/gui/dialogs/game_stats.cpp
+++ b/src/gui/dialogs/game_stats.cpp
@@ -18,11 +18,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/core/log.hpp"
#include "gui/dialogs/message.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
diff --git a/src/gui/dialogs/game_version_dialog.cpp b/src/gui/dialogs/game_version_dialog.cpp
index 79f2d11774f..0d1a51e432f 100644
--- a/src/gui/dialogs/game_version_dialog.cpp
+++ b/src/gui/dialogs/game_version_dialog.cpp
@@ -26,11 +26,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/styled_widget.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/selectable_item.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/stacked_widget.hpp"
diff --git a/src/gui/dialogs/game_version_dialog.hpp b/src/gui/dialogs/game_version_dialog.hpp
index da12feaabe8..45d2076e0b3 100644
--- a/src/gui/dialogs/game_version_dialog.hpp
+++ b/src/gui/dialogs/game_version_dialog.hpp
@@ -24,13 +24,7 @@
namespace gui2
{
-
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-class list_view;
-#else
class listbox;
-#endif
-class stacked_widget;
namespace dialogs
{
diff --git a/src/gui/dialogs/help_browser.hpp b/src/gui/dialogs/help_browser.hpp
index 9e2d5d52538..2f2490a5d77 100644
--- a/src/gui/dialogs/help_browser.hpp
+++ b/src/gui/dialogs/help_browser.hpp
@@ -16,8 +16,6 @@
#include "gui/dialogs/modal_dialog.hpp"
-class config;
-
namespace gui2
{
namespace dialogs
diff --git a/src/gui/dialogs/hotkey_bind.cpp b/src/gui/dialogs/hotkey_bind.cpp
index 0754214800a..97ae05fc270 100644
--- a/src/gui/dialogs/hotkey_bind.cpp
+++ b/src/gui/dialogs/hotkey_bind.cpp
@@ -39,6 +39,7 @@ void hotkey_bind::pre_show(window& window)
window.connect_signal<event::SDL_RAW_EVENT>(
std::bind(&hotkey_bind::sdl_event_callback, this, std::ref(window), _5),
event::dispatcher::front_child);
+
}
void hotkey_bind::sdl_event_callback(window& win, const SDL_Event &event)
diff --git a/src/gui/dialogs/label_settings.cpp b/src/gui/dialogs/label_settings.cpp
index 5500cdf795d..e43073af090 100644
--- a/src/gui/dialogs/label_settings.cpp
+++ b/src/gui/dialogs/label_settings.cpp
@@ -23,11 +23,7 @@
#include "map/label.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/styled_widget.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/window.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/toggle_button.hpp"
diff --git a/src/gui/dialogs/language_selection.cpp b/src/gui/dialogs/language_selection.cpp
index 22f3bb99d48..fa6338fe08b 100644
--- a/src/gui/dialogs/language_selection.cpp
+++ b/src/gui/dialogs/language_selection.cpp
@@ -17,11 +17,7 @@
#include "gui/dialogs/language_selection.hpp"
#include "gui/auxiliary/find_widget.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "language.hpp"
diff --git a/src/gui/dialogs/language_selection.hpp b/src/gui/dialogs/language_selection.hpp
index 43f4bfedda0..b30226c9d64 100644
--- a/src/gui/dialogs/language_selection.hpp
+++ b/src/gui/dialogs/language_selection.hpp
@@ -28,6 +28,9 @@ public:
{
}
+ /** The execute function. See @ref modal_dialog for more information. */
+ DEFINE_SIMPLE_EXECUTE_WRAPPER(language_selection)
+
private:
/** Inherited from modal_dialog, implemented by REGISTER_DIALOG. */
virtual const std::string& window_id() const override;
diff --git a/src/gui/dialogs/loading_screen.cpp b/src/gui/dialogs/loading_screen.cpp
index 2f26f15b721..4202a87f607 100644
--- a/src/gui/dialogs/loading_screen.cpp
+++ b/src/gui/dialogs/loading_screen.cpp
@@ -199,10 +199,7 @@ loading_screen::~loading_screen()
* to end the thread faster.
*/
if(is_worker_running_) {
-#if defined(_MSC_VER) && _MSC_VER <= 1800
- HANDLE process = GetCurrentProcess();
- TerminateProcess(process, 0u);
-#elif defined(_LIBCPP_VERSION) || defined(__MINGW32__)
+#if defined(_LIBCPP_VERSION) || defined(__MINGW32__)
std::_Exit(0);
#else
std::quick_exit(0);
diff --git a/src/gui/dialogs/multiplayer/faction_select.cpp b/src/gui/dialogs/multiplayer/faction_select.cpp
index c8818e0db69..b2f093bc871 100644
--- a/src/gui/dialogs/multiplayer/faction_select.cpp
+++ b/src/gui/dialogs/multiplayer/faction_select.cpp
@@ -15,14 +15,11 @@
#include "gui/dialogs/multiplayer/faction_select.hpp"
+#include "game_config_manager.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/auxiliary/old_markup.hpp"
#include "gui/core/log.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
@@ -31,7 +28,6 @@
#include "gui/widgets/toggle_button.hpp"
#include "gui/widgets/window.hpp"
#include "formatter.hpp"
-#include "game_config_manager.hpp"
#include "gettext.hpp"
#include "help/help.hpp"
#include "preferences/game.hpp" // for encountered_units
diff --git a/src/gui/dialogs/multiplayer/lobby.cpp b/src/gui/dialogs/multiplayer/lobby.cpp
index d6426826f00..7c2dec5e9a7 100644
--- a/src/gui/dialogs/multiplayer/lobby.cpp
+++ b/src/gui/dialogs/multiplayer/lobby.cpp
@@ -26,11 +26,7 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/menu_button.hpp"
#include "gui/widgets/minimap.hpp"
#include "gui/widgets/chatbox.hpp"
@@ -392,14 +388,12 @@ void mp_lobby::update_gamelist_diff()
void mp_lobby::update_gamelist_header()
{
-#ifndef GUI2_EXPERIMENTAL_LISTBOX
const std::string games_string = VGETTEXT("Games: showing $num_shown out of $num_total", {
{"num_shown", std::to_string(lobby_info_.games_visibility().count())},
{"num_total", std::to_string(lobby_info_.games().size())}
});
find_widget<label>(gamelistbox_, "map", false).set_label(games_string);
-#endif
}
std::map<std::string, string_map> mp_lobby::make_game_row_data(const mp::game_info& game)
diff --git a/src/gui/dialogs/multiplayer/lobby.hpp b/src/gui/dialogs/multiplayer/lobby.hpp
index 1593bd47832..96f085f2ac0 100644
--- a/src/gui/dialogs/multiplayer/lobby.hpp
+++ b/src/gui/dialogs/multiplayer/lobby.hpp
@@ -22,18 +22,13 @@
#include "game_initialization/multiplayer.hpp"
#include "quit_confirmation.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#endif
class wesnothd_connection;
namespace gui2
{
class grid;
class label;
-#ifndef GUI2_EXPERIMENTAL_LISTBOX
class listbox;
-#endif
class text_box;
class window;
class multi_page;
diff --git a/src/gui/dialogs/multiplayer/mp_change_control.cpp b/src/gui/dialogs/multiplayer/mp_change_control.cpp
index 985f1f0dae6..aa6c7b26cd6 100644
--- a/src/gui/dialogs/multiplayer/mp_change_control.cpp
+++ b/src/gui/dialogs/multiplayer/mp_change_control.cpp
@@ -25,11 +25,7 @@
#include "preferences/credentials.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "log.hpp"
diff --git a/src/gui/dialogs/multiplayer/mp_connect.cpp b/src/gui/dialogs/multiplayer/mp_connect.cpp
index 880c0076046..c4d6f998a4f 100644
--- a/src/gui/dialogs/multiplayer/mp_connect.cpp
+++ b/src/gui/dialogs/multiplayer/mp_connect.cpp
@@ -20,11 +20,7 @@
#include "gui/auxiliary/field.hpp"
#include "gui/dialogs/modal_dialog.hpp"
#include "gui/widgets/button.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "utils/functional.hpp"
diff --git a/src/gui/dialogs/multiplayer/mp_create_game.cpp b/src/gui/dialogs/multiplayer/mp_create_game.cpp
index 7afe374130b..762a1890ace 100644
--- a/src/gui/dialogs/multiplayer/mp_create_game.cpp
+++ b/src/gui/dialogs/multiplayer/mp_create_game.cpp
@@ -28,11 +28,7 @@
#include "gui/widgets/integer_selector.hpp"
#include "gui/widgets/menu_button.hpp"
#include "preferences/game.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "formatter.hpp"
#include "formula/string_utils.hpp"
#include "game_config.hpp"
@@ -48,13 +44,8 @@
#include "savegame.hpp"
#include "map_settings.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "utils/functional.hpp"
-#endif
-
#include <boost/algorithm/string.hpp>
-
static lg::log_domain log_mp_create("mp/create");
#define DBG_MP LOG_STREAM(debug, log_mp_create)
diff --git a/src/gui/dialogs/multiplayer/mp_join_game.cpp b/src/gui/dialogs/multiplayer/mp_join_game.cpp
index 8f685811ebf..a73b5c1a963 100644
--- a/src/gui/dialogs/multiplayer/mp_join_game.cpp
+++ b/src/gui/dialogs/multiplayer/mp_join_game.cpp
@@ -34,11 +34,7 @@
#include "gui/widgets/menu_button.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/tree_view.hpp"
#include "gui/widgets/tree_view_node.hpp"
@@ -49,14 +45,12 @@
#include "utils/scope_exit.hpp"
#include "wesnothd_connection.hpp"
-
static lg::log_domain log_mp_connect_engine("mp/connect/engine");
#define DBG_MP LOG_STREAM(debug, log_mp_connect_engine)
#define LOG_MP LOG_STREAM(info, log_mp_connect_engine)
#define WRN_MP LOG_STREAM(warn, log_mp_connect_engine)
#define ERR_MP LOG_STREAM(err, log_mp_connect_engine)
-
namespace gui2
{
namespace dialogs
diff --git a/src/gui/dialogs/multiplayer/mp_method_selection.cpp b/src/gui/dialogs/multiplayer/mp_method_selection.cpp
index 4a6745c7158..ed5d9fe2f7f 100644
--- a/src/gui/dialogs/multiplayer/mp_method_selection.cpp
+++ b/src/gui/dialogs/multiplayer/mp_method_selection.cpp
@@ -20,11 +20,7 @@
#include "game_initialization/multiplayer.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/window.hpp"
@@ -72,7 +68,7 @@ void mp_method_selection::pre_show(window& window)
window.add_to_keyboard_chain(list);
connect_signal_mouse_left_click(find_widget<button>(&window, "register", false),
- bind_void(&desktop::open_object, forum_registration_url));
+ std::bind(&desktop::open_object, forum_registration_url));
}
void mp_method_selection::post_show(window& window)
diff --git a/src/gui/dialogs/multiplayer/mp_staging.cpp b/src/gui/dialogs/multiplayer/mp_staging.cpp
index 9bc03ca6675..1186a28c617 100644
--- a/src/gui/dialogs/multiplayer/mp_staging.cpp
+++ b/src/gui/dialogs/multiplayer/mp_staging.cpp
@@ -27,11 +27,7 @@
#include "gui/widgets/drawing.hpp"
#include "gui/widgets/menu_button.hpp"
#include "gui/widgets/image.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/label.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/slider.hpp"
diff --git a/src/gui/dialogs/outro.cpp b/src/gui/dialogs/outro.cpp
index f47326af262..272a871809b 100644
--- a/src/gui/dialogs/outro.cpp
+++ b/src/gui/dialogs/outro.cpp
@@ -52,8 +52,7 @@ void outro::pre_show(window& window)
window.set_enter_disabled(true);
window.get_canvas(0).set_variable("outro_text", wfl::variant(text_));
- window.connect_signal<event::DRAW>(
- std::bind(&outro::draw_callback, this, std::ref(window)), event::dispatcher::front_child);
+ connect_signal_on_draw(window, std::bind(&outro::draw_callback, this, std::ref(window)));
set_next_draw();
}
diff --git a/src/gui/dialogs/preferences_dialog.cpp b/src/gui/dialogs/preferences_dialog.cpp
index b1c27be3a0e..85c2e5504cb 100644
--- a/src/gui/dialogs/preferences_dialog.cpp
+++ b/src/gui/dialogs/preferences_dialog.cpp
@@ -49,11 +49,7 @@
#include "gui/widgets/grid.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/scroll_label.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/slider.hpp"
@@ -332,7 +328,7 @@ void preferences_dialog::initialize_sound_option_group(const std::string& id_suf
// the callback the setter callback is duplicated in the on-change callback. The field
// class could possibly use some reworking to make this less redundant, but for now it
// works well enough.
- register_bool(toggle_widget_id, true, toggle_getter, bind_void(toggle_setter, _1),
+ register_bool(toggle_widget_id, true, toggle_getter, std::bind(toggle_setter, _1),
std::bind(sound_toggle_on_change<toggle_setter>, std::ref(window), volume_widget_id, _1), true);
// Set up the volume slider. integer_field doesn't have a callback-on-changed mechanism.
@@ -473,19 +469,15 @@ void preferences_dialog::post_build(window& window)
register_integer("idle_anim_frequency", true,
idle_anim_rate, set_idle_anim_rate);
-#if 0
+
/* FONT SCALING */
register_integer("scaling_slider", true,
font_scaling, set_font_scaling);
-#endif
- /* FPS LIMITER */
- register_bool("fps_limiter", true,
- []() { return draw_delay() != 0; }, [](bool v) { set_draw_delay(v ? -1 : 0); });
/* SELECT THEME */
connect_signal_mouse_left_click(
find_widget<button>(&window, "choose_theme", false),
- bind_void(&show_theme_dialog));
+ std::bind(&show_theme_dialog));
//
// SOUND PANEL
@@ -648,7 +640,7 @@ void preferences_dialog::post_build(window& window)
}
case ADVANCED_PREF_TYPE::SLIDER: {
- slider* setter_widget = build_single_widget_instance<slider>("slider", config {"definition", "minimal"});
+ slider* setter_widget = build_single_widget_instance<slider>(config {"definition", "minimal"});
setter_widget->set_id("setter");
// Maximum must be set first or this will assert
setter_widget->set_value_range(option["min"].to_int(), option["max"].to_int());
@@ -695,7 +687,7 @@ void preferences_dialog::post_build(window& window)
selected = 0;
}
- menu_button* setter_widget = build_single_widget_instance<menu_button>("menu_button");
+ menu_button* setter_widget = build_single_widget_instance<menu_button>();
setter_widget->set_id("setter");
details_grid.swap_child("setter", setter_widget, true);
@@ -720,7 +712,7 @@ void preferences_dialog::post_build(window& window)
case ADVANCED_PREF_TYPE::SPECIAL: {
//main_grid->remove_child("setter");
- image* value_widget = build_single_widget_instance<image>("image");
+ image* value_widget = build_single_widget_instance<image>();
value_widget->set_label("icons/arrows/arrows_blank_right_25.png~CROP(3,3,18,18)");
main_grid->swap_child("value", value_widget, true);
@@ -1009,11 +1001,11 @@ void preferences_dialog::pre_show(window& window)
});
gui2::bind_status_label<slider>(&window, "turbo_slider");
-#if 0
+
gui2::bind_status_label<slider>(&window, "scaling_slider", [](slider& s)->std::string {
return s.get_value_label() + "%";
});
-#endif
+
listbox& selector = find_widget<listbox>(&window, "selector", false);
stacked_widget& pager = find_widget<stacked_widget>(&window, "pager", false);
diff --git a/src/gui/dialogs/preferences_dialog.hpp b/src/gui/dialogs/preferences_dialog.hpp
index 6ba1a3fa403..3787a53fe54 100644
--- a/src/gui/dialogs/preferences_dialog.hpp
+++ b/src/gui/dialogs/preferences_dialog.hpp
@@ -61,10 +61,8 @@ namespace gui2
class listbox;
class menu_button;
-class styled_widget;
class slider;
class text_box;
-class toggle_button;
namespace dialogs
{
diff --git a/src/gui/dialogs/screenshot_notification.cpp b/src/gui/dialogs/screenshot_notification.cpp
index b17ea50926c..792d64f447b 100644
--- a/src/gui/dialogs/screenshot_notification.cpp
+++ b/src/gui/dialogs/screenshot_notification.cpp
@@ -104,13 +104,13 @@ void screenshot_notification::pre_show(window& window)
button& open_b = find_widget<button>(&window, "open", false);
connect_signal_mouse_left_click(
- open_b, bind_void(&desktop::open_object, std::ref(path_)));
+ open_b, std::bind(&desktop::open_object, std::ref(path_)));
open_b.set_active(false);
button& bdir_b = find_widget<button>(&window, "browse_dir", false);
connect_signal_mouse_left_click(
bdir_b,
- bind_void(&desktop::open_object,
+ std::bind(&desktop::open_object,
std::ref(screenshots_dir_path_)));
button& save_b = find_widget<button>(&window, "save", false);
diff --git a/src/gui/dialogs/select_orb_colors.cpp b/src/gui/dialogs/select_orb_colors.cpp
index 2fe2fb110b2..ce7276fe8c0 100644
--- a/src/gui/dialogs/select_orb_colors.cpp
+++ b/src/gui/dialogs/select_orb_colors.cpp
@@ -16,7 +16,7 @@
#include "gui/dialogs/select_orb_colors.hpp"
#include "gui/auxiliary/find_widget.hpp"
-#include "gui/auxiliary/iterator/walker.hpp"
+#include "gui/auxiliary/iterator/iterator.hpp"
#include "gui/core/event/dispatcher.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/grid.hpp"
@@ -101,20 +101,14 @@ void select_orb_colors::setup_orb_group(const std::string& base_id, bool& shown,
//
group<std::string>& group = groups_[base_id];
- using iteration::walker_base;
-
+ // Grid containing each color option toggle.
grid& selection = find_widget<grid>(get_window(), prefix + "selection", false);
- std::unique_ptr<iteration::walker_base> iter(selection.create_walker());
-
- while(!iter->at_end(walker_base::child)) {
- widget* next = iter->get(walker_base::child);
- if(toggle_button* button = dynamic_cast<toggle_button*>(next)) {
+ for(iteration::bottom_up_iterator<true, false, true> iter(selection); !iter.at_end(); ++iter) {
+ if(toggle_button* button = dynamic_cast<toggle_button*>(iter.get())) {
const std::string& id = button->id();
group.add_member(button, id.substr(prefix.size()));
}
-
- iter->next(walker_base::child);
}
group.set_member_states(initial);
diff --git a/src/gui/dialogs/simple_item_selector.cpp b/src/gui/dialogs/simple_item_selector.cpp
index 9bc2172085e..0dd9aed4171 100644
--- a/src/gui/dialogs/simple_item_selector.cpp
+++ b/src/gui/dialogs/simple_item_selector.cpp
@@ -19,11 +19,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/statistics_dialog.cpp b/src/gui/dialogs/statistics_dialog.cpp
index 7ade67dcb74..a0f7101bda9 100644
--- a/src/gui/dialogs/statistics_dialog.cpp
+++ b/src/gui/dialogs/statistics_dialog.cpp
@@ -21,11 +21,7 @@
#include "gettext.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/menu_button.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/story_viewer.cpp b/src/gui/dialogs/story_viewer.cpp
index e06326c9b38..ff85b02dc05 100644
--- a/src/gui/dialogs/story_viewer.cpp
+++ b/src/gui/dialogs/story_viewer.cpp
@@ -88,8 +88,8 @@ void story_viewer::pre_show(window& window)
connect_signal_mouse_left_click(find_widget<button>(&window, "back", false),
std::bind(&story_viewer::nav_button_callback, this, std::ref(window), DIR_BACKWARDS));
- window.connect_signal<event::DRAW>(
- std::bind(&story_viewer::draw_callback, this, std::ref(window)), event::dispatcher::front_child);
+ connect_signal_on_draw(window,
+ std::bind(&story_viewer::draw_callback, this, std::ref(window)));
display_part(window);
}
diff --git a/src/gui/dialogs/story_viewer.hpp b/src/gui/dialogs/story_viewer.hpp
index f6ff2e0cd32..d671fd8fe9d 100644
--- a/src/gui/dialogs/story_viewer.hpp
+++ b/src/gui/dialogs/story_viewer.hpp
@@ -20,8 +20,6 @@
#include "storyscreen/controller.hpp"
#include "storyscreen/part.hpp"
-class CVideo;
-
namespace gui2
{
namespace dialogs
diff --git a/src/gui/dialogs/terrain_layers.cpp b/src/gui/dialogs/terrain_layers.cpp
index 9d233ec04d4..c9bec020cb3 100644
--- a/src/gui/dialogs/terrain_layers.cpp
+++ b/src/gui/dialogs/terrain_layers.cpp
@@ -19,11 +19,7 @@
#include "formatter.hpp"
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "picture.hpp"
diff --git a/src/gui/dialogs/theme_list.cpp b/src/gui/dialogs/theme_list.cpp
index 695fd127d83..3452d016117 100644
--- a/src/gui/dialogs/theme_list.cpp
+++ b/src/gui/dialogs/theme_list.cpp
@@ -15,11 +15,7 @@
#include "gui/dialogs/theme_list.hpp"
#include "gui/auxiliary/find_widget.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "theme.hpp"
diff --git a/src/gui/dialogs/unit_advance.cpp b/src/gui/dialogs/unit_advance.cpp
index de2116f6643..12d386cc36e 100644
--- a/src/gui/dialogs/unit_advance.cpp
+++ b/src/gui/dialogs/unit_advance.cpp
@@ -19,11 +19,7 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/unit_preview_pane.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/unit_attack.cpp b/src/gui/dialogs/unit_attack.cpp
index bd77a3692ba..45fbb599226 100644
--- a/src/gui/dialogs/unit_attack.cpp
+++ b/src/gui/dialogs/unit_attack.cpp
@@ -22,11 +22,7 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/label.hpp"
#include "gui/widgets/image.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/unit_preview_pane.hpp"
#include "gui/widgets/window.hpp"
@@ -75,12 +71,12 @@ REGISTER_DIALOG(unit_attack)
unit_attack::unit_attack(const unit_map::iterator& attacker_itor,
const unit_map::iterator& defender_itor,
- std::vector<battle_context>&& weapons,
+ const std::vector<battle_context>& weapons,
const int best_weapon)
: selected_weapon_(-1)
, attacker_itor_(attacker_itor)
, defender_itor_(defender_itor)
- , weapons_(std::move(weapons))
+ , weapons_(weapons)
, best_weapon_(best_weapon)
{
}
diff --git a/src/gui/dialogs/unit_attack.hpp b/src/gui/dialogs/unit_attack.hpp
index 5a3cbec3d20..3e24ef46e35 100644
--- a/src/gui/dialogs/unit_attack.hpp
+++ b/src/gui/dialogs/unit_attack.hpp
@@ -28,7 +28,7 @@ class unit_attack : public modal_dialog
public:
unit_attack(const unit_map::iterator& attacker_itor,
const unit_map::iterator& defender_itor,
- std::vector<battle_context>&& weapons,
+ const std::vector<battle_context>& weapons,
const int best_weapon);
/***** ***** ***** setters / getters for members ***** ****** *****/
diff --git a/src/gui/dialogs/unit_create.cpp b/src/gui/dialogs/unit_create.cpp
index ef849a150d6..5f050df494d 100644
--- a/src/gui/dialogs/unit_create.cpp
+++ b/src/gui/dialogs/unit_create.cpp
@@ -18,11 +18,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/core/log.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
@@ -33,7 +29,6 @@
#include "gui/widgets/unit_preview_pane.hpp"
#include "gui/widgets/window.hpp"
#include "help/help.hpp"
-#include "game_config.hpp"
#include "gettext.hpp"
#include "play_controller.hpp"
#include "units/types.hpp"
diff --git a/src/gui/dialogs/unit_list.cpp b/src/gui/dialogs/unit_list.cpp
index b800be90510..ead5bd5a3d0 100644
--- a/src/gui/dialogs/unit_list.cpp
+++ b/src/gui/dialogs/unit_list.cpp
@@ -18,11 +18,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/core/log.hpp"
#include "gui/dialogs/message.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
@@ -33,8 +29,6 @@
#include "display.hpp"
#include "font/text_formatting.hpp"
#include "formatter.hpp"
-#include "game_board.hpp"
-#include "resources.hpp"
#include "units/map.hpp"
#include "units/ptr.hpp"
#include "units/unit.hpp"
@@ -160,7 +154,7 @@ void unit_list::pre_show(window& window)
find_widget<image>(row_grid, "unit_status_slowed", false).set_visible(widget::visibility::invisible);
}
- if(!unit->invisible(unit->get_location(), *resources::gameboard, false)) {
+ if(!unit->invisible(unit->get_location(), false)) {
find_widget<image>(row_grid, "unit_status_invisible", false).set_visible(widget::visibility::invisible);
}
}
diff --git a/src/gui/dialogs/unit_recall.cpp b/src/gui/dialogs/unit_recall.cpp
index 0b82329908d..f6545ffe5a2 100644
--- a/src/gui/dialogs/unit_recall.cpp
+++ b/src/gui/dialogs/unit_recall.cpp
@@ -20,11 +20,7 @@
#include "gui/core/log.hpp"
#include "gui/dialogs/edit_text.hpp"
#include "gui/dialogs/message.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
diff --git a/src/gui/dialogs/unit_recall.hpp b/src/gui/dialogs/unit_recall.hpp
index 5984a80dacd..27dd4d88bbd 100644
--- a/src/gui/dialogs/unit_recall.hpp
+++ b/src/gui/dialogs/unit_recall.hpp
@@ -23,7 +23,6 @@
#include <vector>
class team;
-class unit_type;
namespace gui2
{
diff --git a/src/gui/dialogs/unit_recruit.cpp b/src/gui/dialogs/unit_recruit.cpp
index f3ec9cf9e6f..59f98e0bdfb 100644
--- a/src/gui/dialogs/unit_recruit.cpp
+++ b/src/gui/dialogs/unit_recruit.cpp
@@ -18,11 +18,7 @@
#include "gui/widgets/button.hpp"
#include "gui/widgets/image.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/unit_preview_pane.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/dialogs/wml_message.cpp b/src/gui/dialogs/wml_message.cpp
index 317464e0d79..73cc2d0077d 100644
--- a/src/gui/dialogs/wml_message.cpp
+++ b/src/gui/dialogs/wml_message.cpp
@@ -19,11 +19,7 @@
#include "gui/auxiliary/find_widget.hpp"
#include "gui/widgets/button.hpp"
#include "gui/widgets/label.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/settings.hpp"
#include "gui/widgets/text_box.hpp"
#include "gui/widgets/window.hpp"
diff --git a/src/gui/widgets/chatbox.cpp b/src/gui/widgets/chatbox.cpp
index 07cee0b4287..9c48c5a1609 100644
--- a/src/gui/widgets/chatbox.cpp
+++ b/src/gui/widgets/chatbox.cpp
@@ -226,11 +226,8 @@ void chatbox::append_to_chatbox(const std::string& text, size_t id, const bool f
log.set_label(new_text);
if(log_ != nullptr) {
- try {
- const std::string& room_name = open_windows_[id].name;
- log_->at(room_name).log = new_text;
- } catch(const std::out_of_range&) {
- }
+ const std::string& room_name = open_windows_[id].name;
+ log_->at(room_name).log = new_text;
}
if(chatbox_at_end || force_scroll) {
diff --git a/src/gui/widgets/debug.cpp b/src/gui/widgets/debug.cpp
index 3ba4409313d..1e96d5f9bdb 100644
--- a/src/gui/widgets/debug.cpp
+++ b/src/gui/widgets/debug.cpp
@@ -21,15 +21,10 @@
#include "formatter.hpp"
#include "gui/widgets/generator.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
#include "gui/widgets/listbox.hpp"
-#endif
#include "gui/widgets/scrollbar_container.hpp"
#include "gui/widgets/window.hpp"
#include "serialization/string_utils.hpp"
-#include "utils/io.hpp"
#include <fstream>
#include <iostream>
@@ -86,7 +81,7 @@ std::string get_base_filename()
std::ostringstream ss;
time_t t = time(nullptr);
- ss << utils::put_time(std::localtime(&t), "%Y%m%d_%H%M%S");
+ ss << std::put_time(std::localtime(&t), "%Y%m%d_%H%M%S");
static unsigned counter = 0;
++counter;
diff --git a/src/gui/widgets/generator.cpp b/src/gui/widgets/generator.cpp
index 8b53c6158eb..16a35ecddb3 100644
--- a/src/gui/widgets/generator.cpp
+++ b/src/gui/widgets/generator.cpp
@@ -552,7 +552,7 @@ point table::calculate_best_size() const
*/
size_t n_items = get_item_count();
- size_t max_cols = sqrt(n_items) + 2;
+ size_t max_cols = std::sqrt(n_items) + 2;
std::vector<point> item_sizes;
for(size_t i = 0; i < n_items; i++) {
diff --git a/src/gui/widgets/grid.hpp b/src/gui/widgets/grid.hpp
index c83c326bff2..359f979e3bb 100644
--- a/src/gui/widgets/grid.hpp
+++ b/src/gui/widgets/grid.hpp
@@ -343,16 +343,7 @@ private:
* of copied when the grid's child vector is resized. std::vector will
* utilize a move constructor as long as a non-throwing one is provided.
*/
-#if defined(_MSC_VER) && _MSC_VER <= 1800 // MSVC 2013
- child(child&& c) NOEXCEPT
- : flags_(c.flags_)
- , border_size_(c.border_size_)
- , widget_(std::move(c.widget_))
- {
- }
-#else
child(child&&) NOEXCEPT = default;
-#endif
/** Returns the best size for the cell. */
point get_best_size() const;
diff --git a/src/gui/widgets/list.cpp b/src/gui/widgets/list.cpp
deleted file mode 100644
index 75e0a364ed9..00000000000
--- a/src/gui/widgets/list.cpp
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- Copyright (C) 2010 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
-*/
-
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-
-#define GETTEXT_DOMAIN "wesnoth-lib"
-
-#include "gui/widgets/list.hpp"
-#include "gui/widgets/listbox.hpp"
-
-#include "gui/auxiliary/find_widget.hpp"
-#include "gui/core/log.hpp"
-#include "gui/widgets/detail/register.hpp"
-#include "gui/widgets/selectable.hpp"
-#include "gui/widgets/settings.hpp"
-#include "gui/widgets/window.hpp"
-
-#include "utils/functional.hpp"
-
-#define LOG_SCOPE_HEADER get_control_type() + " [" + id() + "] " + __func__
-#define LOG_HEADER LOG_SCOPE_HEADER + ':'
-
-namespace gui2
-{
-
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-REGISTER_WIDGET(listbox)
-#endif
-
-list_view::list_view(const bool has_minimum,
- const bool has_maximum,
- const generator_base::tplacement placement,
- const bool select,
- const builder_grid_const_ptr list_builder)
- : container_base()
- , state_(ENABLED)
- , generator_(nullptr)
- , list_builder_(list_builder)
- , need_layout_(false)
-{
- assert(list_builder);
-
- generator_
- = generator_base::build(has_minimum, has_maximum, placement, select);
- assert(generator_);
-
- connect_signal<event::LEFT_BUTTON_DOWN>(
- std::bind(&list_view::signal_handler_left_button_down, this, _2),
- event::dispatcher::back_pre_child);
-
- connect_signal<event::SDL_KEY_DOWN>(std::bind(
- &list_view::signal_handler_sdl_key_down, this, _2, _3, _5, _6));
-
- connect_signal<event::SDL_KEY_DOWN>(
- std::bind(
- &list_view::signal_handler_sdl_key_down, this, _2, _3, _5, _6),
- event::dispatcher::back_pre_child);
-}
-
-void list_view::add_row(const string_map& item, const int index)
-{
- std::map<std::string, string_map> data;
-
- data.emplace("", item);
- add_row(data, index);
-}
-
-void
-list_view::add_row(const std::map<std::string /* widget id */, string_map>& data,
- const int index)
-{
- assert(generator_);
- grid& grid = generator_->create_item(index, list_builder_, data, nullptr);
-
- selectable_item* selectable
- = find_widget<selectable_item>(&grid, "_toggle", false, false);
-
- if(selectable) {
- dynamic_cast<widget&>(*selectable)
- .connect_signal<event::LEFT_BUTTON_CLICK>(
- std::bind(
- &list_view::signal_handler_pre_child_left_button_click,
- this,
- &grid,
- _2,
- _3,
- _4),
- event::dispatcher::back_pre_child);
-
- // Post widget for panel.
- dynamic_cast<widget&>(*selectable)
- .connect_signal<event::LEFT_BUTTON_CLICK>(
- std::bind(&list_view::signal_handler_left_button_click,
- this,
- &grid,
- _2),
- event::dispatcher::back_post_child);
-
- // Post widget for button and widgets on the panel.
- dynamic_cast<widget&>(*selectable)
- .connect_signal<event::LEFT_BUTTON_CLICK>(
- std::bind(&list_view::signal_handler_left_button_click,
- this,
- &grid,
- _2),
- event::dispatcher::back_child);
- }
-}
-
-void list_view::append_rows(const std::vector<string_map>& items)
-{
- for(const string_map & item : items)
- {
- add_row(item);
- }
-}
-
-void list_view::remove_row(const unsigned row, unsigned count)
-{
- assert(generator_);
-
- if(row >= get_item_count()) {
- return;
- }
-
- if(!count || count > get_item_count()) {
- count = get_item_count();
- }
-
- unsigned height_reduced = 0;
- for(; count; --count) {
- if(generator_->item(row).get_visible() != visibility::invisible) {
- height_reduced += generator_->item(row).get_height();
- }
- generator_->delete_item(row);
- }
-
- if(height_reduced != 0) {
- // resize_content(0, -height_reduced);
- }
-}
-
-void list_view::clear()
-{
- // Due to the removing from the linked group, don't use
- // generator_->clear() directly.
- remove_row(0, 0);
-}
-
-unsigned list_view::get_item_count() const
-{
- assert(generator_);
- return generator_->get_item_count();
-}
-
-void list_view::set_row_active(const unsigned row, const bool active)
-{
- assert(generator_);
- generator_->item(row).set_active(active);
-}
-
-void list_view::set_row_shown(const unsigned row, const bool shown)
-{
- assert(generator_);
-
- window* window = get_window();
- assert(window);
-
- const int selected_row = get_selected_row();
-
- bool resize_needed = false;
- {
- window::invalidate_layout_blocker invalidate_layout_blocker(*window);
-
- generator_->set_item_shown(row, shown);
- generator_->place(generator_->get_origin(),
- generator_->calculate_best_size());
- // resize_needed = !content_resize_request();
- }
-
- if(resize_needed) {
- window->invalidate_layout();
- } else {
- // get_grid().set_visible_rectangle(content_visible_rectangle());
- set_is_dirty(true);
- }
-
- if(selected_row != get_selected_row()) {
- fire(event::NOTIFY_MODIFIED, *this, nullptr);
- }
-}
-
-void list_view::set_row_shown(const boost::dynamic_bitset<>& shown)
-{
- assert(generator_);
- assert(shown.size() == get_item_count());
-
- window* window = get_window();
- assert(window);
-
- const int selected_row = get_selected_row();
-
- bool resize_needed = false;
- {
- window::invalidate_layout_blocker invalidate_layout_blocker(*window);
-
- for(size_t i = 0; i < shown.size(); ++i) {
- generator_->set_item_shown(i, shown[i]);
- }
- generator_->place(generator_->get_origin(),
- generator_->calculate_best_size());
- // resize_needed = !content_resize_request();
- }
-
- if(resize_needed) {
- window->invalidate_layout();
- } else {
- // content_grid_->set_visible_rectangle(content_visible_rectangle());
- set_is_dirty(true);
- }
-
- if(selected_row != get_selected_row()) {
- fire(event::NOTIFY_MODIFIED, *this, nullptr);
- }
-}
-
-const grid* list_view::get_row_grid(const unsigned row) const
-{
- assert(generator_);
- // rename this function and can we return a reference??
- return &generator_->item(row);
-}
-
-grid* list_view::get_row_grid(const unsigned row)
-{
- assert(generator_);
- return &generator_->item(row);
-}
-
-bool list_view::select_row(const unsigned row, const bool select)
-{
- assert(generator_);
-
- generator_->select_item(row, select);
-
- return true; // FIXME test what result should have been!!!
-}
-
-int list_view::get_selected_row() const
-{
- assert(generator_);
-
- return generator_->get_selected_item();
-}
-
-void list_view::place(const point& origin, const point& size)
-{
- // Inherited.
- container_base::place(origin, size);
-
- /**
- * @todo Work-around to set the selected item visible again.
- *
- * At the moment the lists and dialogs in general are resized a lot as
- * work-around for sizing. So this function makes the selected item in view
- * again. It doesn't work great in all cases but the proper fix is to avoid
- * resizing dialogs a lot. Need more work later on.
- */
- const int selected_item = generator_->get_selected_item();
- if(selected_item != -1) {
- /*
- const SDL_Rect& visible = content_visible_area();
- SDL_Rect rect = generator_->item(selected_item).get_rectangle();
-
- rect.x = visible.x;
- rect.w = visible.w;
-
- show_content_rect(rect);
- */
- }
-}
-#if 0
-void list_view::resize_content(
- const int width_modification
- , const int height_modification)
-{
- DBG_GUI_L << LOG_HEADER << " current size " << content_grid()->get_size()
- << " width_modification " << width_modification
- << " height_modification " << height_modification
- << ".\n";
-
- if(content_resize_request(width_modification, height_modification)) {
-
- // Calculate new size.
- point size = content_grid()->get_size();
- size.x += width_modification;
- size.y += height_modification;
-
- // Set new size.
- content_grid()->set_size(size);
-
- // Set status.
- need_layout_ = true;
- // If the content grows assume it "overwrites" the old content.
- if(width_modification < 0 || height_modification < 0) {
- set_is_dirty(true);
- }
- DBG_GUI_L << LOG_HEADER << " succeeded.\n";
- } else {
- DBG_GUI_L << LOG_HEADER << " failed.\n";
- }
-}
-#endif
-
-void list_view::init()
-{
- init_grid(cast<listbox_definition::resolution>(config()).grid);
-
- set_single_child(find_widget<grid>(&get_grid(), "_list_grid", false),
- generator_);
-
- /*
- * These items should be managed by the new listbox class.
- * So make them invisible for now.
- */
- grid* g = find_widget<grid>(&get_grid(), "_header_grid", false, false);
- if(g)
- g->set_visible(widget::visibility::invisible);
-
- g = find_widget<grid>(&get_grid(), "_footer_grid", false, false);
- if(g)
- g->set_visible(widget::visibility::invisible);
-
- g = find_widget<grid>(&get_grid(), "_vertical_scrollbar_grid", false, false);
- if(g)
- g->set_visible(widget::visibility::invisible);
-
- g = find_widget<grid>(&get_grid(), "_horizontal_scrollbar_grid", false, false);
- if(g)
- g->set_visible(widget::visibility::invisible);
-}
-
-bool list_view::get_active() const
-{
- return state_ != DISABLED;
-}
-
-unsigned list_view::get_state() const
-{
- return state_;
-}
-
-void list_view::layout_children(const bool force)
-{
- if(need_layout_ || force) {
- get_grid().place(get_grid().get_origin(), get_grid().get_size());
-
- /*
- get_grid().set_visible_rectangle(content_visible_area_);
- */
- need_layout_ = false;
- set_is_dirty(true);
- }
-}
-
-void list_view::set_self_active(const bool active)
-{
- /* DO NOTHING */
-}
-
-void list_view::signal_handler_left_button_down(const event::ui_event event)
-{
- DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
-
- assert(get_window());
- get_window()->keyboard_capture(this);
-}
-
-void list_view::signal_handler_pre_child_left_button_click(
- grid* grid, const event::ui_event event, bool& handled, bool& halt)
-{
- DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
-
- assert(grid);
- assert(generator_);
-
- for(size_t i = 0; i < generator_->get_item_count(); ++i) {
- if(&generator_->item(i) == grid) {
-
- /**
- * @todo Here we should check whether the panel can be toggled.
- *
- * NO set halt + handled
- * YES do nothing
- *
- * Then a post to the widget, which if done sets the proper state
- * in the list.
- *
- * For now we simply assume an item can only be selected and not
- * deselected (which is true at the moment).
- */
- if(generator_->is_selected(i)) {
- halt = true;
- handled = true;
- }
- return;
- }
- }
- assert(false);
-}
-
-void list_view::signal_handler_left_button_click(grid* grid,
- const event::ui_event event)
-{
- DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
- assert(grid);
- assert(generator_);
-
- /** @todo Test the proper state to set. */
- for(size_t i = 0; i < generator_->get_item_count(); ++i) {
- if(&generator_->item(i) == grid) {
- generator_->select_item(i);
- fire(event::NOTIFY_MODIFIED, *this, nullptr);
- }
- }
-}
-
-void list_view::signal_handler_sdl_key_down(const event::ui_event event,
- bool& handled,
- const SDL_Keycode key,
- SDL_Keymod modifier)
-{
- DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
-
- if(handled) {
- return;
- }
-
- switch(key) {
- case SDLK_UP:
- generator_->handle_key_up_arrow(modifier, handled);
- break;
- case SDLK_DOWN:
- generator_->handle_key_down_arrow(modifier, handled);
- break;
- case SDLK_LEFT:
- generator_->handle_key_left_arrow(modifier, handled);
- break;
- case SDLK_RIGHT:
- generator_->handle_key_right_arrow(modifier, handled);
- break;
- default:
- ;
- /* Do nothing. */
- }
- if(handled) {
- fire(event::NOTIFY_MODIFIED, *this, nullptr);
- }
-}
-
-} // namespace gui2
-
-#endif
diff --git a/src/gui/widgets/list.hpp b/src/gui/widgets/list.hpp
deleted file mode 100644
index 756691a9e3e..00000000000
--- a/src/gui/widgets/list.hpp
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- Copyright (C) 2010 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
-*/
-
-#pragma once
-
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-
-#include "gui/widgets/generator.hpp"
-#include "gui/widgets/scrollbar_container.hpp"
-
-#include <boost/dynamic_bitset.hpp>
-
-namespace gui2
-{
-
-/**
- * The list class.
- *
- * For now it's a generic for all kind of lists, horizontal, vertical etc.
- * Might be that there will be different types per class, not sure yet.
- */
-class list_view : public container_base
-{
- friend class debug_layout_graph;
-
-public:
- /**
- * Constructor.
- *
- * @param has_minimum Does the listbox need to have one item
- * selected.
- * @param has_maximum Can the listbox only have one item
- * selected.
- * @param placement How are the items placed.
- * @param select Select an item when selected, if false it
- * changes the visible state instead.
- */
- list_view(const bool has_minimum,
- const bool has_maximum,
- const generator_base::tplacement placement,
- const bool select,
- const builder_grid_const_ptr list_builder);
-
- /***** ***** ***** ***** Row handling. ***** ***** ****** *****/
- /**
- * When an item in the list is selected by the user we need to
- * update the state. We installed a callback handler which
- * calls us.
- *
- * @param item The data send to the set_members of the
- * widgets.
- * @param index The item before which to add the new item,
- * 0 == begin, -1 == end.
- */
- void add_row(const string_map& item, const int index = -1);
-
- /**
- * Adds single row to the grid.
- *
- * This function expect a row to have multiple widgets (either multiple
- * columns or one column with multiple widgets).
- *
- *
- * @param data The data to send to the set_members of the
- * widgets. If the member id is not an empty
- * string it is only send to the widget that has
- * the wanted id (if any). If the member id is an
- * empty string, it is send to all members.
- * Having both empty and non-empty id's gives
- * undefined behavior.
- * @param index The item before which to add the new item,
- * 0 == begin, -1 == end.
- */
- void add_row(const std::map<std::string /* widget id */, string_map>& data,
- const int index = -1);
-
- /**
- * Appends several rows to the grid.
- *
- * @param items The data to send to the set_members of the
- * widgets.
- */
- void append_rows(const std::vector<string_map>& items);
-
- /**
- * Removes a row in the listbox.
- *
- * @param row The row to remove, when not in
- * range the function is ignored.
- * @param count The number of rows to remove, 0 means all
- * rows (starting from row).
- */
- void remove_row(const unsigned row, unsigned count = 1);
-
- /** Removes all the rows in the listbox, clearing it. */
- void clear();
-
- /** Returns the number of items in the listbox. */
- unsigned get_item_count() const;
-
- /**
- * Makes a row active or inactive.
- *
- * NOTE this doesn't change the select status of the row.
- *
- * @param row The row to (de)activate.
- * @param active true activate, false deactivate.
- */
- void set_row_active(const unsigned row, const bool active);
-
- /**
- * Makes a row visible or invisible.
- *
- * @param row The row to show or hide.
- * @param shown true visible, false invisible.
- */
- void set_row_shown(const unsigned row, const bool shown);
-
- /**
- * Makes a row visible or invisible.
- *
- * Use this version if you want to show hide multiple items since it's
- * optimized for that purpose, for one it calls the selection changed
- * callback only once instead of several times.
- *
- * @param shown A vector with the show hide status for every
- * row. The number of items in the vector must
- * be equal to the number of items in the
- * listbox.
- */
- void set_row_shown(const boost::dynamic_bitset<>& shown);
-
- /**
- * Returns the grid of the wanted row.
- *
- * There's only a const version since allowing callers to modify the grid
- * behind our backs might give problems. We return a pointer instead of a
- * reference since dynamic casting of pointers is easier (no try catch
- * needed).
- *
- * @param row The row to get the grid from, the caller has
- * to make sure the row is a valid row.
- * @returns The grid of the wanted row.
- */
- const grid* get_row_grid(const unsigned row) const;
-
- /**
- * The possibly-giving-problems nonconst version of get_row_grid
- *
- * @param row The row to get the grid from, the caller has
- * to make sure the row is a valid row.
- * @returns The grid of the wanted row.
- */
- grid* get_row_grid(const unsigned row);
-
- /**
- * Selectes a row.
- *
- * @param row The row to select.
- * @param select Select or deselect the row.
- */
- bool select_row(const unsigned row, const bool select = true);
-
- /**
- * Returns the first selected row
- *
- * @returns The first selected row.
- * @retval -1 No row selected.
- */
- int get_selected_row() const;
-#if 0
- /**
- * Request to update the size of the content after changing the content.
- *
- * When a resize is required the container first can try to handle it
- * itself. If it can't honor the request the function will call @ref
- * window::invalidate_layout().
- *
- * @note Calling this function on a widget with size == (0, 0) results
- * false but doesn't call invalidate_layout, the engine expects to be in
- * build up phase with the layout already invalidated.
- *
- * @returns True if the resizing succeeded, false
- * otherwise.
- */
- bool update_content_size();
-#endif
- /***** ***** ***** ***** inherited ***** ***** ****** *****/
-
- /** Inherited from tcontrol_. */
- void init();
-
- /** See @ref styled_widget::get_active. */
- virtual bool get_active() const override;
-
- /** See @ref styled_widget::get_state. */
- virtual unsigned get_state() const override;
-
- /** See @ref widget::place. */
- virtual void place(const point& origin, const point& size) override;
-
-private:
- /**
- * Possible states of the widget.
- *
- * Note the order of the states must be the same as defined in settings.hpp.
- */
- enum state_t {
- ENABLED,
- DISABLED,
- };
-
- /**
- * Current state of the widget.
- *
- * The state of the widget determines what to render and how the widget
- * reacts to certain 'events'.
- */
- state_t state_;
-
- /**
- * Contains a pointer to the generator.
- *
- * The pointer is not owned by this class, it's stored in the content_grid_
- * of the scrollbar_container super class and freed when it's grid is
- * freed.
- */
- generator_base* generator_;
-
- /** Contains the builder for the new items. */
- builder_grid_const_ptr list_builder_;
-
- bool need_layout_;
-#if 0
- /**
- * Resizes the content.
- *
- * The resize either happens due to resizing the content or invalidate the
- * layout of the window.
- *
- * @param width_modification The wanted modification to the width:
- * * negative values reduce width.
- * * zero leave width as is.
- * * positive values increase width.
- * @param height_modification The wanted modification to the height:
- * * negative values reduce height.
- * * zero leave height as is.
- * * positive values increase height.
- */
- void resize_content(
- const int width_modification
- , const int height_modification);
-#endif
- /** Layouts the children if needed. */
- void layout_children(const bool force);
-#if 0
- /** Inherited from scrollbar_container. */
- virtual void set_content_size(const point& origin, const point& size);
-#endif
- /** See @ref container_base::set_self_active. */
- virtual void set_self_active(const bool active) override;
-
-public:
- /** Static type getter that does not rely on the widget being constructed. */
- static const std::string& type();
-
-private:
- /** Inherited from styled_widget, implemented by REGISTER_WIDGET. */
- virtual const std::string& get_control_type() const override;
-
- /***** ***** ***** signal handlers ***** ****** *****/
-
- void signal_handler_left_button_down(const event::ui_event event);
-
- void signal_handler_pre_child_left_button_click(grid* grid,
- const event::ui_event event,
- bool& handled,
- bool& halt);
-
- void signal_handler_left_button_click(grid* grid,
- const event::ui_event event);
-
- void signal_handler_sdl_key_down(const event::ui_event event,
- bool& handled,
- const SDL_Keycode key,
- SDL_Keymod modifier);
-};
-
-typedef list_view listbox;
-
-} // namespace gui2
-
-#endif
diff --git a/src/gui/widgets/listbox.cpp b/src/gui/widgets/listbox.cpp
index 52742993ab2..a0f4d27ff45 100644
--- a/src/gui/widgets/listbox.cpp
+++ b/src/gui/widgets/listbox.cpp
@@ -12,8 +12,6 @@
See the COPYING file for more details.
*/
-#ifndef GUI2_EXPERIMENTAL_LISTBOX
-
#define GETTEXT_DOMAIN "wesnoth-lib"
#include "gui/widgets/listbox.hpp"
@@ -973,17 +971,6 @@ builder_listbox::builder_listbox(const config& cfg)
widget* builder_listbox::build() const
{
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- list_view* widget = new list_view(true, true, generator_base::vertical_list, true, list_builder);
-
- // init_control(widget);
- if(!list_data.empty()) {
- widget->append_rows(list_data);
- }
-
- return widget;
-#else
-
listbox* widget = new listbox(*this, generator_base::vertical_list, list_builder, has_minimum_, has_maximum_);
widget->set_vertical_scrollbar_mode(vertical_scrollbar_mode);
@@ -999,7 +986,6 @@ widget* builder_listbox::build() const
widget->finalize(header, footer, list_data);
return widget;
-#endif
}
/*WIKI_MACRO
@@ -1090,17 +1076,6 @@ builder_horizontal_listbox::builder_horizontal_listbox(const config& cfg)
widget* builder_horizontal_listbox::build() const
{
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- list_view* widget = new list_view(true, true, generator_base::horizontal_list, true, list_builder);
-
- // init_control(widget);
- if(!list_data.empty()) {
- widget->append_rows(list_data);
- }
-
- return widget;
-#else
-
listbox* widget = new listbox(*this, generator_base::horizontal_list, list_builder, has_minimum_, has_maximum_);
widget->set_vertical_scrollbar_mode(vertical_scrollbar_mode);
@@ -1116,7 +1091,6 @@ widget* builder_horizontal_listbox::build() const
widget->finalize(nullptr, nullptr, list_data);
return widget;
-#endif
}
/*WIKI_MACRO
@@ -1207,17 +1181,6 @@ builder_grid_listbox::builder_grid_listbox(const config& cfg)
widget* builder_grid_listbox::build() const
{
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- list_view* widget = new list_view(true, true, generator_base::grid, true, list_builder);
-
- // init_control(widget);
- if(!list_data.empty()) {
- widget->append_rows(list_data);
- }
-
- return widget;
-#else
-
listbox* widget = new listbox(*this, generator_base::table, list_builder, has_minimum_, has_maximum_);
widget->set_vertical_scrollbar_mode(vertical_scrollbar_mode);
@@ -1233,7 +1196,6 @@ widget* builder_grid_listbox::build() const
widget->finalize(nullptr, nullptr, list_data);
return widget;
-#endif
}
} // namespace implementation
@@ -1241,5 +1203,3 @@ widget* builder_grid_listbox::build() const
// }------------ END --------------
} // namespace gui2
-
-#endif
diff --git a/src/gui/widgets/listbox.hpp b/src/gui/widgets/listbox.hpp
index 5ae8b510504..2f7e3ec4d2d 100644
--- a/src/gui/widgets/listbox.hpp
+++ b/src/gui/widgets/listbox.hpp
@@ -14,8 +14,6 @@
#pragma once
-#ifndef GUI2_EXPERIMENTAL_LISTBOX
-
#include "gui/widgets/generator.hpp"
#include "gui/widgets/scrollbar_container.hpp"
@@ -526,5 +524,3 @@ struct builder_grid_listbox : public builder_styled_widget
// }------------ END --------------
} // namespace gui2
-
-#endif
diff --git a/src/gui/widgets/matrix.hpp b/src/gui/widgets/matrix.hpp
index 7bbc10a1265..0d001b89c8f 100644
--- a/src/gui/widgets/matrix.hpp
+++ b/src/gui/widgets/matrix.hpp
@@ -157,7 +157,7 @@ public:
*
* @param compare_functor The functor to use to sort the items.
*/
- void sort(const pane::tcompare_functor& compare_functor)
+ void sort(const pane::compare_functor_t& compare_functor)
{
/********************** OUTLINE *******************/
pane_->sort(compare_functor);
@@ -172,7 +172,7 @@ public:
* @param filter_functor The functor to determine whether an item
* should be shown or hidden.
*/
- void filter(const pane::tfilter_functor& filter_functor)
+ void filter(const pane::filter_functor_t& filter_functor)
{
/********************** OUTLINE *******************/
pane_->filter(filter_functor);
diff --git a/src/gui/widgets/pane.cpp b/src/gui/widgets/pane.cpp
index da3b762dcd3..ccdc4156f1d 100644
--- a/src/gui/widgets/pane.cpp
+++ b/src/gui/widgets/pane.cpp
@@ -208,14 +208,14 @@ void pane::child_populate_dirty_list(window& caller,
}
}
-void pane::sort(const tcompare_functor& compare_functor)
+void pane::sort(const compare_functor_t& compare_functor)
{
items_.sort(compare_functor);
set_origin_children();
}
-void pane::filter(const tfilter_functor& filter_functor)
+void pane::filter(const filter_functor_t& filter_functor)
{
for(auto & item : items_)
{
diff --git a/src/gui/widgets/pane.hpp b/src/gui/widgets/pane.hpp
index fdda3f8dfd6..306e3522028 100644
--- a/src/gui/widgets/pane.hpp
+++ b/src/gui/widgets/pane.hpp
@@ -48,9 +48,9 @@ public:
grid* item_grid;
};
- typedef std::function<bool(const item&, const item&)> tcompare_functor;
+ typedef std::function<bool(const item&, const item&)> compare_functor_t;
- typedef std::function<bool(const item&)> tfilter_functor;
+ typedef std::function<bool(const item&)> filter_functor_t;
/** @deprecated Use the second overload. */
explicit pane(const builder_grid_ptr item_builder);
@@ -99,7 +99,7 @@ public:
*
* @param compare_functor The functor to use to sort the items.
*/
- void sort(const tcompare_functor& compare_functor);
+ void sort(const compare_functor_t& compare_functor);
/**
* Filters the contents of the pane.
@@ -110,7 +110,7 @@ public:
* @param filter_functor The functor to determine whether an item
* should be shown or hidden.
*/
- void filter(const tfilter_functor& filter_functor);
+ void filter(const filter_functor_t& filter_functor);
private:
/** See @ref widget::calculate_best_size. */
diff --git a/src/gui/widgets/password_box.cpp b/src/gui/widgets/password_box.cpp
index e7b81ccf3ac..e5a1e057762 100644
--- a/src/gui/widgets/password_box.cpp
+++ b/src/gui/widgets/password_box.cpp
@@ -46,7 +46,7 @@ void password_box::set_value(const std::string& text)
{
real_value_ = text;
size_t sz = utf8::size(text);
- utf8::string passwd;
+ std::string passwd;
for(size_t i = 0; i < sz; i++) {
passwd.append(font::unicode_bullet);
}
@@ -70,7 +70,7 @@ void password_box::delete_selection()
set_cursor(start, false);
}
-void password_box::insert_char(const utf8::string& unicode)
+void password_box::insert_char(const std::string& unicode)
{
int len = get_selection_length();
unsigned sel = get_selection_start();
@@ -83,7 +83,7 @@ void password_box::insert_char(const utf8::string& unicode)
if(sz == 1) {
text_box::insert_char(font::unicode_bullet);
} else {
- utf8::string passwd;
+ std::string passwd;
for(size_t i = 0; i < sz; i++) {
passwd.append(font::unicode_bullet);
}
diff --git a/src/gui/widgets/password_box.hpp b/src/gui/widgets/password_box.hpp
index e487c2b1f39..f736a72a1c0 100644
--- a/src/gui/widgets/password_box.hpp
+++ b/src/gui/widgets/password_box.hpp
@@ -49,7 +49,7 @@ public:
protected:
- void insert_char(const utf8::string& unicode) override;
+ void insert_char(const std::string& unicode) override;
void paste_selection(const bool mouse) override;
void delete_selection() override;
diff --git a/src/gui/widgets/scrollbar.cpp b/src/gui/widgets/scrollbar.cpp
index dfe974b2269..55e2e8f711d 100644
--- a/src/gui/widgets/scrollbar.cpp
+++ b/src/gui/widgets/scrollbar.cpp
@@ -43,8 +43,6 @@ scrollbar_base::scrollbar_base(const implementation::builder_styled_widget& buil
&scrollbar_base::signal_handler_mouse_enter, this, _2, _3, _4));
connect_signal<event::MOUSE_MOTION>(std::bind(
&scrollbar_base::signal_handler_mouse_motion, this, _2, _3, _4, _5));
- connect_signal<event::SDL_TOUCH_MOTION>(std::bind(
- &scrollbar_base::signal_handler_mouse_motion, this, _2, _3, _4, _5));
connect_signal<event::MOUSE_LEAVE>(std::bind(
&scrollbar_base::signal_handler_mouse_leave, this, _2, _3));
connect_signal<event::LEFT_BUTTON_DOWN>(std::bind(
@@ -62,11 +60,6 @@ void scrollbar_base::finalize_setup()
}
}
-void scrollbar_base::scroll_by(const int pixels)
-{
- move_positioner(static_cast<int>(pixels_per_step_ * pixels));
-}
-
void scrollbar_base::scroll(const scroll_mode scroll)
{
switch(scroll) {
diff --git a/src/gui/widgets/scrollbar.hpp b/src/gui/widgets/scrollbar.hpp
index dad4d541ac1..34940a0daad 100644
--- a/src/gui/widgets/scrollbar.hpp
+++ b/src/gui/widgets/scrollbar.hpp
@@ -71,8 +71,6 @@ public:
* @param scroll 'step size' to scroll.
*/
void scroll(const scroll_mode scroll);
-
- void scroll_by(const int pixels);
/** Is the positioner at the beginning of the scrollbar? */
bool at_begin() const
diff --git a/src/gui/widgets/scrollbar_container.cpp b/src/gui/widgets/scrollbar_container.cpp
index 937e6dbc67f..a401b29226e 100644
--- a/src/gui/widgets/scrollbar_container.cpp
+++ b/src/gui/widgets/scrollbar_container.cpp
@@ -98,15 +98,6 @@ scrollbar_container::scrollbar_container(
connect_signal<event::SDL_WHEEL_RIGHT>(
std::bind(&scrollbar_container::signal_handler_sdl_wheel_right, this, _2, _3),
event::dispatcher::back_post_child);
-
- connect_signal<event::SDL_TOUCH_MOTION>(
- std::bind(&scrollbar_container::signal_handler_sdl_touch_motion,
- this,
- _2,
- _3,
- _5,
- _6),
- event::dispatcher::back_post_child);
}
void scrollbar_container::layout_initialize(const bool full_initialization)
@@ -768,7 +759,7 @@ void scrollbar_container::finalize_setup()
}
/***** Setup the content *****/
- content_ = build_single_widget_instance<spacer>("spacer");
+ content_ = build_single_widget_instance<spacer>();
// TODO: possibly move this unique_ptr casting functionality to a helper function.
content_grid_.reset(dynamic_cast<grid*>(get_grid().swap_child("_content_grid", content_, true).release()));
@@ -1187,39 +1178,4 @@ void scrollbar_container::signal_handler_sdl_wheel_right(const event::ui_event e
}
}
-void
-scrollbar_container::signal_handler_sdl_touch_motion(const event::ui_event event,
- bool& handled,
- const point& position,
- const point& distance)
-{
- (void) position;
- DBG_GUI_E << LOG_HEADER << event << ".\n";
-
- bool is_scrollbar_moved = false;
-
- if (horizontal_scrollbar_grid_ && horizontal_scrollbar_) {
-
- if(horizontal_scrollbar_grid_->get_visible() == widget::visibility::visible) {
- horizontal_scrollbar_->scroll_by(-distance.x);
- is_scrollbar_moved = true;
- }
- }
-
- if (vertical_scrollbar_grid_ && vertical_scrollbar_) {
-
- if(vertical_scrollbar_grid_->get_visible() == widget::visibility::visible) {
- vertical_scrollbar_->scroll_by(-distance.y);
- is_scrollbar_moved = true;
- }
- }
-
- if (is_scrollbar_moved) {
- scrollbar_moved();
- handled = true;
- }
-}
-
-
-
} // namespace gui2
diff --git a/src/gui/widgets/scrollbar_container.hpp b/src/gui/widgets/scrollbar_container.hpp
index 3b47fb7dc45..5f74ad44033 100644
--- a/src/gui/widgets/scrollbar_container.hpp
+++ b/src/gui/widgets/scrollbar_container.hpp
@@ -43,9 +43,7 @@ class scrollbar_container : public container_base
friend struct implementation::builder_scroll_label;
friend struct implementation::builder_scrollbar_panel;
-#ifndef GUI2_EXPERIMENTAL_LISTBOX
friend class listbox;
-#endif
friend class tree_view;
friend struct scrollbar_container_implementation;
@@ -542,8 +540,6 @@ private:
void signal_handler_sdl_wheel_down(const event::ui_event event, bool& handled);
void signal_handler_sdl_wheel_left(const event::ui_event event, bool& handled);
void signal_handler_sdl_wheel_right(const event::ui_event event, bool& handled);
- void signal_handler_sdl_touch_motion(const event::ui_event event, bool& handled,
- const point& position, const point& distance);
public:
scrollbar_base* horizontal_scrollbar()
diff --git a/src/gui/widgets/slider.cpp b/src/gui/widgets/slider.cpp
index 872804efddf..e1c9d16aaae 100644
--- a/src/gui/widgets/slider.cpp
+++ b/src/gui/widgets/slider.cpp
@@ -239,7 +239,7 @@ void slider::signal_handler_left_button_up(const event::ui_event event, bool& ha
static t_string default_value_label_generator(const std::vector<t_string>& value_labels, int item_position, int max)
{
- assert(int(value_labels.size()) == max);
+ assert(static_cast<int>(value_labels.size()) == max);
assert(item_position < max && item_position >= 0);
return value_labels[item_position];
}
diff --git a/src/gui/widgets/status_label_helper.hpp b/src/gui/widgets/status_label_helper.hpp
index 8225d2c3d46..35c3c344602 100644
--- a/src/gui/widgets/status_label_helper.hpp
+++ b/src/gui/widgets/status_label_helper.hpp
@@ -20,7 +20,6 @@
#include "gui/widgets/styled_widget.hpp"
#include "utils/functional.hpp"
-#include "utils/type_trait_aliases.hpp"
namespace gui2
{
@@ -28,7 +27,7 @@ namespace gui2
* Default value getter for selectable widgets (like toggle buttons)
*/
template<typename T>
-static inline utils::enable_if_t<std::is_base_of<selectable_item, T>::value, std::string>
+static inline std::enable_if_t<std::is_base_of<selectable_item, T>::value, std::string>
default_status_value_getter(T& w)
{
return w.get_value_bool() ? _("yes") : _("no");
@@ -38,7 +37,7 @@ default_status_value_getter(T& w)
* Default value getter for integer-based widgets (like sliders)
*/
template<typename T>
-static inline utils::enable_if_t<std::is_base_of<integer_selector, T>::value, std::string>
+static inline std::enable_if_t<std::is_base_of<integer_selector, T>::value, std::string>
default_status_value_getter(T& w)
{
return w.get_value_label();
diff --git a/src/gui/widgets/styled_widget.hpp b/src/gui/widgets/styled_widget.hpp
index a1a308ac694..6ed3d6d0c0f 100644
--- a/src/gui/widgets/styled_widget.hpp
+++ b/src/gui/widgets/styled_widget.hpp
@@ -458,10 +458,11 @@ private:
}
/**
- * Contains a helper cache for the rendering.
+ * Text renderer object used for size calculations.
*
- * Creating a pango_text object is quite expensive and is done on various
- * occasions so it's cached here.
+ * Note this is *not* used to actually render any text, only to get the dimensions of the text for
+ * layout purposes. The actual text rendering happens in the canvas. This is kept as a class member
+ * since creating a pango_text object is quite expensive.
*
* @todo Maybe if still too slow we might also copy this cache to the
* canvas so it can reuse our results, but for now it seems fast enough.
diff --git a/src/gui/widgets/text_box.cpp b/src/gui/widgets/text_box.cpp
index 72f089fc5c4..5e756cd5cfe 100644
--- a/src/gui/widgets/text_box.cpp
+++ b/src/gui/widgets/text_box.cpp
@@ -242,7 +242,7 @@ void text_box::delete_selection()
start -= len;
}
- utf8::string tmp = get_value();
+ std::string tmp = get_value();
set_value(utf8::erase(tmp, start, len));
set_cursor(start, false);
}
diff --git a/src/gui/widgets/text_box_base.cpp b/src/gui/widgets/text_box_base.cpp
index bae9a11a87c..1f13e87284e 100644
--- a/src/gui/widgets/text_box_base.cpp
+++ b/src/gui/widgets/text_box_base.cpp
@@ -150,7 +150,7 @@ void text_box_base::set_cursor(const size_t offset, const bool select)
}
}
-void text_box_base::insert_char(const utf8::string& unicode)
+void text_box_base::insert_char(const std::string& unicode)
{
delete_selection();
@@ -193,7 +193,7 @@ void text_box_base::copy_selection(const bool mouse)
}
unsigned end, start = selection_start_;
- const utf8::string txt = text_.text();
+ const std::string txt = text_.text();
if(selection_length_ > 0) {
end = utf8::index(txt, start + selection_length_);
@@ -422,7 +422,7 @@ void text_box_base::handle_key_delete(SDL_Keymod /*modifier*/, bool& handled)
fire(event::NOTIFY_MODIFIED, *this, nullptr);
}
-void text_box_base::handle_commit(bool& handled, const utf8::string& unicode)
+void text_box_base::handle_commit(bool& handled, const std::string& unicode)
{
DBG_GUI_E << LOG_SCOPE_HEADER << '\n';
@@ -444,7 +444,7 @@ void text_box_base::handle_commit(bool& handled, const utf8::string& unicode)
/**
* SDL_TEXTEDITING handler. See example at https://wiki.libsdl.org/Tutorials/TextInput
*/
-void text_box_base::handle_editing(bool& handled, const utf8::string& unicode, int32_t start, int32_t len)
+void text_box_base::handle_editing(bool& handled, const std::string& unicode, int32_t start, int32_t len)
{
if(unicode.size() > 1 || unicode[0] != 0) {
handled = true;
diff --git a/src/gui/widgets/text_box_base.hpp b/src/gui/widgets/text_box_base.hpp
index a7e201482e3..7f41e74b715 100644
--- a/src/gui/widgets/text_box_base.hpp
+++ b/src/gui/widgets/text_box_base.hpp
@@ -185,7 +185,7 @@ protected:
*
* @param unicode The unicode value of the character to insert.
*/
- virtual void insert_char(const utf8::string& unicode);
+ virtual void insert_char(const std::string& unicode);
/**
* Deletes the character.
@@ -481,9 +481,9 @@ private:
protected:
virtual void handle_commit(bool& handled,
- const utf8::string& unicode);
+ const std::string& unicode);
virtual void handle_editing(bool& handled,
- const utf8::string& unicode,
+ const std::string& unicode,
int32_t start,
int32_t length);
@@ -511,7 +511,7 @@ private:
void signal_handler_sdl_text_input(const event::ui_event event,
bool& handled,
- const utf8::string& unicode,
+ const std::string& unicode,
int32_t start,
int32_t len);
diff --git a/src/gui/widgets/tree_view.cpp b/src/gui/widgets/tree_view.cpp
index 0895a1ff234..7183244faa3 100644
--- a/src/gui/widgets/tree_view.cpp
+++ b/src/gui/widgets/tree_view.cpp
@@ -74,7 +74,7 @@ std::pair<tree_view_node::ptr_t, int> tree_view::remove_node(tree_view_node* nod
tree_view_node::node_children_vector& siblings = node->parent_node_->children_;
auto node_itor = std::find_if(siblings.begin(), siblings.end(),
- [node](const std::unique_ptr<tree_view_node>& c) { return c.get() == node; }
+ [node](const tree_view_node::ptr_t& c) { return c.get() == node; }
);
assert(node_itor != siblings.end());
diff --git a/src/gui/widgets/tree_view_node.hpp b/src/gui/widgets/tree_view_node.hpp
index 4893567d9c7..ee7ad29e75f 100644
--- a/src/gui/widgets/tree_view_node.hpp
+++ b/src/gui/widgets/tree_view_node.hpp
@@ -16,6 +16,7 @@
#include "gui/widgets/widget.hpp"
#include "gui/widgets/grid.hpp"
+
#include <memory>
namespace gui2
@@ -34,7 +35,7 @@ class tree_view_node : public widget
friend class tree_view;
public:
- using ptr_t = std::unique_ptr<tree_view_node>;
+ using ptr_t = std::shared_ptr<tree_view_node>;
using node_children_vector = std::vector<ptr_t>;
bool operator==(const tree_view_node& node)
diff --git a/src/gui/widgets/unit_preview_pane.cpp b/src/gui/widgets/unit_preview_pane.cpp
index 9d38adf3484..6e6a4efee17 100644
--- a/src/gui/widgets/unit_preview_pane.cpp
+++ b/src/gui/widgets/unit_preview_pane.cpp
@@ -122,10 +122,10 @@ static inline std::string get_hp_tooltip(const utils::string_map& res, const std
const int res_def = 100 - get(resist.first, false);
if(res_att == res_def) {
- line << "<span color='" << unit_helper::resistance_color(res_def) << "'>" << utils::signed_percent(res_def) << "</span>";
+ line << "<span color='" << unit_helper::resistance_color(res_def) << "'>\t" << utils::signed_percent(res_def) << "</span>";
} else {
- line << "<span color='" << unit_helper::resistance_color(res_att) << "'>" << utils::signed_percent(res_att) << "</span>" << "/"
- << "<span color='" << unit_helper::resistance_color(res_def) << "'>" << utils::signed_percent(res_def) << "</span>";
+ line << "<span color='" << unit_helper::resistance_color(res_att) << "'>\t" << utils::signed_percent(res_att) << "</span>" << "/"
+ << "<span color='" << unit_helper::resistance_color(res_def) << "'>" << utils::signed_percent(res_def) << "</span>";
att_def_diff = true;
}
@@ -167,8 +167,6 @@ static inline std::string get_mp_tooltip(int total_movement, std::function<int (
}
}
-
-
for(const terrain_movement& tm: terrain_moves)
{
tooltip << '\n' << font::unicode_bullet << " " << tm.name << ": ";
@@ -257,7 +255,7 @@ void unit_preview_pane::set_displayed_type(const unit_type& type)
+ ")";
}
- mods += "~SCALE_INTO_SHARP(144,144)" + image_mods_;
+ mods += "~XBRZ(2)~SCALE_INTO_SHARP(144,144)" + image_mods_;
icon_type_->set_label((type.icon().empty() ? type.image() : type.icon()) + mods);
}
@@ -401,7 +399,7 @@ void unit_preview_pane::set_displayed_unit(const unit& u)
mods += "~BLIT(" + overlay + ")";
}
- mods += "~SCALE_INTO_SHARP(144,144)" + image_mods_;
+ mods += "~XBRZ(2)~SCALE_INTO_SHARP(144,144)" + image_mods_;
icon_type_->set_label(u.absolute_image() + mods);
}
diff --git a/src/gui/widgets/window.cpp b/src/gui/widgets/window.cpp
index bd01af315c9..20b63ab67fe 100644
--- a/src/gui/widgets/window.cpp
+++ b/src/gui/widgets/window.cpp
@@ -1406,12 +1406,12 @@ void window::signal_handler_sdl_key_down(const event::ui_event event,
void window::signal_handler_message_show_tooltip(const event::ui_event event,
bool& handled,
- event::message& message)
+ const event::message& message)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
- event::message_show_tooltip& request
- = dynamic_cast<event::message_show_tooltip&>(message);
+ const event::message_show_tooltip& request
+ = dynamic_cast<const event::message_show_tooltip&>(message);
dialogs::tip::show(tooltip_.id, request.message, request.location, request.source_rect);
@@ -1420,12 +1420,12 @@ void window::signal_handler_message_show_tooltip(const event::ui_event event,
void window::signal_handler_message_show_helptip(const event::ui_event event,
bool& handled,
- event::message& message)
+ const event::message& message)
{
DBG_GUI_E << LOG_HEADER << ' ' << event << ".\n";
- event::message_show_helptip& request
- = dynamic_cast<event::message_show_helptip&>(message);
+ const event::message_show_helptip& request
+ = dynamic_cast<const event::message_show_helptip&>(message);
dialogs::tip::show(helptip_.id, request.message, request.location, request.source_rect);
diff --git a/src/gui/widgets/window.hpp b/src/gui/widgets/window.hpp
index f4a96f49d17..9c52387bd54 100644
--- a/src/gui/widgets/window.hpp
+++ b/src/gui/widgets/window.hpp
@@ -756,11 +756,11 @@ private:
void signal_handler_message_show_tooltip(const event::ui_event event,
bool& handled,
- event::message& message);
+ const event::message& message);
void signal_handler_message_show_helptip(const event::ui_event event,
bool& handled,
- event::message& message);
+ const event::message& message);
void signal_handler_request_placement(const event::ui_event event,
bool& handled);
diff --git a/src/halo.cpp b/src/halo.cpp
index d38a1a3eb49..2c4d313cb1a 100644
--- a/src/halo.cpp
+++ b/src/halo.cpp
@@ -508,12 +508,8 @@ halo_record::~halo_record()
std::shared_ptr<halo_impl> man = my_manager_.lock();
- if (man) {
- try {
- man->remove(id_);
- } catch (std::exception & e) {
- std::cerr << "Caught an exception in halo::halo_record destructor: \n" << e.what() << std::endl;
- } catch (...) {}
+ if(man) {
+ man->remove(id_);
}
}
diff --git a/src/hash.cpp b/src/hash.cpp
index 4763e8a89e8..5931ab682f9 100644
--- a/src/hash.cpp
+++ b/src/hash.cpp
@@ -47,7 +47,7 @@ std::string hexencode_hash(const std::array<uint8_t, len>& input) {
std::ostringstream sout;
sout << std::hex;
for(uint8_t c : input) {
- sout << int(c);
+ sout << static_cast<int>(c);
}
return sout.str();
}
diff --git a/src/help/help.cpp b/src/help/help.cpp
index 246e0e248a2..1b77802e716 100644
--- a/src/help/help.cpp
+++ b/src/help/help.cpp
@@ -234,13 +234,10 @@ void show_help(const section &toplevel_sec,
CVideo::delay(10);
}
}
- catch (parse_error& /*e*/) {
- // Disabled due to issue #2587
-#if 0
+ catch (parse_error& e) {
std::stringstream msg;
msg << _("Parse error when parsing help text: ") << "'" << e.message << "'";
gui2::show_transient_message("", msg.str());
-#endif
}
}
diff --git a/src/help/help_browser.cpp b/src/help/help_browser.cpp
index b9244403f86..9aff175fcfd 100644
--- a/src/help/help_browser.cpp
+++ b/src/help/help_browser.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_browser.hpp b/src/help/help_browser.hpp
index 97fe8450267..702f1007db1 100644
--- a/src/help/help_browser.hpp
+++ b/src/help/help_browser.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_impl.cpp b/src/help/help_impl.cpp
index 4ac9b8fd177..f7a7af5a90b 100644
--- a/src/help/help_impl.cpp
+++ b/src/help/help_impl.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -23,7 +23,7 @@
#include "gettext.hpp" // for _, gettext, N_
#include "help/help_topic_generators.hpp"
#include "hotkey/hotkey_command.hpp" // for is_scope_active, etc
-#include "picture.hpp" // for get_image, locator
+#include "picture.hpp" // for get_image, locator
#include "log.hpp" // for LOG_STREAM, logger, etc
#include "utils/make_enum.hpp" // for operator<<
#include "map/map.hpp" // for gamemap
@@ -34,7 +34,7 @@
#include "sdl/surface.hpp" // for surface
#include "serialization/string_utils.hpp" // for split, quoted_split, etc
#include "serialization/unicode_cast.hpp" // for unicode_cast
-#include "serialization/unicode_types.hpp" // for char_t, etc
+#include "serialization/utf8_exception.hpp" // for char_t, etc
#include "terrain/terrain.hpp" // for terrain_type
#include "terrain/translation.hpp" // for operator==, ter_list, etc
#include "terrain/type_data.hpp" // for terrain_type_data, etc
@@ -361,28 +361,11 @@ std::vector<topic> generate_time_of_day_topics(const bool /*sort_generated*/)
std::vector<topic> topics;
std::stringstream toplevel;
- // HACK: Wesnoth 1.14 only, to avoid breaking a string freeze in the middle
- // of the RC phase. The string already exists in the wesnoth-help
- // (WML) textdomain and it's used for the help sections tree on the
- // left. It was supposed to be used here as well but someone forgot
- // to mark the string translatable. Future versions will just use the
- // regular textdomain for this file.
- const std::string& tod_schedule_heading =
- translation::dsgettext("wesnoth-help", "Time of Day Schedule");
-
if (! resources::tod_manager) {
- toplevel << _("Only available during a scenario.");
- topics.emplace_back(tod_schedule_heading, "..schedule", toplevel.str());
+ toplevel << N_("Only available during a scenario.");
+ topics.emplace_back("Time of Day Schedule", "..schedule", toplevel.str());
return topics;
}
-
- // HACK: Wesnoth 1.14 only, to avoid breaking a string freeze in the middle
- // of the RC phase. The string already exists in the wesnoth-lib
- // textdomain and it's used for a similar purpose in the Editor UI.
- // Future versions will just use the regular textdomain for this file.
- const std::string& lawful_bonus_label =
- translation::dsgettext("wesnoth-lib", "Lawful Bonus:");
-
const std::vector<time_of_day>& times = resources::tod_manager->times();
for (const time_of_day& time : times)
{
@@ -395,13 +378,13 @@ std::vector<topic> generate_time_of_day_topics(const bool /*sort_generated*/)
text << image << '\n' <<
time.description.str() << '\n' <<
- lawful_bonus_label << ' ' << time.lawful_bonus << '\n' <<
- '\n' << make_link(_("Schedule"), "..schedule");
+ "Lawful Bonus: " << time.lawful_bonus << '\n' <<
+ '\n' << make_link(N_("Schedule"), "..schedule");
topics.emplace_back(time.name.str(), id, text.str());
}
- topics.emplace_back(tod_schedule_heading, "..schedule", toplevel.str());
+ topics.emplace_back("Time of Day Schedule", "..schedule", toplevel.str());
return topics;
}
@@ -1381,9 +1364,9 @@ std::string get_first_word(const std::string &s)
if (ch == utf8::iterator::end(re))
return re;
- ucs4::char_t firstchar = *ch;
+ char32_t firstchar = *ch;
if (font::is_cjk_char(firstchar)) {
- re = unicode_cast<utf8::string>(firstchar);
+ re = unicode_cast<std::string>(firstchar);
}
return re;
}
diff --git a/src/help/help_impl.hpp b/src/help/help_impl.hpp
index 29732838fbd..107fc2c33a8 100644
--- a/src/help/help_impl.hpp
+++ b/src/help/help_impl.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_menu.cpp b/src/help/help_menu.cpp
index c5488f6d6be..24478f35379 100644
--- a/src/help/help_menu.cpp
+++ b/src/help/help_menu.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_menu.hpp b/src/help/help_menu.hpp
index 0089525f724..de2dcb45474 100644
--- a/src/help/help_menu.hpp
+++ b/src/help/help_menu.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_text_area.cpp b/src/help/help_text_area.cpp
index 22550419b5a..cac86ef7aff 100644
--- a/src/help/help_text_area.cpp
+++ b/src/help/help_text_area.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_text_area.hpp b/src/help/help_text_area.hpp
index dcd689a8e60..89d7eb81a11 100644
--- a/src/help/help_text_area.hpp
+++ b/src/help/help_text_area.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/help/help_topic_generators.cpp b/src/help/help_topic_generators.cpp
index d565110f450..e30f8eb2439 100644
--- a/src/help/help_topic_generators.cpp
+++ b/src/help/help_topic_generators.cpp
@@ -231,7 +231,7 @@ std::string terrain_topic_generator::operator()() const {
//Typedef to help with formatting list of traits
-//Maps localized trait name to trait help topic ID
+// Maps localized trait name to trait help topic ID
typedef std::pair<std::string, std::string> trait_data;
//Helper function for printing a list of trait data
@@ -410,7 +410,7 @@ std::string unit_topic_generator::operator()() const {
std::vector<trait_data> random_traits;
int must_have_nameless_traits = 0;
- for (const config & trait : traits) {
+ for(const config& trait : traits) {
const std::string& male_name = trait["male_name"].str();
const std::string& female_name = trait["female_name"].str();
std::string trait_name;
@@ -752,6 +752,7 @@ std::string unit_topic_generator::operator()() const {
} else {
str << "<format>color=white text='" << font::unicode_figure_dash << "'</format>";
}
+
markup = str.str();
str.str(clear_stringstream);
if (m.defense_cap) {
@@ -826,8 +827,6 @@ std::string unit_topic_generator::operator()() const {
return ss.str();
}
-
-
void unit_topic_generator::push_header(std::vector< item > &row, const std::string& name) const {
row.emplace_back(bold(name), font::line_width(name, normal_font_size, TTF_STYLE_BOLD));
}
diff --git a/src/help/help_topic_generators.hpp b/src/help/help_topic_generators.hpp
index 188b3bb36b8..9c1704d0ee0 100644
--- a/src/help/help_topic_generators.hpp
+++ b/src/help/help_topic_generators.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/hotkey/command_executor.cpp b/src/hotkey/command_executor.cpp
index 033f2d1479b..e50ef608c18 100644
--- a/src/hotkey/command_executor.cpp
+++ b/src/hotkey/command_executor.cpp
@@ -331,9 +331,6 @@ bool command_executor::do_execute_command(const hotkey_command& cmd, int /*inde
case HOTKEY_SELECT_AND_ACTION:
select_and_action();
break;
- case HOTKEY_TOUCH_HEX:
- touch_hex();
- break;
case HOTKEY_ACCELERATED:
toggle_accelerated_speed();
break;
@@ -407,8 +404,7 @@ void command_executor::show_menu(const std::vector<config>& items_arg, int xloc,
{
SDL_Rect pos {xloc, yloc, 1, 1};
gui2::dialogs::drop_down_menu mmenu(pos, items, -1, true, false); // TODO: last value should be variable
- mmenu.show();
- if(mmenu.get_retval() == gui2::retval::OK) {
+ if(mmenu.show()) {
res = mmenu.selected_item();
}
} // This will kill the dialog.
@@ -528,19 +524,6 @@ void command_executor::get_menu_images(display& disp, std::vector<config>& items
void mbutton_event(const SDL_Event& event, command_executor* executor)
{
event_queue(event, executor);
-
- /* Run mouse events immediately.
-
- This is necessary because the sidebar doesn't allow set_button_state() to be called after a
- button has received the mouse press event but before it has received the mouse release event.
- When https://github.com/wesnoth/wesnoth/pull/2872 delayed the processing of input events,
- set_button_state() ended up being called at such a time. However, if we run the event handlers
- now, the button (if any) hasn't received the press event yet and we can call set_button_state()
- safely.
-
- See https://github.com/wesnoth/wesnoth/issues/2884 */
-
- run_events(executor);
}
void jbutton_event(const SDL_Event& event, command_executor* executor)
@@ -568,16 +551,14 @@ void keyup_event(const SDL_Event&, command_executor* executor)
void run_events(command_executor* executor)
{
if(!executor) return;
- bool commands_ran = executor->run_queued_commands();
- if(commands_ran) {
- executor->set_button_state();
- }
+ executor->run_queued_commands();
}
static void event_queue(const SDL_Event& event, command_executor* executor)
{
if (!executor) return;
executor->queue_command(event);
+ executor->set_button_state();
}
void command_executor::queue_command(const SDL_Event& event, int index)
@@ -596,7 +577,7 @@ void command_executor::queue_command(const SDL_Event& event, int index)
bool keypress = (event.type == SDL_KEYDOWN || event.type == SDL_TEXTINPUT) &&
!press_event_sent_;
bool press = keypress ||
- (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_FINGERDOWN);
+ (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_MOUSEBUTTONDOWN);
bool release = event.type == SDL_KEYUP;
if(press) {
LOG_HK << "sending press event (keypress = " <<
@@ -663,39 +644,6 @@ void command_executor::execute_command_wrap(const command_executor::queued_comma
}
}
-// Removes duplicate commands caused by both SDL_KEYDOWN and SDL_TEXTINPUT triggering hotkeys.
-// See https://github.com/wesnoth/wesnoth/issues/1736
-std::vector<command_executor::queued_command> command_executor::filter_command_queue()
-{
- std::vector<queued_command> filtered_commands;
-
- /** A command plus "key released" flag. Otherwise, we will filter out key releases that are preceded by a keypress. */
- using command_with_keyrelease = std::pair<const hotkey_command*, bool>;
- std::set<command_with_keyrelease> seen_commands;
-
- for(const queued_command& cmd : command_queue_) {
- command_with_keyrelease command_key(cmd.command, cmd.release);
- if(seen_commands.find(command_key) == seen_commands.end()) {
- seen_commands.insert(command_key);
- filtered_commands.push_back(cmd);
- }
- }
-
- command_queue_.clear();
-
- return filtered_commands;
-}
-
-bool command_executor::run_queued_commands()
-{
- std::vector<queued_command> commands = filter_command_queue();
- for(const queued_command& cmd : commands) {
- execute_command_wrap(cmd);
- }
-
- return !commands.empty();
-}
-
void command_executor_default::set_button_state()
{
display& disp = get_display();
@@ -758,6 +706,37 @@ void command_executor_default::set_button_state()
}
}
+// Removes duplicate commands caused by both SDL_KEYDOWN and SDL_TEXTINPUT triggering hotkeys.
+// See https://github.com/wesnoth/wesnoth/issues/1736
+std::vector<command_executor::queued_command> command_executor::filter_command_queue()
+{
+ std::vector<queued_command> filtered_commands;
+
+ /** A command plus "key released" flag. Otherwise, we will filter out key releases that are preceded by a keypress. */
+ using command_with_keyrelease = std::pair<const hotkey_command*, bool>;
+ std::set<command_with_keyrelease> seen_commands;
+
+ for(const queued_command& cmd : command_queue_) {
+ command_with_keyrelease command_key(cmd.command, cmd.release);
+ if(seen_commands.find(command_key) == seen_commands.end()) {
+ seen_commands.insert(command_key);
+ filtered_commands.push_back(cmd);
+ }
+ }
+
+ command_queue_.clear();
+
+ return filtered_commands;
+}
+
+void command_executor::run_queued_commands()
+{
+ std::vector<queued_command> commands = filter_command_queue();
+ for(const queued_command& cmd : commands) {
+ execute_command_wrap(cmd);
+ }
+}
+
void command_executor_default::recalculate_minimap()
{
get_display().recalculate_minimap();
diff --git a/src/hotkey/command_executor.hpp b/src/hotkey/command_executor.hpp
index 8cece34e725..2377c869479 100644
--- a/src/hotkey/command_executor.hpp
+++ b/src/hotkey/command_executor.hpp
@@ -103,7 +103,6 @@ public:
virtual void deselect_hex() {}
virtual void move_action() {}
virtual void select_and_action() {}
- virtual void touch_hex() {}
virtual void left_mouse_click() {}
virtual void right_mouse_click() {}
virtual void toggle_accelerated_speed() {}
@@ -136,7 +135,7 @@ public:
virtual bool can_execute_command(const hotkey_command& command, int index=-1) const = 0;
void queue_command(const SDL_Event& event, int index = -1);
- bool run_queued_commands();
+ void run_queued_commands();
void execute_quit_command()
{
const hotkey_command& quit_hotkey = hotkey_command::get_command_by_command(hotkey::HOTKEY_QUIT_GAME);
diff --git a/src/hotkey/hotkey_command.cpp b/src/hotkey/hotkey_command.cpp
index d3c049abd19..019fd04ebd4 100644
--- a/src/hotkey/hotkey_command.cpp
+++ b/src/hotkey/hotkey_command.cpp
@@ -75,7 +75,6 @@ std::array<hotkey_command_temp, HOTKEY_NULL - 1> master_hotkey_list {{
{ HOTKEY_DESELECT_HEX, "deselecthex", N_("Deselect Hex"), false, scope_game, HKCAT_MAP, "" },
{ HOTKEY_MOVE_ACTION, "moveaction", N_("Move/Attack"), false, scope_game, HKCAT_UNITS, "" },
{ HOTKEY_SELECT_AND_ACTION, "selectmoveaction", N_("Select/Move/Attack"), false, scope_game, HKCAT_UNITS, "" },
- { HOTKEY_TOUCH_HEX, "touchhex", N_("Touch"), false, scope_game, HKCAT_UNITS, "" },
{ HOTKEY_ANIMATE_MAP, "animatemap", N_("Animate Map"), false, scope_game | scope_editor, HKCAT_MAP, "" },
{ HOTKEY_CYCLE_UNITS, "cycle", N_("Next Unit"), false, scope_game, HKCAT_UNITS, "" },
{ HOTKEY_CYCLE_BACK_UNITS, "cycleback", N_("Previous Unit"), false, scope_game, HKCAT_UNITS, "" },
diff --git a/src/hotkey/hotkey_command.hpp b/src/hotkey/hotkey_command.hpp
index 39441ee7b09..09fb3fefc68 100644
--- a/src/hotkey/hotkey_command.hpp
+++ b/src/hotkey/hotkey_command.hpp
@@ -65,7 +65,7 @@ enum HOTKEY_COMMAND {
// Controls
HOTKEY_SELECT_HEX, HOTKEY_DESELECT_HEX,
- HOTKEY_MOVE_ACTION, HOTKEY_SELECT_AND_ACTION, HOTKEY_TOUCH_HEX,
+ HOTKEY_MOVE_ACTION, HOTKEY_SELECT_AND_ACTION,
// Camera movement
HOTKEY_SCROLL_UP, HOTKEY_SCROLL_DOWN, HOTKEY_SCROLL_LEFT, HOTKEY_SCROLL_RIGHT,
diff --git a/src/hotkey/hotkey_handler.cpp b/src/hotkey/hotkey_handler.cpp
index 7a75e9298fc..b190a526943 100644
--- a/src/hotkey/hotkey_handler.cpp
+++ b/src/hotkey/hotkey_handler.cpp
@@ -122,11 +122,6 @@ void play_controller::hotkey_handler::select_and_action() {
mouse_handler_.select_or_action(browse());
}
-void play_controller::hotkey_handler::touch_hex() {
- auto touched_hex = gui()->mouseover_hex();
- mouse_handler_.touch_action(touched_hex, false);
-}
-
void play_controller::hotkey_handler::move_action(){
mouse_handler_.move_action(browse());
}
@@ -312,7 +307,6 @@ bool play_controller::hotkey_handler::can_execute_command(const hotkey::hotkey_c
case hotkey::HOTKEY_DESELECT_HEX:
case hotkey::HOTKEY_MOVE_ACTION:
case hotkey::HOTKEY_SELECT_AND_ACTION:
- case hotkey::HOTKEY_TOUCH_HEX:
case hotkey::HOTKEY_MINIMAP_CODING_TERRAIN:
case hotkey::HOTKEY_MINIMAP_CODING_UNIT:
case hotkey::HOTKEY_MINIMAP_DRAW_UNITS:
diff --git a/src/hotkey/hotkey_handler.hpp b/src/hotkey/hotkey_handler.hpp
index bc18fe1a4ce..ae15c113952 100644
--- a/src/hotkey/hotkey_handler.hpp
+++ b/src/hotkey/hotkey_handler.hpp
@@ -88,7 +88,6 @@ public:
virtual void left_mouse_click() override;
virtual void move_action() override;
virtual void select_and_action() override;
- virtual void touch_hex() override;
virtual void select_hex() override;
virtual void deselect_hex() override;
virtual void right_mouse_click() override;
diff --git a/src/hotkey/hotkey_item.cpp b/src/hotkey/hotkey_item.cpp
index 0a908f07ae6..d033570c2b8 100644
--- a/src/hotkey/hotkey_item.cpp
+++ b/src/hotkey/hotkey_item.cpp
@@ -40,11 +40,6 @@ namespace hotkey {
hotkey_list hotkeys_;
config default_hotkey_cfg_;
-namespace {
- const int TOUCH_MOUSE_INDEX = 255;
- const char TOUCH_MOUSE_STRING[] = "255";
-};
-
static unsigned int sdl_get_mods()
{
unsigned int mods;
@@ -201,11 +196,7 @@ hotkey_ptr load_from_config(const config& cfg)
if (!mouse_cfg.empty()) {
auto mouse = std::make_shared<hotkey_mouse>();
base = std::dynamic_pointer_cast<hotkey_base>(mouse);
- if (mouse_cfg == TOUCH_MOUSE_STRING) {
- mouse->set_button(TOUCH_MOUSE_INDEX);
- } else {
- mouse->set_button(cfg["button"].to_int());
- }
+ mouse->set_button(cfg["button"].to_int());
}
// TODO: add joystick support back
#if 0
@@ -263,10 +254,7 @@ hotkey_ptr load_from_config(const config& cfg)
bool hotkey_mouse::matches_helper(const SDL_Event &event) const
{
- if (event.type != SDL_MOUSEBUTTONUP
- && event.type != SDL_MOUSEBUTTONDOWN
- && event.type != SDL_FINGERDOWN
- && event.type != SDL_FINGERUP) {
+ if (event.type != SDL_MOUSEBUTTONUP && event.type != SDL_MOUSEBUTTONDOWN) {
return false;
}
@@ -275,11 +263,11 @@ bool hotkey_mouse::matches_helper(const SDL_Event &event) const
return false;
}
- if (event.button.which == SDL_TOUCH_MOUSEID) {
- return button_ == TOUCH_MOUSE_INDEX;
+ if (event.button.button != button_) {
+ return false;
}
- return event.button.button == button_;
+ return true;
}
const std::string hotkey_mouse::get_name_helper() const
@@ -317,7 +305,7 @@ bool hotkey_keyboard::matches_helper(const SDL_Event &event) const
if(text == ":" || text == "`") {
mods = mods & ~KMOD_SHIFT;
}
- return text_ == text && utf8::size(utf8::string(event.text.text)) == 1 && mods == mod_;
+ return text_ == text && utf8::size(std::string(event.text.text)) == 1 && mods == mod_;
}
return false;
diff --git a/src/image_modifications.cpp b/src/image_modifications.cpp
index 74ed66ad134..c8d9710f77d 100644
--- a/src/image_modifications.cpp
+++ b/src/image_modifications.cpp
@@ -232,6 +232,8 @@ public:
{
add_input(inputs, "x");
add_input(inputs, "y");
+ add_input(inputs, "u");
+ add_input(inputs, "v");
add_input(inputs, "red");
add_input(inputs, "green");
add_input(inputs, "blue");
@@ -259,6 +261,10 @@ public:
return variant(w);
} else if(key == "height") {
return variant(h);
+ } else if(key == "u") {
+ return variant(p.x / static_cast<float>(w));
+ } else if(key == "v") {
+ return variant(p.y / static_cast<float>(h));
}
return variant();
@@ -407,18 +413,20 @@ surface blit_modification::operator()(const surface& src) const
throw imod_exception(sstr);
}
- if(surf_->w + x_ < 0) {
+ if(surf_->w + x_ > src->w) {
std::stringstream sstr;
sstr << "~BLIT(): offset and width '"
- << x_ + surf_->w << "' less than zero no blitting performed.\n";
+ << x_ + surf_->w << "' larger than destination image's width '"
+ << src->w << "' no blitting performed.\n";
throw imod_exception(sstr);
}
- if(surf_->h + y_ < 0) {
+ if(surf_->h + y_ > src->h) {
std::stringstream sstr;
sstr << "~BLIT(): offset and height '"
- << y_ + surf_->h << "' less than zero no blitting performed.\n";
+ << y_ + surf_->h << "' larger than destination image's height '"
+ << src->h << "' no blitting performed.\n";
throw imod_exception(sstr);
}
@@ -1013,12 +1021,7 @@ REGISTER_MOD_PARSER(BLIT, args)
ERR_DP << "no arguments passed to the ~BLIT() function" << std::endl;
return nullptr;
}
-
- if(s > 3){
- ERR_DP << "too many arguments passed to the ~BLIT() function" << std::endl;
- return nullptr;
- }
-
+
int x = 0, y = 0;
if(s == 3) {
@@ -1026,6 +1029,11 @@ REGISTER_MOD_PARSER(BLIT, args)
y = lexical_cast_default<int>(param[2]);
}
+ if(x < 0 || y < 0) {
+ ERR_DP << "negative position arguments in ~BLIT() function" << std::endl;
+ return nullptr;
+ }
+
const image::locator img(param[0]);
std::stringstream message;
message << "~BLIT():";
diff --git a/src/joystick.cpp b/src/joystick.cpp
index a2f7657ae2f..a370b3315e4 100644
--- a/src/joystick.cpp
+++ b/src/joystick.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2011 - 2018 by Fabian Mueller
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -133,7 +133,7 @@ std::pair<double, double> joystick_manager::get_mouse_axis_pair() {
thrust = get_thrusta_axis();
}
- const int radius = round_double(sqrt(pow(values.first, 2.0f) + pow(values.second, 2.0f)));
+ const int radius = std::round(std::sqrt(std::pow(values.first, 2.0f) + std::pow(values.second, 2.0f)));
const int deadzone = preferences::joystick_mouse_deadzone();
const double multiplier = 1.0 + thrust;
@@ -142,7 +142,7 @@ std::pair<double, double> joystick_manager::get_mouse_axis_pair() {
// TODO do some math to normalize over the value - deadzone.
//const double relation = std::abs( (double)values.first / (double)values.second );
- //const int range_x = values.first - round_double(relation * deadzone);
+ //const int range_x = values.first - std::round(relation * deadzone);
//const int range_y = values.second - ((1.0 - relation) * deadzone);
//double x_value = ((double)(values.first - deadzone) / (double)(32768 - deadzone)) *
@@ -169,7 +169,7 @@ std::pair<double, double> joystick_manager::get_scroll_axis_pair() {
thrust = get_thrusta_axis();
}
- const int radius = round_double(sqrt(pow(values.first, 2.0f) + pow(values.second, 2.0f)));
+ const int radius = std::round(std::sqrt(std::pow(values.first, 2.0f) + std::pow(values.second, 2.0f)));
const int deadzone = preferences::joystick_scroll_deadzone();
const double multiplier = 1.0 + thrust;
@@ -218,7 +218,7 @@ std::pair<double, double> joystick_manager::get_cursor_polar_coordinates() {
std::pair<double, double> joystick_manager::get_polar_coordinates(int joystick_xaxis, int xaxis, int joystick_yaxis, int yaxis) {
const std::pair<int, int> values = get_axis_pair(joystick_xaxis, xaxis, joystick_yaxis, yaxis);
- const double radius = (sqrt(pow(values.first, 2.0f) + pow(values.second, 2.0f))) / 32768.0;
+ const double radius = (std::sqrt(std::pow(values.first, 2.0f) + std::pow(values.second, 2.0f))) / 32768.0;
const double angle = (atan2(
static_cast<double>(values.second)
, static_cast<double>(values.first))) * 180.0 / pi<double>();
@@ -275,7 +275,7 @@ bool joystick_manager::update_highlighted_hex(map_location& highlighted_hex, con
const int x_axis = values.first;
const int y_axis = values.second;
- //const int radius = round_double(sqrt(pow(x_axis, 2.0f) + pow(y_axis, 2.0f)));
+ //const int radius = std::round(std::(std::pow(x_axis, 2.0f) + std::pow(y_axis, 2.0f)));
// const int deadzone = preferences::joystick_cursor_deadzone();
//const int threshold2 = 10*threshold;
@@ -285,7 +285,7 @@ bool joystick_manager::update_highlighted_hex(map_location& highlighted_hex, con
//const bool greater_threshold2 = radius > threshold2;
highlighted_hex = selected_hex;
- highlighted_hex.add(round_double(x_axis / 3200), round_double(y_axis / 3200));
+ highlighted_hex.add(std::round(x_axis / 3200), std::round(y_axis / 3200));
//if (!greater_threshold) {
// counter_ = 0;
@@ -310,7 +310,7 @@ bool joystick_manager::update_highlighted_hex(map_location& highlighted_hex) {
const int x_axis = values.first;
const int y_axis = values.second;
- const int radius = round_double(sqrt(pow(x_axis, 2.0f) + pow(y_axis, 2.0f)));
+ const int radius = std::round(std::sqrt(std::pow(x_axis, 2.0f) + std::pow(y_axis, 2.0f)));
const int deadzone = preferences::joystick_cursor_deadzone();
const int threshold = deadzone + preferences::joystick_cursor_threshold();
diff --git a/src/joystick.hpp b/src/joystick.hpp
index 64db962e543..aea18d6c345 100644
--- a/src/joystick.hpp
+++ b/src/joystick.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2011 - 2018 by Fabian Mueller
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/lexical_cast.hpp b/src/lexical_cast.hpp
index 181d3768eef..b1327c84408 100644
--- a/src/lexical_cast.hpp
+++ b/src/lexical_cast.hpp
@@ -47,8 +47,6 @@
#include "global.hpp"
-#include "utils/type_trait_aliases.hpp"
-
#include <cstdlib>
#include <limits>
#include <string>
@@ -171,7 +169,7 @@ struct lexical_caster<
std::string
, From
, void
- , utils::enable_if_t<std::is_integral<utils::remove_pointer_t<From>>::value>
+ , std::enable_if_t<std::is_integral<std::remove_pointer_t<From>>::value>
>
{
std::string operator()(From value, boost::optional<std::string>) const
@@ -196,7 +194,7 @@ struct lexical_caster<
long long
, From
, void
- , utils::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
+ , std::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
>
{
long long operator()(From value, boost::optional<long long> fallback) const
@@ -251,8 +249,8 @@ template <class To, class From>
struct lexical_caster<
To
, From
- , utils::enable_if_t<std::is_integral<To>::value && std::is_signed<To>::value && !std::is_same<To, long long>::value>
- , utils::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
+ , std::enable_if_t<std::is_integral<To>::value && std::is_signed<To>::value && !std::is_same<To, long long>::value>
+ , std::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
>
{
To operator()(From value, boost::optional<To> fallback) const
@@ -276,7 +274,7 @@ template <class To>
struct lexical_caster<
To
, std::string
- , utils::enable_if_t<std::is_integral<To>::value && std::is_signed<To>::value && !std::is_same<To, long long>::value>
+ , std::enable_if_t<std::is_integral<To>::value && std::is_signed<To>::value && !std::is_same<To, long long>::value>
>
{
To operator()(const std::string& value, boost::optional<To> fallback) const
@@ -309,8 +307,8 @@ template <class To, class From>
struct lexical_caster<
To
, From
- , utils::enable_if_t<std::is_floating_point<To>::value>
- , utils::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
+ , std::enable_if_t<std::is_floating_point<To>::value>
+ , std::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
>
{
To operator()(From value, boost::optional<To> fallback) const
@@ -334,7 +332,7 @@ template <class To>
struct lexical_caster<
To
, std::string
- , utils::enable_if_t<std::is_floating_point<To>::value>
+ , std::enable_if_t<std::is_floating_point<To>::value>
>
{
To operator()(const std::string& value, boost::optional<To> fallback) const
@@ -379,7 +377,7 @@ struct lexical_caster<
unsigned long long
, From
, void
- , utils::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
+ , std::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
>
{
unsigned long long operator()(From value, boost::optional<unsigned long long> fallback) const
@@ -435,8 +433,8 @@ template <class To, class From>
struct lexical_caster<
To
, From
- , utils::enable_if_t<std::is_unsigned<To>::value && !std::is_same<To, unsigned long long>::value>
- , utils::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
+ , std::enable_if_t<std::is_unsigned<To>::value && !std::is_same<To, unsigned long long>::value>
+ , std::enable_if_t<boost::mpl::has_key<boost::mpl::set<char*, const char*> , From>::value>
>
{
To operator()(From value, boost::optional<To> fallback) const
@@ -460,7 +458,7 @@ template <class To>
struct lexical_caster<
To
, std::string
- , utils::enable_if_t<std::is_unsigned<To>::value>
+ , std::enable_if_t<std::is_unsigned<To>::value>
>
{
To operator()(const std::string& value, boost::optional<To> fallback) const
diff --git a/src/log.cpp b/src/log.cpp
index f645b3498af..3f5a92cd88c 100644
--- a/src/log.cpp
+++ b/src/log.cpp
@@ -28,7 +28,6 @@
#include <ctime>
#include "global.hpp"
-#include "utils/io.hpp"
namespace {
@@ -176,7 +175,7 @@ bool broke_strict() {
std::string get_timestamp(const time_t& t, const std::string& format) {
std::ostringstream ss;
- ss << utils::put_time(std::localtime(&t), format.c_str());
+ ss << std::put_time(std::localtime(&t), format.c_str());
return ss.str();
}
diff --git a/src/log_windows.cpp b/src/log_windows.cpp
index cd29fe61b9f..6d54c793926 100644
--- a/src/log_windows.cpp
+++ b/src/log_windows.cpp
@@ -28,8 +28,6 @@
#include <boost/algorithm/string/predicate.hpp>
-#include "utils/io.hpp"
-
#ifndef UNICODE
#define UNICODE
#endif
@@ -112,7 +110,7 @@ std::string unique_log_filename()
o << log_file_prefix;
const time_t cur = time(nullptr);
- o << utils::put_time(std::localtime(&cur), "%Y%m%d-%H%M%S-");
+ o << std::put_time(std::localtime(&cur), "%Y%m%d-%H%M%S-");
o << GetCurrentProcessId() << log_file_suffix;
diff --git a/src/map/location.hpp b/src/map/location.hpp
index 8463a41b28a..2d4d4cb533c 100644
--- a/src/map/location.hpp
+++ b/src/map/location.hpp
@@ -19,8 +19,6 @@
class config;
class variable_set;
-#include "global.hpp"
-
#include <array>
#include <cmath>
#include <cstdlib>
diff --git a/src/map/map.cpp b/src/map/map.cpp
index 7bfbffaf42f..186fdd23b7e 100644
--- a/src/map/map.cpp
+++ b/src/map/map.cpp
@@ -206,61 +206,38 @@ std::string gamemap::write() const
{
return t_translation::write_game_map(tiles_, starting_positions_, t_translation::coordinate{ border_size(), border_size() }) + "\n";
}
-namespace
-{
- struct overlay_rule
- {
- t_translation::ter_list old_;
- t_translation::ter_list new_;
- terrain_type_data::merge_mode mode_;
- boost::optional<t_translation::terrain_code> terrain_;
- bool use_old_;
- bool replace_if_failed_;
-
- overlay_rule()
- : old_()
- , new_()
- , mode_(terrain_type_data::BOTH)
- , terrain_()
- , use_old_(false)
- , replace_if_failed_(false)
- {
- }
- };
-}
-void gamemap::overlay(const gamemap& m, const config& rules_cfg, map_location loc)
+void gamemap::overlay(const gamemap& m, map_location loc, const std::vector<overlay_rule>& rules, bool m_is_odd, bool ignore_special_locations)
{
- int xpos = loc.x;
- int ypos = loc.y;
- //const config::const_child_itors &rules = rules_cfg.child_range("rule");
- std::vector<overlay_rule> rules(rules_cfg.child_count("rule"));
- for(size_t i = 0; i <rules.size(); ++i)
- {
- const config& cfg = rules_cfg.child("rule", i);
- rules[i].old_ = t_translation::read_list(cfg["old"].str());
- rules[i].new_ = t_translation::read_list(cfg["new"].str());
- rules[i].mode_ = cfg["layer"] == "base" ? terrain_type_data::BASE : cfg["layer"] == "overlay" ? terrain_type_data::OVERLAY : terrain_type_data::BOTH;
- const t_translation::ter_list& terrain = t_translation::read_list(cfg["terrain"].str());
- if(!terrain.empty()) {
- rules[i].terrain_ = terrain[0];
- }
- rules[i].use_old_ = cfg["use_old"].to_bool();
- rules[i].replace_if_failed_ = cfg["replace_if_failed"].to_bool();
- }
+ int xpos = loc.wml_x();
+ int ypos = loc.wml_y();
- const int xstart = std::max<int>(-border_size(), -xpos - border_size());
- const int ystart = std::max<int>(-border_size(), -ypos - border_size() - ((xpos & 1) ? 1 : 0));
- const int xend = std::min<int>(m.w() + border_size(), w() + border_size() - xpos);
- const int yend = std::min<int>(m.h() + border_size(), h() + border_size() - ypos);
+ const int xstart = std::max<int>(0, -xpos);
+ const int xend = std::min<int>(m.total_width(), total_width() -xpos);
+ const int xoffset = xpos;
- for(int x1 = xstart; x1 < xend; ++x1) {
- for(int y1 = ystart; y1 < yend; ++y1) {
- const int x2 = x1 + xpos;
- const int y2 = y1 + ypos + ((xpos & 1) && (x1 & 1) ? 1 : 0);
+ const int ystart_even = std::max<int>(0, -ypos);
+ const int yend_even = std::min<int>(m.total_height(), total_height() - ypos);
+ const int yoffset_even = ypos;
- const t_translation::terrain_code t = m[{x1,y1}];
- const t_translation::terrain_code current = (*this)[{x2, y2}];
+ const int ystart_odd = std::max<int>(0, -ypos +(xpos & 1) -(m_is_odd ? 1 : 0));
+ const int yend_odd = std::min<int>(m.total_height(), total_height() - ypos +(xpos & 1) -(m_is_odd ? 1 : 0));
+ const int yoffset_odd = ypos -(xpos & 1) + (m_is_odd ? 1 : 0);
+
+ for(int x1 = xstart; x1 != xend; ++x1) {
+ int ystart, yend, yoffset;
+ if(x1 & 1) {
+ ystart = ystart_odd , yend = yend_odd , yoffset = yoffset_odd;
+ }
+ else {
+ ystart = ystart_even, yend = yend_even, yoffset = yoffset_even;
+ }
+ for(int y1 = ystart; y1 != yend; ++y1) {
+ const int x2 = x1 + xoffset;
+ const int y2 = y1 + yoffset;//ypos + ((xpos & 1) && (x1 & 1) ? 1 : 0);
+
+ const t_translation::terrain_code t = m.tiles_.get(x1,y1);
+ const t_translation::terrain_code current = tiles_.get(x2, y2);
if(t == t_translation::FOGGED || t == t_translation::VOID_TERRAIN) {
continue;
@@ -281,22 +258,38 @@ void gamemap::overlay(const gamemap& m, const config& rules_cfg, map_location lo
}
if (!rule) {
- set_terrain(map_location(x2, y2), t);
+ set_terrain(map_location(x2, y2, wml_loc()), t);
}
else if(!rule->use_old_) {
- set_terrain(map_location(x2, y2), rule->terrain_ ? *rule->terrain_ : t , rule->mode_, rule->replace_if_failed_);
+ set_terrain(map_location(x2, y2, wml_loc()), rule->terrain_ ? *rule->terrain_ : t , rule->mode_, rule->replace_if_failed_);
}
}
}
- if (!rules_cfg["ignore_special_locations"].to_bool(false)) {
+ if (!ignore_special_locations) {
for(auto& pair : m.starting_positions_.left) {
+
+ int x = pair.second.wml_x();
+ int y = pair.second.wml_y();
+ if(x & 1) {
+ if(x < xstart || x >= xend || y < ystart_odd || y >= yend_odd) {
+ continue;
+ }
+ }
+ else {
+ if(x < xstart || x >= xend || y < ystart_even || y >= yend_even) {
+ continue;
+ }
+ }
+ int x_new = x + xoffset;
+ int y_new = y + ((x & 1 ) ? yoffset_odd : yoffset_even);
+ map_location pos_new = map_location(x_new, y_new, wml_loc());
+
starting_positions_.left.erase(pair.first);
- starting_positions_.insert(starting_positions::value_type(pair.first, t_translation::coordinate(pair.second.x + xpos, pair.second.y + ypos+ ((xpos & 1) && (pair.second.x & 1) ? 1 : 0))));
+ starting_positions_.insert(starting_positions::value_type(pair.first, t_translation::coordinate(pos_new.x, pos_new.y)));
}
}
}
-
t_translation::terrain_code gamemap::get_terrain(const map_location& loc) const
{
@@ -449,16 +442,3 @@ std::vector<map_location> gamemap::parse_location_range(const std::string &x, co
}
return res;
}
-
-void gamemap::add_fog_border()
-{
- t_translation::ter_map tiles_new(tiles_.w + 1, tiles_.h + 1);
- for (int x = 0, x_end = tiles_new.w; x != x_end; ++x) {
- for (int y = 0, y_end = tiles_new.h; y != y_end; ++y) {
- tiles_new.get(x, y) = (x == 0 || y == 0) ? t_translation::VOID_TERRAIN : tiles_.get(x - 1, y - 1);
- }
- }
- ++w_;
- ++h_;
- tiles_ = tiles_new;
-}
diff --git a/src/map/map.hpp b/src/map/map.hpp
index ccb2e330d7a..d5aa4f45c58 100644
--- a/src/map/map.hpp
+++ b/src/map/map.hpp
@@ -22,6 +22,8 @@ class config;
#include "terrain/translation.hpp"
#include "terrain/type_data.hpp"
+#include <boost/optional.hpp>
+
//class terrain_type_data; Can't forward declare because of enum
/**
@@ -83,8 +85,29 @@ public:
std::string write() const;
+ struct overlay_rule
+ {
+ t_translation::ter_list old_;
+ t_translation::ter_list new_;
+ terrain_type_data::merge_mode mode_;
+ boost::optional<t_translation::terrain_code> terrain_;
+ bool use_old_;
+ bool replace_if_failed_;
+
+ overlay_rule()
+ : old_()
+ , new_()
+ , mode_(terrain_type_data::BOTH)
+ , terrain_()
+ , use_old_(false)
+ , replace_if_failed_(false)
+ {
+
+ }
+ };
+
/** Overlays another map onto this one at the given position. */
- void overlay(const gamemap& m, const config& rules, map_location loc);
+ void overlay(const gamemap& m, map_location loc, const std::vector<overlay_rule>& rules = std::vector<overlay_rule>(), bool is_odd = false, bool ignore_special_locations = false);
/** Effective map width. */
int w() const { return w_; }
@@ -205,7 +228,7 @@ public:
}
}
}
- void add_fog_border();
+
protected:
t_translation::ter_map tiles_;
diff --git a/src/menu_events.cpp b/src/menu_events.cpp
index 69e8ebcc86d..8ff1889c84a 100644
--- a/src/menu_events.cpp
+++ b/src/menu_events.cpp
@@ -88,10 +88,10 @@ static lg::log_domain log_engine("engine");
namespace events
{
-menu_handler::menu_handler(game_display* gui, play_controller& pc, const config& game_config)
+menu_handler::menu_handler(game_display* gui, play_controller& pc)
: gui_(gui)
, pc_(pc)
- , game_config_(game_config)
+ , game_config_(game_config_manager::get()->game_config())
, textbox_info_()
, last_search_()
, last_search_hit_()
@@ -275,9 +275,7 @@ void menu_handler::recruit(int side_num, const map_location& last_hex)
gui2::dialogs::unit_recruit dlg(sample_units, board().get_team(side_num));
- dlg.show();
-
- if(dlg.get_retval() == gui2::retval::OK) {
+ if(dlg.show()) {
map_location recruit_hex = last_hex;
do_recruit(sample_units[dlg.get_selected_index()]->id(), side_num, recruit_hex);
}
@@ -373,9 +371,7 @@ void menu_handler::recall(int side_num, const map_location& last_hex)
gui2::dialogs::unit_recall dlg(recall_list_team, current_team);
- dlg.show();
-
- if(dlg.get_retval() != gui2::retval::OK) {
+ if(!dlg.show()) {
return;
}
@@ -442,7 +438,7 @@ void menu_handler::show_enemy_moves(bool ignore_units, int side_num)
// Compute enemy movement positions
for(auto& u : units()) {
- bool invisible = u.invisible(u.get_location(), gui_->get_disp_context());
+ bool invisible = u.invisible(u.get_location());
if(board().get_team(side_num).is_enemy(u.side()) && !gui_->fogged(u.get_location()) && !u.incapacitated()
&& !invisible) {
@@ -589,7 +585,7 @@ void menu_handler::goto_leader(int side_num)
{
unit_map::const_iterator i = units().find_leader(side_num);
const display_context& dc = gui_->get_disp_context();
- if(i != units().end() && i->is_visible_to_team(dc.get_team(gui_->viewing_side()), dc, false)) {
+ if(i != units().end() && i->is_visible_to_team(dc.get_team(gui_->viewing_side()), false)) {
gui_->scroll_to_tile(i->get_location(), game_display::WARP);
}
}
@@ -1354,7 +1350,7 @@ void menu_handler::do_search(const std::string& new_search)
name.begin(), name.end(), last_search_.begin(), last_search_.end(), chars_equal_insensitive)
!= name.end()) {
if(!teams()[gui_->viewing_team()].is_enemy(ui->side())
- || !ui->invisible(ui->get_location(), gui_->get_disp_context())) {
+ || !ui->invisible(ui->get_location())) {
found = true;
}
}
diff --git a/src/menu_events.hpp b/src/menu_events.hpp
index 55402ef40fb..a6878ec0367 100644
--- a/src/menu_events.hpp
+++ b/src/menu_events.hpp
@@ -45,7 +45,7 @@ namespace events
class menu_handler : private chat_handler
{
public:
- menu_handler(game_display* gui, play_controller& pc, const config& game_config);
+ menu_handler(game_display* gui, play_controller& pc);
virtual ~menu_handler();
gui::floating_textbox& get_textbox();
diff --git a/src/mouse_events.cpp b/src/mouse_events.cpp
index d76049908a5..33ada83911d 100644
--- a/src/mouse_events.cpp
+++ b/src/mouse_events.cpp
@@ -21,13 +21,11 @@
#include "config.hpp" // for config
#include "cursor.hpp" // for set, CURSOR_TYPE::NORMAL, etc
#include "game_board.hpp" // for game_board, etc
-#include "game_config.hpp" // for red_to_green
#include "game_events/pump.hpp" // for fire
#include "gettext.hpp" // for _
#include "gui/dialogs/transient_message.hpp" // for show_transient_message
#include "gui/dialogs/unit_attack.hpp" // for unit_attack
#include "gui/widgets/settings.hpp" // for new_widgets
-#include "gui/widgets/retval.hpp" // for enum
#include "language.hpp" // for string_table, symbol_table
#include "log.hpp" // for LOG_STREAM, logger, etc
#include "map/map.hpp" // for gamemap
@@ -91,285 +89,9 @@ void mouse_handler::set_side(int side_number)
int mouse_handler::drag_threshold() const
{
- // TODO: Use physical screen size.
return 14;
}
-void mouse_handler::touch_motion(int x, int y, const bool browse, bool update, map_location new_hex)
-{
- // Frankensteining from mouse_motion(), as it has a lot in common, but a lot of differences too.
- // Copy-pasted from everywhere. TODO: generalize the two.
- SDL_GetMouseState(&x,&y);
-
- // This is from mouse_handler_base::mouse_motion_default()
- tooltips::process(x, y);
-
- if(simple_warp_) {
- return;
- }
-
- if(minimap_scrolling_) {
- const map_location& mini_loc = gui().minimap_location_on(x,y);
- if(mini_loc.valid()) {
- if(mini_loc != last_hex_) {
- last_hex_ = mini_loc;
- gui().scroll_to_tile(mini_loc,display::WARP,false);
- }
- return;
- } else {
- // clicking outside of the minimap will end minimap scrolling
- minimap_scrolling_ = false;
- }
- }
-
- // Fire the drag & drop only after minimal drag distance
- // While we check the mouse buttons state, we also grab fresh position data.
- int mx = drag_from_x_; // some default value to prevent unlikely SDL bug
- int my = drag_from_y_;
- if(is_dragging() && !dragging_started_) {
- if(dragging_touch_) {
- SDL_GetMouseState(&mx, &my);
- const double drag_distance = std::pow(static_cast<double>(drag_from_x_- mx), 2)
- + std::pow(static_cast<double>(drag_from_y_- my), 2);
- if(drag_distance > drag_threshold()*drag_threshold()) {
- dragging_started_ = true;
- }
- }
- }
-
- // Not-so-smooth panning
- const auto found_unit = find_unit(selected_hex_);
- bool selected_hex_has_my_unit = found_unit.valid() && found_unit.get_shared_ptr()->side() == side_num_;
- if((browse || !found_unit.valid()) && is_dragging() && dragging_started_) {
- SDL_GetMouseState(&mx, &my);
-
- if(sdl::point_in_rect(x, y, gui().map_area())) {
- int dx = drag_from_x_ - mx;
- int dy = drag_from_y_ - my;
-
- gui().scroll(dx, dy);
- drag_from_x_ = mx;
- drag_from_y_ = my;
- }
- return;
- }
-
- // now copy-pasting mouse_handler::mouse_motion()
-
- game_board & board = pc_.gamestate().board_;
-
- if(new_hex == map_location::null_location())
- new_hex = gui().hex_clicked_on(x,y);
-
- if(new_hex != last_hex_) {
- update = true;
- if( pc_.get_map_const().on_board(last_hex_) ) {
- // we store the previous hexes used to propose attack direction
- previous_hex_ = last_hex_;
- // the hex of the selected unit is also "free"
- { // start planned unit map scope
- wb::future_map_if_active raii;
- if(last_hex_ == selected_hex_ || !find_unit(last_hex_)) {
- previous_free_hex_ = last_hex_;
- }
- } // end planned unit map scope
- }
- last_hex_ = new_hex;
- }
-
- if(reachmap_invalid_) update = true;
-
- if(!update) return;
-
- if(reachmap_invalid_) {
- reachmap_invalid_ = false;
- if(!current_paths_.destinations.empty() && !show_partial_move_) {
- { // start planned unit map scope
- wb::future_map_if_active planned_unit_map;
- selected_hex_has_my_unit = found_unit.valid();
- } // end planned unit map scope
- if(selected_hex_.valid() && selected_hex_has_my_unit) {
- // FIXME: vic: why doesn't this trigger when touch-dragging an unselected unit?
- // reselect the unit without firing events (updates current_paths_)
- select_hex(selected_hex_, true);
- }
- // we do never deselect here, mainly because of canceled attack-move
- }
- }
-
- // reset current_route_ and current_paths if not valid anymore
- // we do it before cursor selection, because it uses current_paths_
- if( !pc_.get_map_const().on_board(new_hex) ) {
- current_route_.steps.clear();
- gui().set_route(nullptr);
- pc_.get_whiteboard()->erase_temp_move();
- }
-
- if(unselected_paths_) {
- unselected_paths_ = false;
- current_paths_ = pathfind::paths();
- gui().unhighlight_reach();
- } else if(over_route_) {
- over_route_ = false;
- current_route_.steps.clear();
- gui().set_route(nullptr);
- pc_.get_whiteboard()->erase_temp_move();
- }
-
- gui().highlight_hex(new_hex);
- pc_.get_whiteboard()->on_mouseover_change(new_hex);
-
- unit_map::iterator selected_unit;
- unit_map::iterator mouseover_unit;
- map_location attack_from;
-
- { // start planned unit map scope
- wb::future_map_if_active planned_unit_map;
- selected_unit = found_unit;
- mouseover_unit = find_unit(new_hex);
-
- // we search if there is an attack possibility and where
- attack_from = current_unit_attacks_from(new_hex);
-
- //see if we should show the normal cursor, the movement cursor, or
- //the attack cursor
- //If the cursor is on WAIT, we don't change it and let the setter
- //of this state end it
- if (cursor::get() != cursor::WAIT) {
- if (selected_unit &&
- selected_unit->side() == side_num_ &&
- !selected_unit->incapacitated() && !browse)
- {
- if (attack_from.valid()) {
- cursor::set(dragging_started_ ? cursor::ATTACK_DRAG : cursor::ATTACK);
- }
- else if (!mouseover_unit &&
- current_paths_.destinations.contains(new_hex))
- {
- // Is this where left-drag cursor changes? Test.
- cursor::set(dragging_started_ ? cursor::MOVE_DRAG : cursor::MOVE);
- } else {
- // selected unit can't attack or move there
- cursor::set(cursor::NORMAL);
- }
- } else {
- // no selected unit or we can't move it
-
- if ( selected_hex_.valid() && mouseover_unit
- && mouseover_unit->side() == side_num_ ) {
- // empty hex field selected and unit on our site under the cursor
- cursor::set(dragging_started_ ? cursor::MOVE_DRAG : cursor::MOVE);
- } else {
- cursor::set(cursor::NORMAL);
- }
- }
- }
- } // end planned unit map scope
-
- // show (or cancel) the attack direction indicator
- if(attack_from.valid() && (!browse || pc_.get_whiteboard()->is_active())) {
- gui().set_attack_indicator(attack_from, new_hex);
- } else {
- gui().clear_attack_indicator();
- }
-
- unit_ptr un; //will later point to unit at mouseover_hex_
-
- // the destination is the pointed hex or the adjacent hex
- // used to attack it
- map_location dest;
- unit_map::const_iterator dest_un;
- { // start planned unit map scope
- wb::future_map_if_active raii;
- if (attack_from.valid()) {
- dest = attack_from;
- dest_un = find_unit(dest);
- } else {
- dest = new_hex;
- dest_un = find_unit(new_hex);
- }
-
- if(dest == selected_hex_ || dest_un) {
- current_route_.steps.clear();
- gui().set_route(nullptr);
- pc_.get_whiteboard()->erase_temp_move();
- }
- else if (!current_paths_.destinations.empty() &&
- board.map().on_board(selected_hex_) && board.map().on_board(new_hex))
- {
- if (selected_unit && !selected_unit->incapacitated()) {
- // Show the route from selected unit to mouseover hex
- current_route_ = get_route(&*selected_unit, dest, viewing_team());
-
- pc_.get_whiteboard()->create_temp_move();
-
- if(!browse) {
- gui().set_route(&current_route_);
- }
- }
- }
-
- if(board.map().on_board(selected_hex_)
- && !selected_unit
- && mouseover_unit.valid()
- && mouseover_unit) {
- // Show the route from selected hex to mouseover unit
- current_route_ = get_route(&*mouseover_unit, selected_hex_, viewing_team());
-
- pc_.get_whiteboard()->create_temp_move();
-
- if(!browse) {
- gui().set_route(&current_route_);
- }
- } else if (!selected_unit) {
- current_route_.steps.clear();
- gui().set_route(nullptr);
- pc_.get_whiteboard()->erase_temp_move();
- }
-
- unit_map::iterator iter = mouseover_unit;
- if (iter)
- un = iter.get_shared_ptr();
- else
- un.reset();
- } //end planned unit map scope
-
- if( (!selected_hex_.valid()) && un && current_paths_.destinations.empty() &&
- !gui().fogged(un->get_location()))
- {
- if (un->side() == side_num_) {
- //unit is on our team, show path if the unit has one
- const map_location go_to = un->get_goto();
- if(board.map().on_board(go_to)) {
- pathfind::marked_route route;
- { // start planned unit map scope
- wb::future_map_if_active raii;
- route = get_route(un.get(), go_to, current_team());
- } // end planned unit map scope
- gui().set_route(&route);
- }
- over_route_ = true;
-
- wb::future_map_if_active raii;
- current_paths_ = pathfind::paths(*un, false, true,
- viewing_team(), path_turns_);
- } else {
- //unit under cursor is not on our team
- //Note: planned unit map must be activated after this is done,
- //since the future state includes changes to units' movement.
- unit_movement_resetter move_reset(*un);
-
- wb::future_map_if_active raii;
- current_paths_ = pathfind::paths(*un, false, true,
- viewing_team(), path_turns_);
- }
-
- unselected_paths_ = true;
- gui().highlight_reach(current_paths_);
- }
-
-}
-
void mouse_handler::mouse_motion(int x, int y, const bool browse, bool update, map_location new_hex)
{
// we ignore the position coming from event handler
@@ -513,8 +235,8 @@ void mouse_handler::mouse_motion(int x, int y, const bool browse, bool update, m
// used to attack it
map_location dest;
unit_map::const_iterator dest_un;
- /* start planned unit map scope*/
- {
+
+ { // start planned unit map scope
wb::future_map_if_active raii;
if(attack_from.valid()) {
dest = attack_from;
@@ -557,14 +279,15 @@ void mouse_handler::mouse_motion(int x, int y, const bool browse, bool update, m
pc_.get_whiteboard()->erase_temp_move();
}
- if(mouseover_unit) {
- un = mouseover_unit.get_shared_ptr();
+ unit_map::iterator iter = mouseover_unit;
+ if(iter) {
+ un = iter.get_shared_ptr();
} else {
un.reset();
}
- } /*end planned unit map scope*/
+ } // end planned unit map scope
- if(!selected_hex_.valid() && un && current_paths_.destinations.empty() && !gui().fogged(un->get_location())) {
+ if((!selected_hex_.valid()) && un && current_paths_.destinations.empty() && !gui().fogged(un->get_location())) {
/*
* Only process unit if toggler not preventing normal unit
* processing. This can happen e.g. if, after activating 'show
@@ -736,12 +459,12 @@ map_location mouse_handler::current_unit_attacks_from(const map_location& loc) c
if(current_paths_.destinations.contains(adj[n])) {
static const size_t NDIRECTIONS = map_location::NDIRECTIONS;
- unsigned int difference = std::abs(int(preferred - n));
+ unsigned int difference = std::abs(static_cast<int>(preferred - n));
if(difference > NDIRECTIONS / 2) {
difference = NDIRECTIONS - difference;
}
- unsigned int second_difference = std::abs(int(second_preferred - n));
+ unsigned int second_difference = std::abs(static_cast<int>(second_preferred - n));
if(second_difference > NDIRECTIONS / 2) {
second_difference = NDIRECTIONS - second_difference;
}
@@ -1007,17 +730,6 @@ void mouse_handler::move_action(bool browse)
}
}
-void mouse_handler::touch_action(const map_location touched_hex, bool browse)
-{
- unit_map::iterator unit = find_unit(touched_hex);
-
- if (touched_hex.valid() && unit.valid() && !unit->get_hidden()) {
- select_or_action(browse);
- } else {
- deselect_hex();
- }
-}
-
void mouse_handler::select_hex(const map_location& hex, const bool browse, const bool highlight, const bool fire_event)
{
selected_hex_ = hex;
@@ -1080,7 +792,7 @@ void mouse_handler::select_hex(const map_location& hex, const bool browse, const
for(unit_map::iterator u = pc_.gamestate().board_.units_.begin(); u != pc_.gamestate().board_.units_.end();
++u) {
- bool invisible = u->invisible(u->get_location(), gui_->get_disp_context());
+ bool invisible = u->invisible(u->get_location());
if(!gui_->fogged(u->get_location()) && !u->incapacitated() && !invisible) {
const pathfind::paths& path =
@@ -1254,7 +966,7 @@ int mouse_handler::fill_weapon_choices(
best = bc_vector.size();
}
- bc_vector.emplace_back(std::move(bc));
+ bc_vector.push_back(std::move(bc));
}
}
@@ -1282,11 +994,9 @@ int mouse_handler::show_attack_dialog(const map_location& attacker_loc, const ma
return -1;
}
- gui2::dialogs::unit_attack dlg(attacker, defender, std::move(bc_vector), best);
-
- dlg.show();
+ gui2::dialogs::unit_attack dlg(attacker, defender, bc_vector, best);
- if(dlg.get_retval() == gui2::retval::OK) {
+ if(dlg.show()) {
return dlg.get_selected_weapon();
}
@@ -1414,7 +1124,7 @@ void mouse_handler::show_attack_options(const unit_map::const_iterator& u)
}
unit_map::const_iterator i = pc_.gamestate().board_.units().find(loc);
- if(!i || !i->is_visible_to_team(cur_team, gui_->get_disp_context(), false)) {
+ if(!i || !i->is_visible_to_team(cur_team, false)) {
continue;
}
@@ -1439,7 +1149,7 @@ bool mouse_handler::unit_in_cycle(unit_map::const_iterator it)
return false;
}
- if(current_team().is_enemy(int(gui().viewing_team() + 1)) && it->invisible(it->get_location(), gui().get_disp_context())) {
+ if(current_team().is_enemy(static_cast<int>(gui().viewing_team() + 1)) && it->invisible(it->get_location())) {
return false;
}
diff --git a/src/mouse_events.hpp b/src/mouse_events.hpp
index c7e5fe80e2a..9b15188a94e 100644
--- a/src/mouse_events.hpp
+++ b/src/mouse_events.hpp
@@ -84,8 +84,6 @@ public:
const bool fire_event = true);
void move_action(bool browse);
-
- void touch_action(const map_location hex, bool browse);
void select_or_action(bool browse);
@@ -132,8 +130,6 @@ protected:
// bool left_click(int x, int y, const bool browse);
bool move_unit_along_current_route();
- void touch_motion(int x, int y, const bool browse, bool update=false, map_location loc = map_location::null_location());
-
void save_whiteboard_attack(const map_location& attacker_loc, const map_location& defender_loc, int weapon_choice);
// fill weapon choices into bc_vector
diff --git a/src/mouse_handler_base.cpp b/src/mouse_handler_base.cpp
index 5a01623550f..d987080ed79 100644
--- a/src/mouse_handler_base.cpp
+++ b/src/mouse_handler_base.cpp
@@ -52,7 +52,6 @@ mouse_handler_base::mouse_handler_base()
: simple_warp_(false)
, minimap_scrolling_(false)
, dragging_left_(false)
- , dragging_touch_(false)
, dragging_started_(false)
, dragging_right_(false)
, drag_from_x_(0)
@@ -66,14 +65,9 @@ mouse_handler_base::mouse_handler_base()
{
}
-bool mouse_handler_base::dragging_started() const
-{
- return dragging_started_;
-}
-
bool mouse_handler_base::is_dragging() const
{
- return dragging_left_ || dragging_right_ || dragging_touch_;
+ return dragging_left_ || dragging_right_;
}
void mouse_handler_base::mouse_motion_event(const SDL_MouseMotionEvent& event, const bool browse)
@@ -81,13 +75,6 @@ void mouse_handler_base::mouse_motion_event(const SDL_MouseMotionEvent& event, c
mouse_motion(event.x, event.y, browse);
}
-void mouse_handler_base::touch_motion_event(const SDL_TouchFingerEvent& event, const bool browse)
-{
- // This is wrong (needs to be scaled from -1..1 to screen size), but it's discarded in touch_motion anyway.
- // Let's not waste CPU cycles.
- touch_motion(event.x, event.y, browse);
-}
-
void mouse_handler_base::mouse_update(const bool browse, map_location loc)
{
int x, y;
@@ -107,7 +94,8 @@ bool mouse_handler_base::mouse_motion_default(int x, int y, bool /*update*/)
// if the game is run in a window, we could miss a LMB/MMB up event
// if it occurs outside our window.
// thus, we need to check if the LMB/MMB is still down
- minimap_scrolling_ = ((SDL_GetMouseState(nullptr, nullptr) & (SDL_BUTTON(SDL_BUTTON_LEFT) | SDL_BUTTON(SDL_BUTTON_MIDDLE))) != 0);
+ minimap_scrolling_ = ((SDL_GetMouseState(nullptr, nullptr) & (SDL_BUTTON(1) | SDL_BUTTON(2))) != 0);
+
if(minimap_scrolling_) {
const map_location& loc = gui().minimap_location_on(x, y);
if(loc.valid()) {
@@ -132,19 +120,12 @@ bool mouse_handler_base::mouse_motion_default(int x, int y, bool /*update*/)
int my = drag_from_y_;
if(is_dragging() && !dragging_started_) {
- Uint32 mouse_state = dragging_left_ || dragging_right_ ? SDL_GetMouseState(&mx, &my) : 0;
-#ifdef MOUSE_TOUCH_EMULATION
- if(dragging_left_ && (mouse_state & SDL_BUTTON(SDL_BUTTON_RIGHT))) {
- // Monkey-patch touch controls again to make them look like left button.
- mouse_state = SDL_BUTTON(SDL_BUTTON_LEFT);
- }
-#endif
- if((dragging_left_ && (mouse_state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0) ||
- (dragging_right_ && (mouse_state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0))
+ if((dragging_left_ && (SDL_GetMouseState(&mx, &my) & SDL_BUTTON_LEFT) != 0) ||
+ (dragging_right_ && (SDL_GetMouseState(&mx, &my) & SDL_BUTTON_RIGHT) != 0))
{
const double drag_distance =
- std::pow(static_cast<double>(drag_from_x_- mx), 2) +
- std::pow(static_cast<double>(drag_from_y_- my), 2);
+ std::pow(static_cast<double>(drag_from_x_ - mx), 2) +
+ std::pow(static_cast<double>(drag_from_y_ - my), 2);
if(drag_distance > drag_threshold() * drag_threshold()) {
dragging_started_ = true;
@@ -166,30 +147,7 @@ void mouse_handler_base::mouse_press(const SDL_MouseButtonEvent& event, const bo
map_location loc = gui().hex_clicked_on(event.x, event.y);
mouse_update(browse, loc);
- static clock_t touch_timestamp = 0;
-
- if(is_touch_click(event)) {
- if (event.state == SDL_PRESSED) {
- cancel_dragging();
- touch_timestamp = clock();
- init_dragging(dragging_touch_);
- left_click(event.x, event.y, browse);
- } else if (event.state == SDL_RELEASED) {
- minimap_scrolling_ = false;
-
- if (!dragging_started_ && touch_timestamp > 0) {
- time_t dt = clock() - touch_timestamp;
- if (dt > CLOCKS_PER_SEC * 3 / 10) {
- right_click(event.x, event.y, browse); // show_menu_ = true;
- }
- } else {
- touch_timestamp = 0;
- }
-
- clear_dragging(event, browse);
- left_mouse_up(event.x, event.y, browse);
- }
- } else if(is_left_click(event)) {
+ if(is_left_click(event)) {
if(event.state == SDL_PRESSED) {
cancel_dragging();
init_dragging(dragging_left_);
@@ -234,7 +192,8 @@ void mouse_handler_base::mouse_press(const SDL_MouseButtonEvent& event, const bo
scroll_started_ = false;
}
}
- if(!dragging_left_ && !dragging_right_ && !dragging_touch_ && dragging_started_) {
+
+ if(!dragging_left_ && !dragging_right_ && dragging_started_) {
dragging_started_ = false;
cursor::set_dragging(false);
}
@@ -244,14 +203,6 @@ void mouse_handler_base::mouse_press(const SDL_MouseButtonEvent& event, const bo
bool mouse_handler_base::is_left_click(const SDL_MouseButtonEvent& event) const
{
-#ifdef MOUSE_TOUCH_EMULATION
- if(event.button == SDL_BUTTON_RIGHT) {
- return true;
- }
-#endif
- if(event.which == SDL_TOUCH_MOUSEID) {
- return false;
- }
return event.button == SDL_BUTTON_LEFT && !command_active();
}
@@ -262,21 +213,7 @@ bool mouse_handler_base::is_middle_click(const SDL_MouseButtonEvent& event) cons
bool mouse_handler_base::is_right_click(const SDL_MouseButtonEvent& event) const
{
-#ifdef MOUSE_TOUCH_EMULATION
- (void) event;
- return false;
-#else
- if(event.which == SDL_TOUCH_MOUSEID) {
- return false;
- }
- return event.button == SDL_BUTTON_RIGHT
- || (event.button == SDL_BUTTON_LEFT && command_active());
-#endif
-}
-
-bool mouse_handler_base::is_touch_click(const SDL_MouseButtonEvent& event) const
-{
- return event.which == SDL_TOUCH_MOUSEID;
+ return event.button == SDL_BUTTON_RIGHT || (event.button == SDL_BUTTON_LEFT && command_active());
}
bool mouse_handler_base::left_click(int x, int y, const bool /*browse*/)
@@ -298,10 +235,6 @@ bool mouse_handler_base::left_click(int x, int y, const bool /*browse*/)
return false;
}
-void mouse_handler_base::touch_action(const map_location /*hex*/, bool /*browse*/)
-{
-}
-
void mouse_handler_base::left_drag_end(int /*x*/, int /*y*/, const bool browse)
{
move_action(browse);
@@ -368,7 +301,6 @@ void mouse_handler_base::cancel_dragging()
{
dragging_started_ = false;
dragging_left_ = false;
- dragging_touch_ = false;
dragging_right_ = false;
cursor::set_dragging(false);
}
@@ -382,13 +314,6 @@ void mouse_handler_base::clear_dragging(const SDL_MouseButtonEvent& event, bool
if(dragging_started_) {
dragging_started_ = false;
-
- if(dragging_touch_) {
- dragging_touch_ = false;
- // Maybe to do: create touch_drag_end(). Do panning and what else there. OTOH, it's fine now.
- left_drag_end(event.x, event.y, browse);
- }
-
if(dragging_left_) {
dragging_left_ = false;
left_drag_end(event.x, event.y, browse);
@@ -401,7 +326,6 @@ void mouse_handler_base::clear_dragging(const SDL_MouseButtonEvent& event, bool
} else {
dragging_left_ = false;
dragging_right_ = false;
- dragging_touch_ = false;
}
}
diff --git a/src/mouse_handler_base.hpp b/src/mouse_handler_base.hpp
index 483128663a4..fd7b329e160 100644
--- a/src/mouse_handler_base.hpp
+++ b/src/mouse_handler_base.hpp
@@ -48,9 +48,6 @@ public:
/** Const version of @ref gui */
virtual const display& gui() const = 0;
-
- /** If mouse/finger has moved far enough to consider it move/swipe, and not a click/touch */
- bool dragging_started() const;
/**
* @return true when the class in the "dragging" state.
@@ -65,8 +62,6 @@ public:
void mouse_motion_event(const SDL_MouseMotionEvent& event, const bool browse);
- void touch_motion_event(const SDL_TouchFingerEvent& event, const bool browse);
-
/** Update the mouse with a fake mouse motion */
void mouse_update(const bool browse, map_location loc);
@@ -90,15 +85,10 @@ public:
int x, int y, const bool browse, bool update = false, map_location new_loc = map_location::null_location())
= 0;
- virtual void touch_motion(
- int x, int y, const bool browse, bool update = false, map_location new_loc = map_location::null_location())
- = 0;
-
virtual void mouse_press(const SDL_MouseButtonEvent& event, const bool browse);
bool is_left_click(const SDL_MouseButtonEvent& event) const;
bool is_middle_click(const SDL_MouseButtonEvent& event) const;
bool is_right_click(const SDL_MouseButtonEvent& event) const;
- bool is_touch_click(const SDL_MouseButtonEvent& event) const;
/** Called when scrolling with the mouse wheel. */
virtual void mouse_wheel(int xscroll, int yscroll, bool browse);
@@ -129,8 +119,6 @@ public:
// Overridden with unit move code elsewhere
}
- virtual void touch_action(const map_location hex, bool browse);
-
/** Called whenever the left mouse drag has "ended". */
virtual void left_drag_end(int /*x*/, int /*y*/, const bool /*browse*/);
@@ -226,9 +214,6 @@ protected:
/** LMB drag init flag */
bool dragging_left_;
- /** Finger drag init flag */
- bool dragging_touch_;
-
/** Actual drag flag */
bool dragging_started_;
diff --git a/src/movetype.cpp b/src/movetype.cpp
index 83a1e5651ad..02ee83da226 100644
--- a/src/movetype.cpp
+++ b/src/movetype.cpp
@@ -515,7 +515,7 @@ void movetype::terrain_info::merge(const config & new_values, bool overwrite)
merged_data_.reset();
// Copy-on-write.
- if ( !data_.unique() ) {
+ if(data_.use_count() != 1) {
data_.reset(new data(*data_));
// We also need to make copies of our fallback and cascade.
// This is to keep the caching manageable, as this means each
@@ -594,7 +594,7 @@ const std::shared_ptr<movetype::terrain_info::data> &
*/
void movetype::terrain_info::make_unique_cascade() const
{
- if ( !data_.unique() )
+ if(data_.use_count() != 1)
// Const hack because this is not really changing the data.
const_cast<terrain_info *>(this)->data_.reset(new data(*data_));
@@ -608,7 +608,7 @@ void movetype::terrain_info::make_unique_cascade() const
*/
void movetype::terrain_info::make_unique_fallback() const
{
- if ( !data_.unique() )
+ if(data_.use_count() != 1)
// Const hack because this is not really changing the data.
const_cast<terrain_info *>(this)->data_.reset(new data(*data_));
diff --git a/src/network_asio.hpp b/src/network_asio.hpp
index e06bc115afb..fceaa5c8d07 100644
--- a/src/network_asio.hpp
+++ b/src/network_asio.hpp
@@ -16,10 +16,6 @@
#ifdef _WIN32
-#if _WIN32_WINNT < _WIN32_WINNT_VISTA
-#define BOOST_ASIO_DISABLE_IOCP
-#endif
-
#ifdef INADDR_ANY
#undef INADDR_ANY
#endif
diff --git a/src/pathfind/astarsearch.cpp b/src/pathfind/astarsearch.cpp
index 48451d22046..8b3fb19d8f1 100644
--- a/src/pathfind/astarsearch.cpp
+++ b/src/pathfind/astarsearch.cpp
@@ -154,7 +154,7 @@ plain_route a_star_search(const map_location& src, const map_location& dst,
if (calc.cost(dst, 0) >= stop_at) {
LOG_PF << "aborted A* search because Start or Dest is invalid\n";
plain_route locRoute;
- locRoute.move_cost = int(calc.getNoPathValue());
+ locRoute.move_cost = static_cast<int>(calc.getNoPathValue());
return locRoute;
}
diff --git a/src/pathfind/pathfind.cpp b/src/pathfind/pathfind.cpp
index b4bcd0dc272..c10cc1d22e4 100644
--- a/src/pathfind/pathfind.cpp
+++ b/src/pathfind/pathfind.cpp
@@ -416,7 +416,7 @@ static void find_routes(
if ( skirmisher && next.moves_left > 0 &&
enemy_zoc(*current_team, next_hex, *viewing_team, see_all) &&
- !skirmisher->get_ability_bool("skirmisher", next_hex, *resources::gameboard) ) {
+ !skirmisher->get_ability_bool("skirmisher", next_hex) ) {
next.moves_left = 0;
}
}
@@ -686,7 +686,7 @@ marked_route mark_route(const plain_route &rt, bool update_move_cost)
++turns;
- bool invisible = u.invisible(*i, *resources::gameboard, false);
+ bool invisible = u.invisible(*i, false);
res.marks[*i] = marked_route::mark(turns, zoc, capture, invisible);
@@ -705,7 +705,7 @@ marked_route mark_route(const plain_route &rt, bool update_move_cost)
}
zoc = enemy_zoc(unit_team, *(i + 1), viewing_team)
- && !u.get_ability_bool("skirmisher", *(i+1), *resources::gameboard);
+ && !u.get_ability_bool("skirmisher", *(i+1));
if (zoc) {
total_costs += movement;
@@ -794,7 +794,7 @@ double shortest_path_calculator::cost(const map_location& loc, const double so_f
// check ZoC
if (!ignore_unit_ && remaining_movement != terrain_cost
&& enemy_zoc(teams_[unit_.side()-1], loc, viewing_team_, see_all_)
- && !unit_.get_ability_bool("skirmisher", loc, *resources::gameboard)) {
+ && !unit_.get_ability_bool("skirmisher", loc)) {
// entering ZoC cost all remaining MP
move_cost += remaining_movement;
} else {
diff --git a/src/pathfind/teleport.cpp b/src/pathfind/teleport.cpp
index 0f56c9ac6bb..7064587fb90 100644
--- a/src/pathfind/teleport.cpp
+++ b/src/pathfind/teleport.cpp
@@ -262,7 +262,7 @@ const teleport_map get_teleport_locations(const unit &u,
{
std::vector<teleport_group> groups;
- if (u.get_ability_bool("teleport", *resources::gameboard)) {
+ if (u.get_ability_bool("teleport")) {
for (const unit_ability & teleport : u.get_abilities("teleport")) {
const int tunnel_count = (teleport.first)->child_count("tunnel");
for(int i = 0; i < tunnel_count; ++i) {
diff --git a/src/persist_var.cpp b/src/persist_var.cpp
index c27e2afd4ba..7e87afce106 100644
--- a/src/persist_var.cpp
+++ b/src/persist_var.cpp
@@ -200,7 +200,7 @@ void verify_and_clear_global_variable(const vconfig &pcfg)
{
bool valid = true;
if (!pcfg.has_attribute("global")) {
- ERR_PERSIST << "[clear_global_variable] missing required attribute \"from_global\"";
+ ERR_PERSIST << "[clear_global_variable] missing required attribute \"global\"";
valid = false;
}
if (!pcfg.has_attribute("namespace")) {
diff --git a/src/picture.cpp b/src/picture.cpp
index 4f5c8bbf3f2..e508815335b 100644
--- a/src/picture.cpp
+++ b/src/picture.cpp
@@ -233,9 +233,6 @@ static int last_index_ = 0;
void flush_cache()
{
-#ifdef _OPENMP
-#pragma omp critical(image_cache)
-#endif //_OPENMP
{
images_.flush();
hexed_images_.flush();
@@ -629,10 +626,17 @@ static surface load_image_sub_file(const image::locator& loc)
try {
surf = (*mod)(surf);
} catch(const image::modification::imod_exception& e) {
+ std::ostringstream ss;
+ ss << "\n";
+
+ for(const std::string& mod : utils::parenthetical_split(loc.get_modifications(), '~')) {
+ ss << "\t" << mod << "\n";
+ }
+
ERR_CFG << "Failed to apply a modification to an image:\n"
- << "Image: " << loc.get_filename() << ".\n"
- << "Modifications: " << loc.get_modifications() << ".\n"
- << "Error: " << e.message;
+ << "Image: " << loc.get_filename() << "\n"
+ << "Modifications: " << ss.str() << "\n"
+ << "Error: " << e.message << "\n";
}
// NOTE: do this *after* applying the mod or you'll get crashes!
@@ -1051,18 +1055,10 @@ surface get_image(const image::locator& i_locator, TYPE type)
}
// return the image if already cached
- bool tmp;
-#ifdef _OPENMP
-#pragma omp critical(image_cache)
-#endif //_OPENMP
- tmp = i_locator.in_cache(*imap);
+ bool tmp = i_locator.in_cache(*imap);
if(tmp) {
- surface result;
-#ifdef _OPENMP
-#pragma omp critical(image_cache)
-#endif //_OPENMP
- result = i_locator.locate_in_cache(*imap);
+ surface result = i_locator.locate_in_cache(*imap);
return result;
}
@@ -1091,9 +1087,6 @@ surface get_image(const image::locator& i_locator, TYPE type)
return res;
}
-#ifdef _OPENMP
-#pragma omp critical(image_cache)
-#endif //_OPENMP
i_locator.add_to_cache(*imap, res);
return res;
@@ -1160,9 +1153,6 @@ surface get_hexmask()
bool is_in_hex(const locator& i_locator)
{
bool result;
-#ifdef _OPENMP
-#pragma omp critical(in_hex_info_)
-#endif //_OPENMP
{
if(i_locator.in_cache(in_hex_info_)) {
result = i_locator.locate_in_cache(in_hex_info_);
diff --git a/src/picture.hpp b/src/picture.hpp
index 65b05000f51..6053de77a85 100644
--- a/src/picture.hpp
+++ b/src/picture.hpp
@@ -16,7 +16,6 @@
#include "map/location.hpp"
#include "terrain/translation.hpp"
-#include "game_config.hpp"
#include <SDL.h>
#include <unordered_map>
diff --git a/src/play_controller.cpp b/src/play_controller.cpp
index a60e4ef463e..2d510f779fb 100644
--- a/src/play_controller.cpp
+++ b/src/play_controller.cpp
@@ -129,8 +129,8 @@ static void clear_resources()
}
play_controller::play_controller(const config& level, saved_game& state_of_game,
- const config& game_config, const ter_data_cache& tdata, bool skip_replay)
- : controller_base(game_config)
+ const ter_data_cache& tdata, bool skip_replay)
+ : controller_base()
, observer()
, quit_confirmation()
, ticks_(SDL_GetTicks())
@@ -142,9 +142,9 @@ play_controller::play_controller(const config& level, saved_game& state_of_game,
, whiteboard_manager_()
, plugins_context_()
, labels_manager_()
- , help_manager_(&game_config)
+ , help_manager_(&game_config_)
, mouse_handler_(nullptr, *this)
- , menu_handler_(nullptr, *this, game_config)
+ , menu_handler_(nullptr, *this)
, hotkey_handler_(new hotkey_handler(*this, saved_game_))
, soundsources_manager_()
, persist_()
@@ -341,7 +341,7 @@ void play_controller::init_managers()
void play_controller::fire_preload()
{
// Run initialization scripts, even if loading from a snapshot.
- gamestate().gamedata_.get_variable("turn_number") = int(turn());
+ gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
pump().fire("preload");
}
@@ -360,10 +360,10 @@ void play_controller::fire_prestart()
pump().fire("prestart");
// prestart event may modify start turn with WML, reflect any changes.
- gamestate().gamedata_.get_variable("turn_number") = int(turn());
+ gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
}
-void play_controller::refresh_objectives()
+void play_controller::refresh_objectives() const
{
const config cfg("side", gui_->viewing_side());
gamestate().lua_kernel_->run_wml_action("show_objectives", vconfig(cfg),
@@ -374,9 +374,12 @@ void play_controller::fire_start()
{
gamestate().gamedata_.set_phase(game_data::START);
pump().fire("start");
+
skip_story_ = false; // Show [message]s from now on even with --campaign-skip-story
+
// start event may modify start turn with WML, reflect any changes.
- gamestate().gamedata_.get_variable("turn_number") = int(turn());
+ gamestate().gamedata_.get_variable("turn_number") = static_cast<int>(turn());
+
refresh_objectives();
check_objectives();
// prestart and start events may modify the initial gold amount,
@@ -635,7 +638,7 @@ void play_controller::tab()
for (const unit& u : gamestate().board_.units()){
const map_location& loc = u.get_location();
if(!gui_->fogged(loc) &&
- !(gamestate().board_.teams()[gui_->viewing_team()].is_enemy(u.side()) && u.invisible(loc, gui_->get_disp_context())))
+ !(gamestate().board_.teams()[gui_->viewing_team()].is_enemy(u.side()) && u.invisible(loc)))
dictionary.insert(u.name());
}
//TODO List map labels
@@ -724,7 +727,7 @@ bool play_controller::is_team_visible(int team_num, bool observer) const
int play_controller::find_last_visible_team() const
{
- assert(current_side() <= int(gamestate().board_.teams().size()));
+ assert(current_side() <= static_cast<int>(gamestate().board_.teams().size()));
const int num_teams = gamestate().board_.teams().size();
const bool is_observer = this->is_observer();
@@ -1185,8 +1188,7 @@ void play_controller::play_turn()
int last_player_number = gamestate_->player_number_;
int next_player_number = gamestate_->next_player_number_;
- while(gamestate_->player_number_ <= int(gamestate().board_.teams().size()))
- {
+ while(gamestate_->player_number_ <= static_cast<int>(gamestate().board_.teams().size())) {
gamestate_->next_player_number_ = gamestate_->player_number_ + 1;
next_player_number = gamestate_->next_player_number_;
last_player_number = gamestate_->player_number_;
@@ -1203,7 +1205,7 @@ void play_controller::play_turn()
play_side();
//ignore any changes to next_player_number_ that happen after the [end_turn] is sended to the server, otherwise we will get OOS.
next_player_number = gamestate_->next_player_number_;
- assert(next_player_number <= 2 * int(gamestate().board_.teams().size()));
+ assert(next_player_number <= 2 * static_cast<int>(gamestate().board_.teams().size()));
if(is_regular_game_end()) {
return;
}
diff --git a/src/play_controller.hpp b/src/play_controller.hpp
index c03e94914ba..e9187038f66 100644
--- a/src/play_controller.hpp
+++ b/src/play_controller.hpp
@@ -76,7 +76,6 @@ class play_controller : public controller_base, public events::observer, public
{
public:
play_controller(const config& level, saved_game& state_of_game,
- const config& game_config,
const ter_data_cache& tdata, bool skip_replay);
virtual ~play_controller();
@@ -268,15 +267,18 @@ public:
virtual void send_to_wesnothd(const config&, const std::string& = "unknown") const { }
virtual bool receive_from_wesnothd(config&) const { return false; }
/// Reevaluate [show_if] conditions and build a new objectives string.
- void refresh_objectives();
+ void refresh_objectives() const;
void show_objectives() const;
+
struct scoped_savegame_snapshot
{
scoped_savegame_snapshot(const play_controller& controller);
~scoped_savegame_snapshot();
const play_controller& controller_;
};
+
saved_game& get_saved_game() { return saved_game_; }
+
protected:
friend struct scoped_savegame_snapshot;
void play_slice_catch();
diff --git a/src/playmp_controller.cpp b/src/playmp_controller.cpp
index 86f5ce20672..64edf776695 100644
--- a/src/playmp_controller.cpp
+++ b/src/playmp_controller.cpp
@@ -39,10 +39,10 @@ static lg::log_domain log_engine("engine");
#define LOG_NG LOG_STREAM(info, log_engine)
playmp_controller::playmp_controller(const config& level,
- saved_game& state_of_game, const config& game_config,
+ saved_game& state_of_game,
const ter_data_cache & tdata,
mp_campaign_info* mp_info)
- : playsingle_controller(level, state_of_game, game_config, tdata, mp_info && mp_info->skip_replay)
+ : playsingle_controller(level, state_of_game, tdata, mp_info && mp_info->skip_replay)
, network_processing_stopped_(false)
, blindfold_(*gui_, mp_info && mp_info->skip_replay_blindfolded)
, mp_info_(mp_info)
diff --git a/src/playmp_controller.hpp b/src/playmp_controller.hpp
index 5a10f45ce4e..e1cb3d0bdb8 100644
--- a/src/playmp_controller.hpp
+++ b/src/playmp_controller.hpp
@@ -24,7 +24,6 @@ class playmp_controller : public playsingle_controller, public syncmp_handler
{
public:
playmp_controller(const config& level, saved_game& state_of_game,
- const config& game_config,
const ter_data_cache & tdata, mp_campaign_info* mp_info);
virtual ~playmp_controller();
diff --git a/src/playsingle_controller.cpp b/src/playsingle_controller.cpp
index b91b8d59520..6c31a19f08c 100644
--- a/src/playsingle_controller.cpp
+++ b/src/playsingle_controller.cpp
@@ -65,9 +65,8 @@ static lg::log_domain log_enginerefac("enginerefac");
#define LOG_RG LOG_STREAM(info, log_enginerefac)
playsingle_controller::playsingle_controller(const config& level,
- saved_game& state_of_game,
- const config& game_config, const ter_data_cache & tdata, bool skip_replay)
- : play_controller(level, state_of_game, game_config, tdata, skip_replay)
+ saved_game& state_of_game, const ter_data_cache & tdata, bool skip_replay)
+ : play_controller(level, state_of_game, tdata, skip_replay)
, cursor_setter_(cursor::NORMAL)
, textbox_info_()
, replay_sender_(*resources::recorder)
diff --git a/src/playsingle_controller.hpp b/src/playsingle_controller.hpp
index 0b491c8dfab..2b42558c5b4 100644
--- a/src/playsingle_controller.hpp
+++ b/src/playsingle_controller.hpp
@@ -37,7 +37,7 @@ class playsingle_controller : public play_controller
{
public:
playsingle_controller(const config& level, saved_game& state_of_game,
- const config& game_config, const ter_data_cache & tdata, bool skip_replay);
+ const ter_data_cache & tdata, bool skip_replay);
LEVEL_RESULT play_scenario(const config& level);
void play_scenario_init();
diff --git a/src/playturn.cpp b/src/playturn.cpp
index 1febe4d82dd..ac69cc9b17e 100644
--- a/src/playturn.cpp
+++ b/src/playturn.cpp
@@ -191,21 +191,14 @@ turn_info::PROCESS_DATA_RESULT turn_info::process_network_data(const config& cfg
resources::controller->on_not_observer();
}
- auto disp_set_team = [](int side_index) {
- const bool side_changed = static_cast<int>(display::get_singleton()->viewing_team()) != side_index;
- display::get_singleton()->set_team(side_index);
-
- if(side_changed) {
- display::get_singleton()->redraw_everything();
- display::get_singleton()->recalculate_minimap();
- video2::trigger_full_redraw();
- }
- };
-
if (resources::gameboard->is_observer() || (resources::gameboard->teams())[display::get_singleton()->playing_team()].is_local_human()) {
- disp_set_team(display::get_singleton()->playing_team());
+ display::get_singleton()->set_team(display::get_singleton()->playing_team());
+ display::get_singleton()->redraw_everything();
+ display::get_singleton()->recalculate_minimap();
} else if (tm.is_local_human()) {
- disp_set_team(side - 1);
+ display::get_singleton()->set_team(side - 1);
+ display::get_singleton()->redraw_everything();
+ display::get_singleton()->recalculate_minimap();
}
resources::whiteboard->on_change_controller(side,tm);
diff --git a/src/preferences/credentials.cpp b/src/preferences/credentials.cpp
index c56d85cd95a..bca817c3ef5 100644
--- a/src/preferences/credentials.cpp
+++ b/src/preferences/credentials.cpp
@@ -79,7 +79,7 @@ static std::string get_system_username()
if(GetUserNameW(buffer, &size)) {
//size includes a terminating null character.
assert(size > 0);
- res = unicode_cast<utf8::string>(boost::iterator_range<wchar_t*>(buffer, buffer + size - 1));
+ res = unicode_cast<std::string>(boost::iterator_range<wchar_t*>(buffer, buffer + size - 1));
}
#else
if(char* const login = getenv("USER")) {
diff --git a/src/preferences/game.cpp b/src/preferences/game.cpp
index 8efa22af70e..518cdbff9ac 100644
--- a/src/preferences/game.cpp
+++ b/src/preferences/game.cpp
@@ -93,9 +93,6 @@ manager::manager() :
preferences::erase("password");
preferences::erase("password_is_wrapped");
- // TODO: remove when we re-enable font scaling configuration.
- preferences::erase("font_scale");
-
/*
completed_campaigns = "A,B,C"
[completed_campaigns]
diff --git a/src/preferences/general.cpp b/src/preferences/general.cpp
index f90ccba5e77..5acb01f33fb 100644
--- a/src/preferences/general.cpp
+++ b/src/preferences/general.cpp
@@ -51,6 +51,8 @@ bool no_preferences_save = false;
bool fps = false;
+int draw_delay_ = 0;
+
config prefs;
}
@@ -972,12 +974,12 @@ void set_show_fps(bool value)
int draw_delay()
{
- return prefs["draw_delay"].to_int(-1);
+ return draw_delay_;
}
void set_draw_delay(int value)
{
- prefs["draw_delay"] = value;
+ draw_delay_ = value;
}
bool use_color_cursors()
@@ -1028,7 +1030,7 @@ void save_sample_rate(const unsigned int rate)
if (sample_rate() == rate)
return;
- prefs["sample_rate"] = int(rate);
+ prefs["sample_rate"] = static_cast<int>(rate);
// If audio is open, we have to re set sample rate
sound::reset_sound();
diff --git a/src/replay.cpp b/src/replay.cpp
index d334757a62b..3e00272df85 100644
--- a/src/replay.cpp
+++ b/src/replay.cpp
@@ -135,7 +135,7 @@ static time_t get_time(const config &speak)
else
{
//fallback in case sender uses wesnoth that doesn't send timestamps
- time = ::time(nullptr);
+ time = time(nullptr);
}
return time;
}
@@ -822,7 +822,7 @@ REPLAY_RETURN do_replay_handle(bool one_move)
{
int val = countdown_update["value"];
int tval = countdown_update["team"];
- if (tval <= 0 || tval > int(resources::gameboard->teams().size())) {
+ if (tval <= 0 || tval > static_cast<int>(resources::gameboard->teams().size())) {
std::stringstream errbuf;
errbuf << "Illegal countdown update \n"
<< "Received update for :" << tval << " Current user :"
diff --git a/src/replay.hpp b/src/replay.hpp
index 200d711487d..ad6eb35578e 100644
--- a/src/replay.hpp
+++ b/src/replay.hpp
@@ -21,6 +21,7 @@
#include "map/location.hpp"
+#include <ctime>
#include <deque>
#include <iterator>
#include <map>
diff --git a/src/replay_helper.cpp b/src/replay_helper.cpp
index 1ae17298eb3..2cac7e96566 100644
--- a/src/replay_helper.cpp
+++ b/src/replay_helper.cpp
@@ -103,7 +103,7 @@ config replay_helper::get_attack(const map_location& a, const map_location& b,
move["defender_type"] = defender_type_id;
move["attacker_lvl"] = attacker_lvl;
move["defender_lvl"] = defender_lvl;
- move["turn"] = int(turn);
+ move["turn"] = static_cast<int>(turn);
move["tod"] = t.id;
/*
add_unit_checksum(a,current_);
diff --git a/src/reports.cpp b/src/reports.cpp
index 818ff1bc7d6..5f9221fd7c2 100644
--- a/src/reports.cpp
+++ b/src/reports.cpp
@@ -14,7 +14,6 @@
#include "actions/attack.hpp"
#include "attack_prediction.hpp"
-#include "desktop/battery_info.hpp"
#include "font/pango/escape.hpp"
#include "font/text_formatting.hpp"
#include "formatter.hpp"
@@ -36,10 +35,6 @@
#include <ctime>
#include <iomanip>
#include <boost/dynamic_bitset.hpp>
-#include <boost/format.hpp>
-#include <boost/lexical_cast.hpp>
-
-#include "utils/io.hpp"
static void add_text(config &report, const std::string &text,
const std::string &tooltip, const std::string &help = "")
@@ -303,7 +298,7 @@ static config unit_status(reports::context & rc, const unit* u)
if (!u) return config();
config res;
map_location displayed_unit_hex = rc.screen().displayed_unit_hex();
- if (rc.map().on_board(displayed_unit_hex) && u->invisible(displayed_unit_hex, rc.dc())) {
+ if (rc.map().on_board(displayed_unit_hex) && u->invisible(displayed_unit_hex)) {
add_status(res, "misc/invisible.png", N_("invisible: "),
N_("This unit is invisible. It cannot be seen or attacked by enemy units."));
}
@@ -596,7 +591,7 @@ static config unit_moves(reports::context & rc, const unit* u)
std::set<terrain_movement> terrain_moves;
if (u->side() == rc.screen().playing_side()) {
- movement_frac = double(u->movement_left()) / std::max<int>(1, u->total_movement());
+ movement_frac = static_cast<double>(u->movement_left()) / std::max<int>(1, u->total_movement());
if (movement_frac > 1.0)
movement_frac = 1.0;
}
@@ -636,7 +631,7 @@ static config unit_moves(reports::context & rc, const unit* u)
tooltip << naps << '\n';
}
- int grey = 128 + int((255 - 128) * movement_frac);
+ int grey = 128 + static_cast<int>((255 - 128) * movement_frac);
color_t c = color_t(grey, grey, grey);
str << span_color(c) << u->movement_left() << '/' << u->total_movement() << naps;
return text_report(str.str(), tooltip.str());
@@ -670,9 +665,10 @@ static int attack_info(reports::context & rc, const attack_type &at, config &res
int base_damage = at.damage();
int specials_damage = at.modified_damage(false);
int damage_multiplier = 100;
+ const_attack_ptr weapon = at.shared_from_this();
int tod_bonus = combat_modifier(rc.units(), rc.map(), displayed_unit_hex, u.alignment(), u.is_fearless());
damage_multiplier += tod_bonus;
- int leader_bonus = under_leadership(rc.units(), displayed_unit_hex).first;
+ int leader_bonus = under_leadership(rc.units(), displayed_unit_hex, weapon).first;
if (leader_bonus != 0)
damage_multiplier += leader_bonus;
@@ -732,7 +728,7 @@ static int attack_info(reports::context & rc, const attack_type &at, config &res
// specials are calculated, but for an unusual case, simple brevity
// trumps complexities.
if ( max_attacks != base_attacks ) {
- int attack_diff = int(max_attacks) - int(base_attacks);
+ int attack_diff = static_cast<int>(max_attacks) - static_cast<int>(base_attacks);
tooltip << '\t' << _("Specials: ") << utils::signed_value(attack_diff) << '\n';
}
}
@@ -780,7 +776,7 @@ static int attack_info(reports::context & rc, const attack_type &at, config &res
continue;
const map_location &loc = enemy.get_location();
if (viewing_team.fogged(loc) ||
- (viewing_team.is_enemy(enemy.side()) && enemy.invisible(loc, rc.dc())))
+ (viewing_team.is_enemy(enemy.side()) && enemy.invisible(loc)))
continue;
bool new_type = seen_types.insert(enemy.type_id()).second;
if (new_type) {
@@ -821,7 +817,7 @@ static int attack_info(reports::context & rc, const attack_type &at, config &res
}
{
- auto ctx = at.specials_context_for_listing();
+ auto ctx = at.specials_context_for_listing(u.side() == rc.screen().playing_side());
boost::dynamic_bitset<> active;
const std::vector<std::pair<t_string, t_string>> &specials = at.special_tooltips(&active);
const size_t specials_size = specials.size();
@@ -880,8 +876,7 @@ static config unit_weapons(reports::context & rc, const unit *attacker, const ma
for (unsigned int i = 0; i < attacker->attacks().size(); i++) {
// skip weapons with attack_weight=0
if (attacker->attacks()[i].attack_weight() > 0) {
- battle_context weapon(rc.units(), attacker_pos, defender->get_location(), i, -1, 0.0, nullptr, attacker);
- weapons.emplace_back(std::move(weapon));
+ weapons.emplace_back(rc.units(), attacker_pos, defender->get_location(), i, -1, 0.0, nullptr, attacker);
}
}
@@ -1539,9 +1534,6 @@ REPORT_GENERATOR(edit_left_button_function)
REPORT_GENERATOR(report_clock, /*rc*/)
{
- config report;
- add_image(report, game_config::images::time_icon, "");
-
std::ostringstream ss;
const char* format = preferences::use_twelve_hour_clock_format()
@@ -1549,23 +1541,9 @@ REPORT_GENERATOR(report_clock, /*rc*/)
: "%H:%M";
time_t t = time(nullptr);
- ss << utils::put_time(std::localtime(&t), format);
- add_text(report, ss.str(), _("Clock"));
-
- return report;
-}
-
+ ss << std::put_time(std::localtime(&t), format);
-REPORT_GENERATOR(battery, /*rc*/)
-{
- config report;
-
- if(desktop::battery_info::does_device_have_battery()) {
- add_image(report, game_config::images::battery_icon, "");
- add_text(report, (boost::format("%.0f %%") % desktop::battery_info::get_battery_percentage()).str(), _("Battery"));
- }
-
- return report;
+ return text_report(ss.str(), _("Clock"));
}
REPORT_GENERATOR(report_countdown, rc)
diff --git a/src/save_index.cpp b/src/save_index.cpp
index 073c644a8a2..3f9d15bd931 100644
--- a/src/save_index.cpp
+++ b/src/save_index.cpp
@@ -85,7 +85,7 @@ config& save_index_class::get(const std::string& name)
time_t m = modified_[name];
config::attribute_value& mod_time = result["mod_time"];
- if(mod_time.empty() || static_cast<time_t>(mod_time.to_int()) != m) {
+ if(mod_time.empty() || mod_time.to_time_t() != m) {
rebuild(name, m);
}
@@ -213,7 +213,7 @@ const config& save_info::summary() const
std::string save_info::format_time_local() const
{
- if(tm* tm_l = localtime(&modified())) {
+ if(std::tm* tm_l = std::localtime(&modified())) {
const std::string format = preferences::use_twelve_hour_clock_format()
? _("%a %b %d %I:%M %p %Y")
: _("%a %b %d %H:%M %Y");
@@ -373,7 +373,7 @@ void extract_summary_from_config(config& cfg_save, config& cfg_summary)
cfg_summary["difficulty"] = cfg_save["difficulty"];
cfg_summary["random_mode"] = cfg_save["random_mode"];
- cfg_summary["active_mods"] = cfg_save.child_or_empty("multiplayer")["active_mods"];
+ cfg_summary["active_mods"] = cfg_save.child("multiplayer")["active_mods"];
cfg_summary["campaign"] = cfg_save["campaign"];
cfg_summary["version"] = cfg_save["version"];
cfg_summary["corrupt"] = "";
diff --git a/src/saved_game.cpp b/src/saved_game.cpp
index 7c42229ab6a..dbdf0fa6240 100644
--- a/src/saved_game.cpp
+++ b/src/saved_game.cpp
@@ -194,7 +194,7 @@ void saved_game::set_defaults()
for(config& side : starting_point_.child_range("side")) {
// Set save_id default value directly after loading to its default to prevent different default behaviour in
// mp_connect code and sp code.
-
+
if(side["no_leader"].to_bool()) {
side["leader_lock"] = true;
side.remove_attribute("type");
@@ -242,7 +242,7 @@ void saved_game::expand_scenario()
// A hash has to be generated using an unmodified scenario data.
mp_settings_.hash = scenario.hash();
-
+
check_require_scenario();
update_label();
@@ -259,6 +259,7 @@ void saved_game::check_require_scenario()
if(!starting_point_["require_scenario"].to_bool(false)) {
return;
}
+
if(starting_point_["addon_id"].empty()) {
//ERR_NG << "cannot handle require_scenario=yes because we don't know from which addon that scenario came from\n";
return;
@@ -270,7 +271,7 @@ void saved_game::check_require_scenario()
required_scenario["name"] = starting_point_["addon_title"];
required_scenario["version"] = starting_point_["addon_version"];
required_scenario["min_version"] = starting_point_["addon_min_version"];
-
+
mp_settings_.update_addon_requirements(required_scenario);
}
@@ -297,7 +298,7 @@ struct modevents_entry
} // end anon namespace
-void saved_game::load_mod(const std::string& type, const std::string& id)
+void saved_game::load_mod(const std::string& type, const std::string& id, config::all_children_iterator pos)
{
if(const config& cfg = game_config_manager::get()->game_config().find_child(type, "id", id)) {
// Note the addon_id if this mod is required to play the game in mp.
@@ -322,18 +323,18 @@ void saved_game::load_mod(const std::string& type, const std::string& id)
if(modevent["enable_if"].empty()
|| variable_to_bool(carryover_.child_or_empty("variables"), modevent["enable_if"])
) {
- this->starting_point_.add_child("event", modevent);
+ this->starting_point_.add_child_at("event", modevent, pos++);
}
}
// Copy lua
for(const config& modlua : cfg.child_range("lua")) {
- this->starting_point_.add_child("lua", modlua);
+ this->starting_point_.add_child_at("lua", modlua, pos++);
}
// Copy load_resource
for(const config& load_resource : cfg.child_range("load_resource")) {
- this->starting_point_.add_child("load_resource", load_resource);
+ this->starting_point_.add_child_at("load_resource", load_resource, pos++);
}
} else {
// TODO: A user message instead?
@@ -366,25 +367,24 @@ void saved_game::expand_mp_events()
mods.emplace_back("campaign", classification_.campaign);
}
- // In the first iteration mod contains no [resource]s in all other iterations, mods contains only [resource]s.
- do {
- for(modevents_entry& mod : mods) {
- load_mod(mod.type, mod.id);
- }
-
- mods.clear();
-
- for(const config& cfg : starting_point_.child_range("load_resource")) {
- if(loaded_resources.find(cfg["id"].str()) == loaded_resources.end()) {
- mods.emplace_back("resource", cfg["id"].str());
-
- loaded_resources.insert(cfg["id"].str());
- }
+ for(modevents_entry& mod : mods) {
+ load_mod(mod.type, mod.id, this->starting_point_.ordered_end());
+ }
+ mods.clear();
+
+ while(starting_point_.has_child("load_resource")) {
+ //todo: this looks like too much exposure of configs internals.
+ auto pos = std::find_if(starting_point_.ordered_begin(), starting_point_.ordered_end(), [&](const config::any_child& can){ return can.key == "load_resource"; });
+ assert(pos != starting_point_.ordered_end());
+ //assert(pos->index == 0);
+ std::string id = pos->cfg["id"];
+ starting_point_.remove_child("load_resource", 0);
+ //pos is still valid because starting_point_.ordered_begin() is a vector iterator.
+ if(loaded_resources.find(id) == loaded_resources.end()) {
+ loaded_resources.insert(id);
+ load_mod("resource", id, pos);
}
-
- starting_point_.clear_children("load_resource");
- } while(!mods.empty());
-
+ }
this->starting_point_["has_mod_events"] = true;
}
}
@@ -483,7 +483,7 @@ void saved_game::post_scenario_generation(const config& old_scenario, config& ge
}
}
-
+
void saved_game::expand_carryover()
{
expand_scenario();
diff --git a/src/saved_game.hpp b/src/saved_game.hpp
index fb5f1ca5f1f..b04babd7de7 100644
--- a/src/saved_game.hpp
+++ b/src/saved_game.hpp
@@ -72,7 +72,7 @@ public:
/// should be called after expand_scenario() but before expand_carryover()
void expand_mp_events();
/// helper for expand_mp_events();
- void load_mod(const std::string& type, const std::string& id);
+ void load_mod(const std::string& type, const std::string& id, config::all_children_iterator pos);
/// adds values of [option]s into [carryover_sides_start][variables] so that they are applied in the next level.
/// Note that since [variabels] are persistent we only use this once at the beginning
/// of a campaign but calling it multiple times is no harm eigher
diff --git a/src/savegame.cpp b/src/savegame.cpp
index 80036e8fd6b..3b60741d223 100644
--- a/src/savegame.cpp
+++ b/src/savegame.cpp
@@ -41,6 +41,7 @@
#include "saved_game.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/parser.hpp"
+#include "serialization/utf8_exception.hpp"
#include "statistics.hpp"
#include "game_version.hpp"
#include "video.hpp"
@@ -100,7 +101,7 @@ bool loadgame::show_difficulty_dialog()
difficulty_dlg.show();
// Return if canceled, since otherwise load_data_.difficulty will be set to 'CANCEL'
- if (difficulty_dlg.get_retval() != gui2::retval::OK) {
+ if(!difficulty_dlg.show()) {
return false;
}
@@ -217,7 +218,7 @@ bool loadgame::check_version_compatibility()
bool loadgame::check_version_compatibility(const version_info & save_version)
{
- if (save_version == game_config::version) {
+ if (save_version == game_config::wesnoth_version) {
return true;
}
@@ -504,7 +505,7 @@ void savegame::write_game(config_writer &out)
{
log_scope("write_game");
- out.write_key_val("version", game_config::version);
+ out.write_key_val("version", game_config::wesnoth_version.str());
gamestate_.write_general_info(out);
out.open_child("statistics");
diff --git a/src/scripting/game_lua_kernel.cpp b/src/scripting/game_lua_kernel.cpp
index e93902cf7bb..4f7408df3c4 100644
--- a/src/scripting/game_lua_kernel.cpp
+++ b/src/scripting/game_lua_kernel.cpp
@@ -448,6 +448,7 @@ static int impl_run_animation(lua_State* L)
anim.start_animations();
anim.wait_for_end();
anim.set_all_standing();
+ anim.clear();
return 0;
}
@@ -1012,6 +1013,119 @@ int game_lua_kernel::intf_set_terrain(lua_State *L)
return 0;
}
+static bool luaW_tableget(lua_State *L, int index, const char* key)
+{
+ lua_pushstring(L, key);
+ lua_gettable(L, index);
+ if(lua_isnil(L, -1)) {
+ lua_pop(L, 1);
+ return false;
+ }
+ return true;
+}
+
+static utils::string_view luaW_tostring(lua_State *L, int index)
+{
+ size_t len = 0;
+ const char* str = lua_tolstring (L, index, &len);
+ return utils::string_view(str, len);
+}
+
+/**
+ * Reaplces part of rhe map.
+ * - Arg 1: map location.
+ * - Arg 2: map data string.
+ * - Arg 3: table for optional named arguments
+ * - is_odd: boolen, if Arg2 has the odd mapo format (as if it was cut from a odd map location)
+ * - ignore_special_locations: boolean
+ * - rules: table of tables
+*/
+int game_lua_kernel::intf_terrain_mask(lua_State *L)
+{
+ map_location loc = luaW_checklocation(L, 1);
+ std::string t_str(luaL_checkstring(L, 2));
+ bool is_odd = false;
+ bool ignore_special_locations = false;
+ std::vector<gamemap::overlay_rule> rules;
+
+ if(lua_istable(L, 3)) {
+ if(luaW_tableget(L, 3, "is_odd")) {
+ is_odd = luaW_toboolean(L, -1);
+ lua_pop(L, 1);
+ }
+ if(luaW_tableget(L, 3, "ignore_special_locations")) {
+ ignore_special_locations = luaW_toboolean(L, -1);
+ lua_pop(L, 1);
+ }
+ if(luaW_tableget(L, 3, "rules")) {
+ if(!lua_istable(L, -1)) {
+ return luaL_argerror(L, 3, "rules must be a table");
+ }
+
+ for (int i = 1, i_end = lua_rawlen(L, -1); i <= i_end; ++i)
+ {
+ lua_rawgeti(L, -1, i);
+ if(!lua_istable(L, -1)) {
+ return luaL_argerror(L, 3, "rules must be a table of tables");
+ }
+ rules.push_back(gamemap::overlay_rule());
+ auto& rule = rules.back();
+ if(luaW_tableget(L, -1, "old")) {
+ rule.old_ = t_translation::read_list(luaW_tostring(L, -1));
+ lua_pop(L, 1);
+ }
+
+ if(luaW_tableget(L, -1, "new")) {
+ rule.new_ = t_translation::read_list(luaW_tostring(L, -1));
+ lua_pop(L, 1);
+ }
+
+ if(luaW_tableget(L, -1, "mode")) {
+ auto str = luaW_tostring(L, -1);
+ rule.mode_ = str == "base" ? terrain_type_data::BASE : (str == "overlay" ? terrain_type_data::OVERLAY : terrain_type_data::BOTH);
+ lua_pop(L, 1);
+ }
+
+ if(luaW_tableget(L, -1, "terrain")) {
+ const t_translation::ter_list terrain = t_translation::read_list(luaW_tostring(L, -1));
+ if(!terrain.empty()) {
+ rule.terrain_ = terrain[0];
+ }
+ lua_pop(L, 1);
+ }
+
+ if(luaW_tableget(L, -1, "use_old")) {
+ rule.use_old_ = luaW_toboolean(L, -1);
+ lua_pop(L, 1);
+ }
+
+ if(luaW_tableget(L, -1, "replace_if_failed")) {
+ rule.replace_if_failed_ = luaW_toboolean(L, -1);
+ lua_pop(L, 1);
+ }
+
+ lua_pop(L, 1);
+ }
+ lua_pop(L, 1);
+ }
+ }
+
+
+ gamemap mask_map(board().map().tdata(), "");
+ mask_map.read(t_str, false);
+ board().map_->overlay(mask_map, loc, rules, is_odd, ignore_special_locations);
+
+ for(team& t : board().teams()) {
+ t.fix_villages(board().map());
+ }
+
+ if (game_display_) {
+ game_display_->needs_rebuild(true);
+ }
+
+ return 0;
+}
+
/**
* Gets details about a terrain.
* - Arg 1: terrain code string.
@@ -1330,6 +1444,7 @@ int game_lua_kernel::impl_game_config_set(lua_State *L)
modify_int_attrib("rest_heal_amount", game_config::rest_heal_amount = value);
modify_int_attrib("recall_cost", game_config::recall_cost = value);
modify_int_attrib("kill_experience", game_config::kill_experience = value);
+ modify_int_attrib("combat_experience", game_config::combat_experience = value);
modify_int_attrib("last_turn", tod_man().set_number_of_turns_by_wml(value));
modify_string_attrib("next_scenario", gamedata().set_next_scenario(value));
modify_string_attrib("theme",
@@ -1659,29 +1774,37 @@ int game_lua_kernel::intf_find_path(lua_State *L)
lua_rawget(L, arg);
if (!lua_isnil(L, -1)) {
int i = luaL_checkinteger(L, -1);
- if (i >= 1 && i <= int(teams().size())) viewing_side = i;
+ if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
else see_all = true;
}
lua_pop(L, 1);
+
+ lua_pushstring(L, "calculate");
+ lua_rawget(L, arg);
+ if(lua_isfunction(L, -1)) {
+ calc.reset(new lua_pathfind_cost_calculator(L, lua_gettop(L)));
+ }
+ // Don't pop, the lua_pathfind_cost_calculator requires it to stay on the stack.
}
else if (lua_isfunction(L, arg))
{
calc.reset(new lua_pathfind_cost_calculator(L, arg));
+ ignore_teleport = lua_isnoneornil(L, arg + 1) || luaW_toboolean(L, arg + 1);
}
+ const team& viewing_team = viewing_side
+ ? board().get_team(viewing_side)
+ : board().get_team(u->side());
+
pathfind::teleport_map teleport_locations;
+ if(!ignore_teleport) {
+ teleport_locations = pathfind::get_teleport_locations(*u, viewing_team, see_all, ignore_units);
+ }
+
if (!calc) {
if (!u) return luaL_argerror(L, 1, "unit not found");
- const team& viewing_team = viewing_side
- ? board().get_team(viewing_side)
- : board().get_team(u->side());
-
- if (!ignore_teleport) {
- teleport_locations = pathfind::get_teleport_locations(
- *u, viewing_team, see_all, ignore_units);
- }
calc.reset(new pathfind::shortest_path_calculator(*u, viewing_team,
teams(), map, ignore_units, false, see_all));
}
@@ -1756,7 +1879,7 @@ int game_lua_kernel::intf_find_reach(lua_State *L)
lua_rawget(L, arg);
if (!lua_isnil(L, -1)) {
int i = luaL_checkinteger(L, -1);
- if (i >= 1 && i <= int(teams().size())) viewing_side = i;
+ if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
else see_all = true;
}
lua_pop(L, 1);
@@ -1910,7 +2033,7 @@ int game_lua_kernel::intf_find_cost_map(lua_State *L)
if (!lua_isnil(L, -1))
{
int i = luaL_checkinteger(L, -1);
- if (i >= 1 && i <= int(teams().size()))
+ if (i >= 1 && i <= static_cast<int>(teams().size()))
{
viewing_side = i;
see_all = false;
@@ -2417,7 +2540,7 @@ int game_lua_kernel::intf_unit_ability(lua_State *L)
{
const unit& u = luaW_checkunit(L, 1);
char const *m = luaL_checkstring(L, 2);
- lua_pushboolean(L, u.get_ability_bool(m, board()));
+ lua_pushboolean(L, u.get_ability_bool(m));
return 1;
}
@@ -2533,7 +2656,7 @@ int game_lua_kernel::intf_simulate_combat(lua_State *L)
++arg_num;
if (lua_isnumber(L, arg_num)) {
att_w = lua_tointeger(L, arg_num) - 1;
- if (att_w < 0 || att_w >= int(att.attacks().size()))
+ if (att_w < 0 || att_w >= static_cast<int>(att.attacks().size()))
return luaL_argerror(L, arg_num, "weapon index out of bounds");
++arg_num;
}
@@ -2542,7 +2665,7 @@ int game_lua_kernel::intf_simulate_combat(lua_State *L)
++arg_num;
if (lua_isnumber(L, arg_num)) {
def_w = lua_tointeger(L, arg_num) - 1;
- if (def_w < 0 || def_w >= int(def.attacks().size()))
+ if (def_w < 0 || def_w >= static_cast<int>(def.attacks().size()))
return luaL_argerror(L, arg_num, "weapon index out of bounds");
++arg_num;
}
@@ -3222,11 +3345,23 @@ static int intf_add_known_unit(lua_State *L)
int game_lua_kernel::intf_add_tile_overlay(lua_State *L)
{
map_location loc = luaW_checklocation(L, 1);
- config cfg = luaW_checkconfig(L, 2);
+ vconfig cfg = luaW_checkvconfig(L, 2);
+ const vconfig &ssf = cfg.child("filter_team");
+
+ std::string team_name;
+ if (!ssf.null()) {
+ const std::vector<int>& teams = side_filter(ssf, &game_state_).get_teams();
+ std::vector<std::string> team_names;
+ std::transform(teams.begin(), teams.end(), std::back_inserter(team_names),
+ [&](int team) { return game_state_.get_disp_context().get_team(team).team_name(); });
+ team_name = utils::join(team_names);
+ } else {
+ team_name = cfg["team_name"].str();
+ }
if (game_display_) {
game_display_->add_overlay(loc, cfg["image"], cfg["halo"],
- cfg["team_name"], cfg["name"], cfg["visible_in_fog"].to_bool(true));
+ team_name, cfg["name"], cfg["visible_in_fog"].to_bool(true));
}
return 0;
}
@@ -3330,7 +3465,7 @@ int game_lua_kernel::intf_delay(lua_State *L)
do {
play_controller_.play_slice(false);
CVideo::delay(10);
- } while (int(final - SDL_GetTicks()) > 0);
+ } while (static_cast<int>(final - SDL_GetTicks()) > 0);
return 0;
}
@@ -4148,6 +4283,7 @@ game_lua_kernel::game_lua_kernel(game_state & gs, play_controller & pc, reports
{ "switch_ai", &intf_switch_ai },
{ "synchronize_choice", &intf_synchronize_choice },
{ "synchronize_choices", &intf_synchronize_choices },
+ { "terrain_mask", &dispatch<&game_lua_kernel::intf_terrain_mask > },
{ "zoom", &dispatch<&game_lua_kernel::intf_zoom > },
{ "teleport", &dispatch<&game_lua_kernel::intf_teleport > },
{ "unit_ability", &dispatch<&game_lua_kernel::intf_unit_ability > },
@@ -4640,12 +4776,16 @@ bool game_lua_kernel::run_filter(char const *name, const map_location& l)
bool game_lua_kernel::run_filter(char const *name, const unit& u)
{
lua_State *L = mState;
- unit_map::const_unit_iterator ui = units().find(u.get_location());
- if (!ui.valid()) return false;
- // Pass the unit as argument.
- luaW_pushunit(L, ui->underlying_id());
-
- return run_filter(name, 1);
+ lua_unit* lu = luaW_pushlocalunit(L, const_cast<unit&>(u));
+ // stack: unit
+ // put the unit to the stack twice to prevent gc.
+ lua_pushvalue(L, -1);
+ // stack: unit, unit
+ bool res = run_filter(name, 1);
+ // stack: unit
+ lu->clear_ref();
+ lua_pop(L, 1);
+ return res;
}
/**
* Runs a script from a filter.
diff --git a/src/scripting/game_lua_kernel.hpp b/src/scripting/game_lua_kernel.hpp
index cef515c9717..0aab400b251 100644
--- a/src/scripting/game_lua_kernel.hpp
+++ b/src/scripting/game_lua_kernel.hpp
@@ -91,6 +91,7 @@ class game_lua_kernel : public lua_kernel_base
int intf_lock_view(lua_State *L);
int intf_get_terrain(lua_State *L);
int intf_set_terrain(lua_State *L);
+ int intf_terrain_mask(lua_State *L);
int intf_get_terrain_info(lua_State *L);
int intf_get_time_of_day(lua_State *L);
int intf_get_village_owner(lua_State *L);
diff --git a/src/scripting/lua_common.cpp b/src/scripting/lua_common.cpp
index 22abc95a300..cd3371af190 100644
--- a/src/scripting/lua_common.cpp
+++ b/src/scripting/lua_common.cpp
@@ -301,8 +301,16 @@ static int impl_vconfig_pairs_collect(lua_State *L)
{
typedef config::const_attr_itors const_attr_itors;
void* p = lua_touserdata(L, 1);
+
+ // Triggers a false positive of C4189 with Visual Studio. Suppress.
+#pragma warning(push)
+#pragma warning(disable: 4189)
+
const_attr_itors* cai = static_cast<const_attr_itors*>(p);
cai->~const_attr_itors();
+
+#pragma warning(pop)
+
return 0;
}
diff --git a/src/scripting/lua_gui2.cpp b/src/scripting/lua_gui2.cpp
index 5d81a0e9434..ae6f3864ffe 100644
--- a/src/scripting/lua_gui2.cpp
+++ b/src/scripting/lua_gui2.cpp
@@ -27,6 +27,7 @@
#include "gui/dialogs/message.hpp"
#include "gui/widgets/clickable_item.hpp"
#include "gui/widgets/styled_widget.hpp"
+#include "gui/widgets/listbox.hpp"
#include "gui/widgets/multi_page.hpp"
#include "gui/widgets/multimenu_button.hpp"
#include "gui/widgets/progress_bar.hpp"
@@ -40,12 +41,6 @@
#include "gui/widgets/widget.hpp"
#include "gui/widgets/window.hpp"
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
-#include "gui/widgets/list.hpp"
-#else
-#include "gui/widgets/listbox.hpp"
-#endif
-
#include "config.hpp"
#include "log.hpp"
#include "scripting/lua_common.hpp"
@@ -131,11 +126,7 @@ static gui2::widget* find_widget(lua_State* L, int i, bool readonly)
gui2::widget* w = scoped_dialog::current->window.get();
for(; !lua_isnoneornil(L, i); ++i)
{
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- if(gui2::list_view* list = dynamic_cast<gui2::list_view*>(w))
-#else
if(gui2::listbox* list = dynamic_cast<gui2::listbox*>(w))
-#endif
{
int v = lua_tointeger(L, i);
if(v < 1) {
@@ -462,14 +453,8 @@ int show_message_box(lua_State* L) {
int intf_set_dialog_value(lua_State* L)
{
gui2::widget *w = find_widget(L, 2, false);
- if (w)
- w->get_window()->invalidate_layout();
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- if(gui2::list_view* list = dynamic_cast<gui2::list_view*>(w))
-#else
if(gui2::listbox* list = dynamic_cast<gui2::listbox*>(w))
-#endif
{
if(lua_istable(L, 1)) {
// Do two passes in case has_minimum is true
@@ -597,11 +582,7 @@ int intf_get_dialog_value(lua_State* L)
gui2::widget *w = find_widget(L, 1, true);
int num_rets = 1;
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- if(gui2::list_view* list = dynamic_cast<gui2::list_view*>(w))
-#else
if(gui2::listbox* list = dynamic_cast<gui2::listbox*>(w))
-#endif
{
lua_pushinteger(L, list->get_selected_row() + 1);
num_rets = 2;
@@ -693,11 +674,7 @@ int intf_remove_dialog_item(lua_State* L)
int number = luaL_checkinteger(L, 2);
gui2::widget* w = find_widget(L, 3, true);
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- if(gui2::list_view* list = dynamic_cast<gui2::list_view*>(w))
-#else
if(gui2::listbox* list = dynamic_cast<gui2::listbox*>(w))
-#endif
{
list->remove_row(pos, number);
} else if(gui2::multi_page* multi_page = dynamic_cast<gui2::multi_page*>(w)) {
@@ -775,23 +752,10 @@ int intf_set_dialog_callback(lua_State* L)
connect_signal_notify_modified(dynamic_cast<gui2::widget&>(*si), std::bind(dialog_callback, _1));
} else if(gui2::integer_selector* is = dynamic_cast<gui2::integer_selector*>(w)) {
connect_signal_notify_modified(dynamic_cast<gui2::widget&>(*is), std::bind(dialog_callback, _1));
- }
-#ifdef GUI2_EXPERIMENTAL_LISTBOX
- else if(gui2::list_view* l = dynamic_cast<gui2::list_view*>(w)) {
- static dialog_callback_wrapper wrapper;
- connect_signal_notify_modified(*l
- , std::bind(
- &dialog_callback_wrapper::forward
- , wrapper
- , w));
- }
-#else
- else if(gui2::listbox* l = dynamic_cast<gui2::listbox*>(w)) {
+ } else if(gui2::listbox* l = dynamic_cast<gui2::listbox*>(w)) {
static dialog_callback_wrapper wrapper;
connect_signal_notify_modified(*l, std::bind(&dialog_callback_wrapper::forward, wrapper, w));
- }
-#endif
- else if(gui2::tree_view* tv = dynamic_cast<gui2::tree_view*>(w)) {
+ } else if(gui2::tree_view* tv = dynamic_cast<gui2::tree_view*>(w)) {
tv->set_selection_change_callback(&dialog_callback);
} else {
return luaL_argerror(L, lua_gettop(L), "unsupported widget");
diff --git a/src/scripting/lua_kernel_base.cpp b/src/scripting/lua_kernel_base.cpp
index 79444c1b341..92fd9222596 100644
--- a/src/scripting/lua_kernel_base.cpp
+++ b/src/scripting/lua_kernel_base.cpp
@@ -163,24 +163,6 @@ static int intf_load(lua_State* L)
return 1;
}
-// Same for loadstring.
-static int intf_loadstring(lua_State* L)
-{
- std::string string = luaL_checkstring(L, 1);
- const char* name = luaL_optstring(L, 2, string.c_str());
-
- deprecated_message("loadstring()", DEP_LEVEL::FOR_REMOVAL, {1, 15, 0}, "Use load() instead.");
-
- int result = luaL_loadbufferx(L, string.data(), string.length(), name, "t");
- if(result != LUA_OK) {
- lua_pushnil(L);
- lua_insert(L, -2);
- return 2;
- }
-
- return 1;
-}
-
// The show lua console callback is similarly a method of lua kernel
int lua_kernel_base::intf_show_lua_console(lua_State *L)
{
@@ -274,8 +256,8 @@ static int intf_name_generator(lua_State *L)
static int intf_random(lua_State *L)
{
if (lua_isnoneornil(L, 1)) {
- double r = double(randomness::generator->next_random());
- double r_max = double(std::numeric_limits<uint32_t>::max());
+ double r = static_cast<double>(randomness::generator->next_random());
+ double r_max = static_cast<double>(std::numeric_limits<uint32_t>::max());
lua_push(L, r / (r_max + 1));
return 1;
}
@@ -343,7 +325,7 @@ static int intf_deprecated_message(lua_State* L) {
const DEP_LEVEL level = DEP_LEVEL(luaL_checkinteger(L, 2));
const std::string ver_str = lua_isnoneornil(L, 3) ? "" : luaL_checkstring(L, 3);
const std::string detail = luaW_checktstring(L, 4);
- const version_info ver = ver_str.empty() ? game_config::version : ver_str;
+ const version_info ver = ver_str.empty() ? game_config::wesnoth_version.str() : ver_str;
const std::string msg = deprecated_message(elem, level, ver, detail);
if(level < DEP_LEVEL::INDEFINITE || level >= DEP_LEVEL::REMOVED) {
// Invalid deprecation level or level 4 deprecation should raise an interpreter error
@@ -569,7 +551,7 @@ lua_kernel_base::lua_kernel_base()
lua_pushcfunction(L, intf_load);
lua_setglobal(L, "load");
- lua_pushcfunction(L, intf_loadstring);
+ lua_pushnil(L);
lua_setglobal(L, "loadstring");
cmd_log_ << "Initializing package repository...\n";
@@ -897,7 +879,8 @@ int lua_kernel_base::impl_game_config_get(lua_State* L)
return_int_attrib("rest_heal_amount", game_config::rest_heal_amount);
return_int_attrib("recall_cost", game_config::recall_cost);
return_int_attrib("kill_experience", game_config::kill_experience);
- return_string_attrib("version", game_config::version);
+ return_int_attrib("combat_experience", game_config::combat_experience);
+ return_string_attrib("version", game_config::wesnoth_version.str());
return_bool_attrib("debug", game_config::debug);
return_bool_attrib("debug_lua", game_config::debug_lua);
return_bool_attrib("mp_debug", game_config::mp_debug);
diff --git a/src/scripting/lua_unit_attacks.cpp b/src/scripting/lua_unit_attacks.cpp
index fa62599dd8c..67363a23865 100644
--- a/src/scripting/lua_unit_attacks.cpp
+++ b/src/scripting/lua_unit_attacks.cpp
@@ -20,7 +20,6 @@
#include "units/unit.hpp"
#include "units/attack_type.hpp"
#include "utils/const_clone.hpp"
-#include "utils/type_trait_aliases.hpp"
#include "lua/lauxlib.h"
#include "lua/lua.h" // for lua_State, lua_settop, etc
@@ -90,7 +89,7 @@ attack_type& luaW_checkweapon(lua_State* L, int idx)
}
template<typename T>
-using attack_ptr_in = std::shared_ptr<utils::const_clone_t<attack_type, utils::remove_pointer_t<T>>>;
+using attack_ptr_in = std::shared_ptr<utils::const_clone_t<attack_type, std::remove_pointer_t<T>>>;
// Note that these two templates are designed on the assumption that T is either unit or unit_type
template<typename T>
diff --git a/src/scripting/push_check.hpp b/src/scripting/push_check.hpp
index d5e6d2d1cee..f236871c158 100644
--- a/src/scripting/push_check.hpp
+++ b/src/scripting/push_check.hpp
@@ -24,8 +24,6 @@
#include "lua/lauxlib.h"
#include "lua/lua.h"
-#include "utils/type_trait_aliases.hpp"
-
#include <cassert>
class enum_tag;
@@ -44,7 +42,7 @@ namespace lua_check_impl
BOOST_MPL_HAS_XXX_TRAIT_DEF(second_type)
}
- template<typename T, typename T2 = utils::remove_reference_t<T>>
+ template<typename T, typename T2 = std::remove_reference_t<T>>
struct is_container
: boost::mpl::bool_<
detail::has_value_type<T2>::value &&
@@ -54,7 +52,7 @@ namespace lua_check_impl
>
{};
- template<typename T, typename T2 = utils::remove_reference_t<T>>
+ template<typename T, typename T2 = std::remove_reference_t<T>>
struct is_map
: boost::mpl::bool_<
detail::has_key_type<T2>::value &&
@@ -62,7 +60,7 @@ namespace lua_check_impl
>
{};
- template<typename T, typename T2 = utils::remove_reference_t<T>>
+ template<typename T, typename T2 = std::remove_reference_t<T>>
struct is_pair
: boost::mpl::bool_<
detail::has_first_type<T2>::value &&
@@ -71,17 +69,17 @@ namespace lua_check_impl
{};
template<typename T>
- using remove_constref = utils::remove_const_t<utils::remove_reference_t<utils::remove_const_t<T>>>;
+ using remove_constref = std::remove_const_t<std::remove_reference_t<std::remove_const_t<T>>>;
//std::string
template<typename T>
- utils::enable_if_t<std::is_same<T, std::string>::value, std::string>
+ std::enable_if_t<std::is_same<T, std::string>::value, std::string>
lua_check(lua_State *L, int n)
{
return luaL_checkstring(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_same<T, std::string>::value, void>
+ std::enable_if_t<std::is_same<T, std::string>::value, void>
lua_push(lua_State *L, const T& val)
{
lua_pushlstring(L, val.c_str(), val.size());
@@ -89,13 +87,13 @@ namespace lua_check_impl
//config
template<typename T>
- utils::enable_if_t<std::is_same<T, config>::value, config>
+ std::enable_if_t<std::is_same<T, config>::value, config>
lua_check(lua_State *L, int n)
{
return luaW_checkconfig(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_same<T, config>::value, void>
+ std::enable_if_t<std::is_same<T, config>::value, void>
lua_push(lua_State *L, const config& val)
{
luaW_pushconfig(L, val);
@@ -103,13 +101,13 @@ namespace lua_check_impl
//location
template<typename T>
- utils::enable_if_t<std::is_same<T, map_location>::value, map_location>
+ std::enable_if_t<std::is_same<T, map_location>::value, map_location>
lua_check(lua_State *L, int n)
{
return luaW_checklocation(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_same<T, map_location>::value, void>
+ std::enable_if_t<std::is_same<T, map_location>::value, void>
lua_push(lua_State *L, const map_location& val)
{
luaW_pushlocation(L, val);
@@ -117,7 +115,7 @@ namespace lua_check_impl
//enums generated by MAKE_ENUM
template<typename T>
- utils::enable_if_t<std::is_base_of<enum_tag, T>::value, T>
+ std::enable_if_t<std::is_base_of<enum_tag, T>::value, T>
lua_check(lua_State *L, int n)
{
T val;
@@ -129,7 +127,7 @@ namespace lua_check_impl
return val;
}
template<typename T>
- utils::enable_if_t<std::is_base_of<enum_tag, T>::value, void>
+ std::enable_if_t<std::is_base_of<enum_tag, T>::value, void>
lua_push(lua_State *L, T val)
{
lua_check_impl::lua_push(L, val.to_string());
@@ -137,13 +135,13 @@ namespace lua_check_impl
//t_string
template<typename T>
- utils::enable_if_t<std::is_same<T, t_string>::value, t_string>
+ std::enable_if_t<std::is_same<T, t_string>::value, t_string>
lua_check(lua_State *L, int n)
{
return luaW_checktstring(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_same<T, t_string>::value, void>
+ std::enable_if_t<std::is_same<T, t_string>::value, void>
lua_push(lua_State *L, const t_string& val)
{
luaW_pushtstring(L, val);
@@ -151,13 +149,13 @@ namespace lua_check_impl
//bool
template<typename T>
- utils::enable_if_t<std::is_same<T, bool>::value, bool>
+ std::enable_if_t<std::is_same<T, bool>::value, bool>
lua_check(lua_State *L, int n)
{
return luaW_toboolean(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_same<T, bool>::value, void>
+ std::enable_if_t<std::is_same<T, bool>::value, void>
lua_push(lua_State *L, bool val)
{
lua_pushboolean(L, val);
@@ -165,13 +163,13 @@ namespace lua_check_impl
//double, float
template<typename T>
- utils::enable_if_t<std::is_floating_point<T>::value, T>
+ std::enable_if_t<std::is_floating_point<T>::value, T>
lua_check(lua_State *L, int n)
{
return luaL_checknumber(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_floating_point<T>::value, void>
+ std::enable_if_t<std::is_floating_point<T>::value, void>
lua_push(lua_State *L, T val)
{
lua_pushnumber(L, val);
@@ -179,14 +177,14 @@ namespace lua_check_impl
//integer types
template<typename T>
- utils::enable_if_t<std::is_integral<T>::value && !std::is_same<T, bool>::value, T>
+ std::enable_if_t<std::is_integral<T>::value && !std::is_same<T, bool>::value, T>
lua_check(lua_State *L, int n)
{
return luaL_checkinteger(L, n);
}
template<typename T>
- utils::enable_if_t<std::is_integral<T>::value && !std::is_same<T, bool>::value, void>
+ std::enable_if_t<std::is_integral<T>::value && !std::is_same<T, bool>::value, void>
lua_push(lua_State *L, T val)
{
lua_pushnumber(L, val);
@@ -195,7 +193,7 @@ namespace lua_check_impl
//std::pair
//Not sure if the not_<is_const> is required; only (maybe) if std::map matches is_container
template<typename T>
- utils::enable_if_t<is_pair<T>::value && !std::is_const<typename T::first_type>::value, T>
+ std::enable_if_t<is_pair<T>::value && !std::is_const<typename T::first_type>::value, T>
lua_check(lua_State *L, int n)
{
T result;
@@ -209,7 +207,7 @@ namespace lua_check_impl
return result;
}
template<typename T>
- utils::enable_if_t<is_pair<T>::value && !std::is_const<typename T::first_type>::value, void>
+ std::enable_if_t<is_pair<T>::value && !std::is_const<typename T::first_type>::value, void>
lua_push(lua_State *L, const T& val)
{
lua_newtable(L);
@@ -221,7 +219,7 @@ namespace lua_check_impl
//std::vector and similar but not std::string
template<typename T>
- utils::enable_if_t<is_container<T>::value && !std::is_same<T, std::string>::value, T>
+ std::enable_if_t<is_container<T>::value && !std::is_same<T, std::string>::value, T>
lua_check(lua_State * L, int n)
{
if (lua_istable(L, n))
@@ -251,7 +249,7 @@ namespace lua_check_impl
//also accepts things like std::vector<int>() | std::adaptors::transformed(..)
template<typename T>
- utils::enable_if_t<
+ std::enable_if_t<
is_container<T>::value && !std::is_same<T, std::string>::value && !is_map<T>::value
, void
>
@@ -270,7 +268,7 @@ namespace lua_check_impl
//accepts std::map TODO: add a check function for that
template<typename T>
- utils::enable_if_t<is_map<T>::value, void>
+ std::enable_if_t<is_map<T>::value, void>
lua_push(lua_State * L, const T& map )
{
lua_newtable(L);
diff --git a/src/sdl/rect.hpp b/src/sdl/rect.hpp
index e43b1c665c6..cd128331d9c 100644
--- a/src/sdl/rect.hpp
+++ b/src/sdl/rect.hpp
@@ -19,7 +19,6 @@
* Contains the SDL_Rect helper code.
*/
-#include "global.hpp"
#include "utils.hpp"
#include <SDL_rect.h>
diff --git a/src/sdl/userevent.hpp b/src/sdl/userevent.hpp
index da2539673a7..32d05988ef1 100644
--- a/src/sdl/userevent.hpp
+++ b/src/sdl/userevent.hpp
@@ -38,9 +38,8 @@ public:
event_.code = code;
}
- UserEvent(int type, int code, int data1, int data2) : UserEvent(type)
+ UserEvent(int type, int data1, int data2) : UserEvent(type)
{
- event_.code = code;
event_.data1 = reinterpret_cast<void*>(data1);
event_.data2 = reinterpret_cast<void*>(data2);
}
diff --git a/src/sdl/utils.cpp b/src/sdl/utils.cpp
index b30299b8ebd..ca475c09fbe 100644
--- a/src/sdl/utils.cpp
+++ b/src/sdl/utils.cpp
@@ -711,9 +711,9 @@ surface adjust_surface_color(const surface &surf, int red, int green, int blue)
g = (*beg) >> 8;
b = (*beg) >> 0;
- r = std::max<int>(0,std::min<int>(255,int(r)+red));
- g = std::max<int>(0,std::min<int>(255,int(g)+green));
- b = std::max<int>(0,std::min<int>(255,int(b)+blue));
+ r = std::max<int>(0,std::min<int>(255,static_cast<int>(r)+red));
+ g = std::max<int>(0,std::min<int>(255,static_cast<int>(g)+green));
+ b = std::max<int>(0,std::min<int>(255,static_cast<int>(b)+blue));
*beg = (alpha << 24) + (r << 16) + (g << 8) + b;
}
@@ -1207,7 +1207,7 @@ surface adjust_surface_alpha_add(const surface &surf, int amount)
g = (*beg) >> 8;
b = (*beg);
- alpha = uint8_t(std::max<int>(0,std::min<int>(255,int(alpha) + amount)));
+ alpha = uint8_t(std::max<int>(0,std::min<int>(255,static_cast<int>(alpha) + amount)));
*beg = (alpha << 24) + (r << 16) + (g << 8) + b;
}
@@ -1856,8 +1856,8 @@ surface rotate_any_surface(const surface& surf, float angle, int zoom, int offse
float max_x, max_y;
// convert angle to radiant (angle * 2 * PI) / 360
const float radians = angle * boost::math::constants::pi<float>() / 180;
- cosine = cos(radians);
- sine = sin(radians);
+ cosine = std::cos(radians);
+ sine = std::sin(radians);
// calculate the size of the dst image
src_w = surf->w * zoom;
src_h = surf->h * zoom;
@@ -1918,15 +1918,15 @@ void put_pixel(const surface& surf, surface_lock& surf_lock, int x, int y, uint3
*reinterpret_cast<uint16_t*>(dst) = pixel;
break;
case 3:
- if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
- dst[0] = (pixel >> 16) & 0xff;
- dst[1] = (pixel >> 8) & 0xff;
- dst[2] = pixel & 0xff;
- } else {
- dst[0] = pixel & 0xff;
- dst[1] = (pixel >> 8) & 0xff;
- dst[2] = (pixel >> 16) & 0xff;
- }
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+ dst[0] = (pixel >> 16) & 0xff;
+ dst[1] = (pixel >> 8) & 0xff;
+ dst[2] = pixel & 0xff;
+#else
+ dst[0] = pixel & 0xff;
+ dst[1] = (pixel >> 8) & 0xff;
+ dst[2] = (pixel >> 16) & 0xff;
+#endif
break;
case 4:
*reinterpret_cast<uint32_t*>(dst) = pixel;
@@ -1947,11 +1947,11 @@ uint32_t get_pixel(const surface& surf, const const_surface_lock& surf_lock, int
case 2:
return *reinterpret_cast<const uint16_t*>(src);
case 3:
- if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
- return src[0] << 16 | src[1] << 8 | src[2];
- else
- return src[0] | src[1] << 8 | src[2] << 16;
- break;
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+ return src[0] << 16 | src[1] << 8 | src[2];
+#else
+ return src[0] | src[1] << 8 | src[2] << 16;
+#endif
case 4:
return *reinterpret_cast<const uint32_t*>(src);
}
diff --git a/src/serialization/base64.cpp b/src/serialization/base64.cpp
index ddca67f160e..71b31f77916 100644
--- a/src/serialization/base64.cpp
+++ b/src/serialization/base64.cpp
@@ -15,6 +15,7 @@
#include "serialization/base64.hpp"
#include <vector>
+#include <string>
namespace {
const std::string base64_itoa_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
diff --git a/src/serialization/binary_or_text.cpp b/src/serialization/binary_or_text.cpp
index d7d41f73f25..d5a0defed82 100644
--- a/src/serialization/binary_or_text.cpp
+++ b/src/serialization/binary_or_text.cpp
@@ -19,11 +19,11 @@
*/
#include "serialization/binary_or_text.hpp"
+
#include "config.hpp"
#include "log.hpp"
-#include "wesconfig.h"
#include "serialization/parser.hpp"
-
+#include "wesconfig.h"
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filter/gzip.hpp>
@@ -31,38 +31,37 @@
static lg::log_domain log_config("config");
#define ERR_CF LOG_STREAM(err, log_config)
-config_writer::config_writer(
- std::ostream &out, compression::format compress) :
- filter_(),
- out_ptr_(compress ? &filter_ : &out), //ternary indirection creates a temporary
- out_(*out_ptr_), //now MSVC will allow binding to the reference member
- compress_(compress),
- level_(0),
- textdomain_(PACKAGE)
+config_writer::config_writer(std::ostream& out, compression::format compress)
+ : filter_()
+ , out_ptr_(compress ? &filter_ : &out) // ternary indirection creates a temporary
+ , out_(*out_ptr_) // now MSVC will allow binding to the reference member
+ , compress_(compress)
+ , level_(0)
+ , textdomain_(PACKAGE)
{
if(compress_ == compression::GZIP) {
filter_.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(9)));
filter_.push(out);
-
} else if(compress_ == compression::BZIP2) {
filter_.push(boost::iostreams::bzip2_compressor(boost::iostreams::bzip2_params()));
filter_.push(out);
}
}
-config_writer::config_writer(
- std::ostream &out, bool compress, int level) :
- filter_(),
- out_ptr_(compress ? &filter_ : &out), //ternary indirection creates a temporary
- out_(*out_ptr_), //now MSVC will allow binding to the reference member
- compress_(compress ? compression::GZIP : compression::NONE),
- level_(0),
- textdomain_(PACKAGE)
+
+config_writer::config_writer(std::ostream& out, bool compress, int level)
+ : filter_()
+ , out_ptr_(compress ? &filter_ : &out) // ternary indirection creates a temporary
+ , out_(*out_ptr_) // now MSVC will allow binding to the reference member
+ , compress_(compress ? compression::GZIP : compression::NONE)
+ , level_(0)
+ , textdomain_(PACKAGE)
{
if(compress_) {
- if (level >=0)
+ if(level >= 0) {
filter_.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(level)));
- else
+ } else {
filter_.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params()));
+ }
filter_.push(out);
}
@@ -70,32 +69,31 @@ config_writer::config_writer(
config_writer::~config_writer()
{
- //we only need this for gzip but we also do it for bz2 for unification.
- if(compress_ == compression::GZIP || compress_ == compression::BZIP2)
- {
+ // we only need this for gzip but we also do it for bz2 for unification.
+ if(compress_ == compression::GZIP || compress_ == compression::BZIP2) {
// prevent empty gz files because of https://svn.boost.org/trac/boost/ticket/5237
out_ << "\n";
}
}
-void config_writer::write(const config &cfg)
+void config_writer::write(const config& cfg)
{
::write(out_, cfg, level_);
}
-void config_writer::write_child(const std::string &key, const config &cfg)
+void config_writer::write_child(const std::string& key, const config& cfg)
{
open_child(key);
::write(out_, cfg, level_);
close_child(key);
}
-void config_writer::open_child(const std::string &key)
+void config_writer::open_child(const std::string& key)
{
::write_open_child(out_, key, level_++);
}
-void config_writer::close_child(const std::string &key)
+void config_writer::close_child(const std::string& key)
{
::write_close_child(out_, key, --level_);
}
diff --git a/src/serialization/preprocessor.cpp b/src/serialization/preprocessor.cpp
index 53104e7e6e1..8198a881f62 100644
--- a/src/serialization/preprocessor.cpp
+++ b/src/serialization/preprocessor.cpp
@@ -23,7 +23,6 @@
#include "buffered_istream.hpp"
#include "config.hpp"
#include "filesystem.hpp"
-#include "game_config.hpp"
#include "log.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/parser.hpp"
diff --git a/src/serialization/string_utils.cpp b/src/serialization/string_utils.cpp
index 31575110a77..9d6573940c9 100644
--- a/src/serialization/string_utils.cpp
+++ b/src/serialization/string_utils.cpp
@@ -480,7 +480,7 @@ std::string urlencode(const std::string &str)
res << '%';
res.width(2);
- res << int(c);
+ res << static_cast<int>(c);
}
return res.str();
@@ -831,16 +831,14 @@ std::pair<int, int> parse_range(const std::string& str)
std::vector<std::pair<int, int>> parse_ranges(const std::string& str)
{
- std::vector< std::pair< int, int >> to_return;
- std::vector<std::string> strs = utils::split(str);
- std::vector<std::string>::const_iterator i, i_end=strs.end();
- for(i = strs.begin(); i != i_end; ++i) {
- to_return.push_back(parse_range(*i));
+ std::vector<std::pair<int, int>> to_return;
+ for(const std::string& r : utils::split(str)) {
+ to_return.push_back(parse_range(r));
}
+
return to_return;
}
-
void ellipsis_truncate(std::string& str, const size_t size)
{
const size_t prev_size = str.length();
diff --git a/src/serialization/ucs4_convert_impl.hpp b/src/serialization/ucs4_convert_impl.hpp
index 3b58dbc523d..ddb707ebb8b 100644
--- a/src/serialization/ucs4_convert_impl.hpp
+++ b/src/serialization/ucs4_convert_impl.hpp
@@ -14,7 +14,7 @@
#pragma once
-#include "unicode_types.hpp"
+#include "utf8_exception.hpp"
#include "utils/math.hpp"
#include <cassert>
@@ -23,7 +23,7 @@ namespace ucs4_convert_impl
struct utf8_impl
{
static const char* get_name() { return "utf8"; }
- static size_t byte_size_from_ucs4_codepoint(ucs4::char_t ch)
+ static size_t byte_size_from_ucs4_codepoint(char32_t ch)
{
if(ch < (1u << 7))
return 1;
@@ -41,7 +41,7 @@ namespace ucs4_convert_impl
throw utf8::invalid_utf8_exception(); // Invalid UCS-4
}
- static int byte_size_from_utf8_first(utf8::char_t ch)
+ static int byte_size_from_utf8_first(char ch)
{
if (!(ch & 0x80)) {
return 1; // US-ASCII character, 1 byte
@@ -59,19 +59,19 @@ namespace ucs4_convert_impl
/**
* Writes a UCS-4 character to a UTF-8 stream.
*
- * @param out An object to write utf8::char_t. Required operations:
- * 1) push(utf8::char_t) to write a single character
+ * @param out An object to write char. Required operations:
+ * 1) push(char) to write a single character
* 2) can_push(size_t n) to check whether there is still
* enough space for n characters.
* @param ch The UCS-4 character to write to the stream.
*/
template<typename writer>
- static inline void write(writer out, ucs4::char_t ch)
+ static inline void write(writer out, char32_t ch)
{
size_t count = byte_size_from_ucs4_codepoint(ch);
assert(out.can_push(count));
if(count == 1) {
- out.push(static_cast<utf8::char_t>(ch));
+ out.push(static_cast<char>(ch));
} else {
for(int j = static_cast<int>(count) - 1; j >= 0; --j) {
unsigned char c = (ch >> (6 * j)) & 0x3f;
@@ -92,12 +92,12 @@ namespace ucs4_convert_impl
* to read.
*/
template<typename iitor_t>
- static inline ucs4::char_t read(iitor_t& input, const iitor_t& end)
+ static inline char32_t read(iitor_t& input, const iitor_t& end)
{
assert(input != end);
size_t size = byte_size_from_utf8_first(*input);
- ucs4::char_t current_char = static_cast<unsigned char>(*input);
+ char32_t current_char = static_cast<unsigned char>(*input);
// Convert the first character
if(size != 1) {
@@ -131,41 +131,41 @@ namespace ucs4_convert_impl
{
static const char* get_name() { return "utf16"; }
template<typename writer>
- static inline void write(writer out, ucs4::char_t ch)
+ static inline void write(writer out, char32_t ch)
{
- const ucs4::char_t bit17 = 0x10000;
+ const char32_t bit17 = 0x10000;
if(ch < bit17)
{
assert(out.can_push(1));
- out.push(static_cast<utf16::char_t>(ch));
+ out.push(static_cast<char16_t>(ch));
}
else
{
assert(out.can_push(2));
- const ucs4::char_t char20 = ch - bit17;
+ const char32_t char20 = ch - bit17;
assert(char20 < (1 << 20));
- const ucs4::char_t lead = 0xD800 + (char20 >> 10);
- const ucs4::char_t trail = 0xDC00 + (char20 & 0x3FF);
+ const char32_t lead = 0xD800 + (char20 >> 10);
+ const char32_t trail = 0xDC00 + (char20 & 0x3FF);
assert(lead < bit17);
assert(trail < bit17);
- out.push(static_cast<utf16::char_t>(lead));
- out.push(static_cast<utf16::char_t>(trail));
+ out.push(static_cast<char16_t>(lead));
+ out.push(static_cast<char16_t>(trail));
}
}
template<typename iitor_t>
- static inline ucs4::char_t read(iitor_t& input, const iitor_t& end)
+ static inline char32_t read(iitor_t& input, const iitor_t& end)
{
- const ucs4::char_t last10 = 0x3FF;
- const ucs4::char_t type_filter = 0xFC00;
- const ucs4::char_t type_lead = 0xD800;
- const ucs4::char_t type_trail = 0xDC00;
+ const char32_t last10 = 0x3FF;
+ const char32_t type_filter = 0xFC00;
+ const char32_t type_lead = 0xD800;
+ const char32_t type_trail = 0xDC00;
assert(input != end);
- ucs4::char_t current_char = static_cast<utf16::char_t>(*input);
+ char32_t current_char = static_cast<char16_t>(*input);
++input;
- ucs4::char_t type = current_char & type_filter;
+ char32_t type = current_char & type_filter;
if(type == type_trail)
{
//found trail without head
@@ -196,17 +196,17 @@ namespace ucs4_convert_impl
{
static const char* get_name() { return "UCS4"; }
template<typename writer>
- static inline void write(writer out, ucs4::char_t ch)
+ static inline void write(writer out, char32_t ch)
{
assert(out.can_push(1));
out.push(ch);
}
template<typename iitor_t>
- static inline ucs4::char_t read(iitor_t& input, const iitor_t& end)
+ static inline char32_t read(iitor_t& input, const iitor_t& end)
{
assert(input != end);
- ucs4::char_t current_char = *input;
+ char32_t current_char = *input;
++input;
return current_char;
}
@@ -216,19 +216,25 @@ namespace ucs4_convert_impl
struct convert_impl {};
template<>
- struct convert_impl<utf8::char_t>
+ struct convert_impl<char>
{
typedef utf8_impl type;
};
template<>
- struct convert_impl<utf16::char_t>
+ struct convert_impl<char16_t>
{
typedef utf16_impl type;
};
template<>
- struct convert_impl<ucs4::char_t>
+ struct convert_impl<wchar_t>
+ {
+ typedef utf16_impl type;
+ };
+
+ template<>
+ struct convert_impl<char32_t>
{
typedef utf32_impl type;
};
diff --git a/src/serialization/ucs4_iterator_base.hpp b/src/serialization/ucs4_iterator_base.hpp
index 26c650627e7..03f0587aee2 100644
--- a/src/serialization/ucs4_iterator_base.hpp
+++ b/src/serialization/ucs4_iterator_base.hpp
@@ -18,8 +18,6 @@
#include <cstddef> //ptrdiff_t
#include <cassert> //assert
-#include "unicode_types.hpp"
-
namespace ucs4
{
template<typename string_type, typename update_implementation>
@@ -27,10 +25,10 @@ namespace ucs4
{
public:
typedef std::input_iterator_tag iterator_category;
- typedef ucs4::char_t value_type;
+ typedef char32_t value_type;
typedef ptrdiff_t difference_type;
- typedef ucs4::char_t* pointer;
- typedef ucs4::char_t& reference;
+ typedef char32_t* pointer;
+ typedef char32_t& reference;
iterator_base(const string_type& str)
: current_char(0)
@@ -75,7 +73,7 @@ namespace ucs4
return *this;
}
- ucs4::char_t operator*() const
+ char32_t operator*() const
{
return current_char;
}
@@ -100,7 +98,7 @@ namespace ucs4
current_char = update_implementation::read(current_substr.second, string_end);
}
- ucs4::char_t current_char;
+ char32_t current_char;
typename string_type::const_iterator string_end;
std::pair<typename string_type::const_iterator, typename string_type::const_iterator> current_substr;
};
diff --git a/src/serialization/unicode.cpp b/src/serialization/unicode.cpp
index ad1dc94458c..59f7c71f698 100644
--- a/src/serialization/unicode.cpp
+++ b/src/serialization/unicode.cpp
@@ -48,18 +48,18 @@ static int byte_size_from_utf8_first(const unsigned char ch)
return count;
}
-utf8::string lowercase(const utf8::string& s)
+std::string lowercase(const std::string& s)
{
if(!s.empty()) {
utf8::iterator itor(s);
- utf8::string res;
+ std::string res;
for(;itor != utf8::iterator::end(s); ++itor) {
- ucs4::char_t uchar = *itor;
+ char32_t uchar = *itor;
// If wchar_t is less than 32 bits wide, we cannot apply towlower() to all codepoints
- if(uchar <= static_cast<ucs4::char_t>(std::numeric_limits<wchar_t>::max()))
+ if(uchar <= static_cast<char32_t>(std::numeric_limits<wchar_t>::max()))
uchar = towlower(static_cast<wchar_t>(uchar));
- res += unicode_cast<utf8::string>(uchar);
+ res += unicode_cast<std::string>(uchar);
}
res.append(itor.substr().second, s.end());
@@ -68,7 +68,7 @@ utf8::string lowercase(const utf8::string& s)
return s;
}
-size_t index(const utf8::string& str, const size_t index)
+size_t index(const std::string& str, const size_t index)
{
// chr counts characters, i is the codepoint index
// remark: several functions rely on the fallback to str.length()
@@ -83,7 +83,7 @@ size_t index(const utf8::string& str, const size_t index)
return i;
}
-size_t size(const utf8::string& str)
+size_t size(const std::string& str)
{
unsigned int chr, i = 0, len = str.size();
try {
@@ -96,12 +96,12 @@ size_t size(const utf8::string& str)
return chr;
}
-utf8::string& insert(utf8::string& str, const size_t pos, const utf8::string& insert)
+std::string& insert(std::string& str, const size_t pos, const std::string& insert)
{
return str.insert(index(str, pos), insert);
}
-utf8::string& erase(utf8::string& str, const size_t start, const size_t len)
+std::string& erase(std::string& str, const size_t start, const size_t len)
{
if (start > size(str)) return str;
unsigned pos = index(str, start);
@@ -114,17 +114,17 @@ utf8::string& erase(utf8::string& str, const size_t start, const size_t len)
}
}
-utf8::string& truncate(utf8::string& str, const size_t size)
+std::string& truncate(std::string& str, const size_t size)
{
return erase(str, size);
}
-void truncate_as_ucs4(utf8::string &str, const size_t size)
+void truncate_as_ucs4(std::string &str, const size_t size)
{
- ucs4::string u4_str = unicode_cast<ucs4::string>(str);
+ std::u32string u4_str = unicode_cast<std::u32string>(str);
if(u4_str.size() > size) {
u4_str.resize(size);
- str = unicode_cast<utf8::string>(u4_str);
+ str = unicode_cast<std::string>(u4_str);
}
}
diff --git a/src/serialization/unicode.hpp b/src/serialization/unicode.hpp
index 80aaf7179f5..1bf3f8884b3 100644
--- a/src/serialization/unicode.hpp
+++ b/src/serialization/unicode.hpp
@@ -16,7 +16,6 @@
#pragma once
#include "ucs4_iterator_base.hpp"
-#include "unicode_types.hpp"
#include "ucs4_convert_impl.hpp"
#include "unicode_cast.hpp"
@@ -30,7 +29,7 @@
* Wide strings are expected to be UTF-16.
*/
namespace utf16 {
- typedef ucs4::iterator_base<utf16::string, ucs4_convert_impl::convert_impl<char_t>::type> iterator;
+ typedef ucs4::iterator_base<std::u16string, ucs4_convert_impl::convert_impl<char16_t>::type> iterator;
}
/**
@@ -38,23 +37,23 @@ namespace utf16 {
* back and forth.
*/
namespace utf8 {
- typedef ucs4::iterator_base<std::string, ucs4_convert_impl::convert_impl<char_t>::type> iterator;
+ typedef ucs4::iterator_base<std::string, ucs4_convert_impl::convert_impl<char>::type> iterator;
/** Returns a lowercased version of the string. */
- utf8::string lowercase(const utf8::string& s);
+ std::string lowercase(const std::string& s);
/**
* Codepoint index corresponding to the nth character in a UTF-8 string.
*
* @return str.length() if there are less than @p index characters.
*/
- size_t index(const utf8::string& str, const size_t index);
+ size_t index(const std::string& str, const size_t index);
/** Length in characters of a UTF-8 string. */
- size_t size(const utf8::string& str);
+ size_t size(const std::string& str);
/** Insert a UTF-8 string at the specified position. */
- utf8::string& insert(utf8::string& str, const size_t pos, const utf8::string& insert);
+ std::string& insert(std::string& str, const size_t pos, const std::string& insert);
/**
* Erases a portion of a UTF-8 string.
@@ -66,7 +65,7 @@ namespace utf8 {
* @note This implementation does not check for valid UTF-8. Don't use it
* for user input.
*/
- utf8::string& erase(utf8::string& str, const size_t start, const size_t len = std::string::npos);
+ std::string& erase(std::string& str, const size_t start, const size_t len = std::string::npos);
/**
* Truncates a UTF-8 string to the specified number of characters.
@@ -77,7 +76,7 @@ namespace utf8 {
* @note This implementation does not check for valid UTF-8. Don't use it
* for user input.
*/
- utf8::string& truncate(utf8::string& str, const size_t size);
+ std::string& truncate(std::string& str, const size_t size);
/**
* Truncates a UTF-8 string to the specified number of characters.
@@ -92,5 +91,5 @@ namespace utf8 {
* codepoints.
* @param size The size to truncate to.
*/
- void truncate_as_ucs4(utf8::string& str, const size_t size);
+ void truncate_as_ucs4(std::string& str, const size_t size);
} // end namespace utf8
diff --git a/src/serialization/unicode_cast.hpp b/src/serialization/unicode_cast.hpp
index 47c26737190..fc1198078ab 100644
--- a/src/serialization/unicode_cast.hpp
+++ b/src/serialization/unicode_cast.hpp
@@ -90,11 +90,11 @@ typename ucs4_convert_impl::enableif<TD, typename TS::value_type>::type unicode_
* @return An instance of TD.
*/
template<typename TD>
-TD unicode_cast(ucs4::char_t onechar)
+TD unicode_cast(char32_t onechar)
{
using namespace ucs4_convert_impl;
typedef typename convert_impl<typename TD::value_type>::type impl_writer;
- typedef convert_impl<ucs4::char_t>::type impl_reader;
+ typedef convert_impl<char32_t>::type impl_reader;
typedef typename std::back_insert_iterator<TD> output_itor;
TD res;
diff --git a/src/serialization/unicode_types.hpp b/src/serialization/utf8_exception.hpp
similarity index 68%
rename from src/serialization/unicode_types.hpp
rename to src/serialization/utf8_exception.hpp
index 4c523508361..45b5ba8bacd 100644
--- a/src/serialization/unicode_types.hpp
+++ b/src/serialization/utf8_exception.hpp
@@ -14,20 +14,9 @@
#pragma once
-#include <string>
-#include <vector>
#include <exception>
-#include <cstdint>
-
-namespace ucs4 {
- typedef uint32_t char_t;
- typedef std::vector<char_t> string;
-}
namespace utf8 {
- typedef char char_t;
- typedef std::string string;
-
/**
* Thrown by operations encountering invalid UTF-8 data.
*
@@ -37,14 +26,3 @@ namespace utf8 {
*/
class invalid_utf8_exception : public std::exception {};
}
-
-/**
- * For Win32 API.
- *
- * On windows, wchar_t is defined as uint16_t.
- * Wide strings are expected to be UTF-16.
- */
-namespace utf16 {
- typedef wchar_t char_t;
- typedef std::vector<char_t> string;
-}
diff --git a/src/server/ban.cpp b/src/server/ban.cpp
index 17e0c3544a7..c828e50493c 100644
--- a/src/server/ban.cpp
+++ b/src/server/ban.cpp
@@ -174,9 +174,9 @@ static lg::log_domain log_server("server");
}
nick_ = cfg["nick"].str();
if (cfg.has_attribute("end_time"))
- end_time_ = lexical_cast_default<time_t>(cfg["end_time"], 0);
+ end_time_ = cfg["end_time"].to_time_t(0);
if (cfg.has_attribute("start_time"))
- start_time_ = lexical_cast_default<time_t>(cfg["start_time"], 0);
+ start_time_ = cfg["start_time"].to_time_t(0);
reason_ = cfg["reason"].str();
// only overwrite defaults if exists
@@ -329,8 +329,8 @@ static lg::log_domain log_server("server");
if (!time) return false;
if (duration.substr(0,4) == "TIME") {
- struct tm* loc;
- loc = localtime(time);
+ std::tm* loc;
+ loc = std::localtime(time);
size_t number = 0;
for (std::string::const_iterator i = duration.begin() + 4;
diff --git a/src/server/forum_user_handler.cpp b/src/server/forum_user_handler.cpp
index 0626088a789..e61057296ee 100644
--- a/src/server/forum_user_handler.cpp
+++ b/src/server/forum_user_handler.cpp
@@ -166,7 +166,7 @@ void fuh::set_is_moderator(const std::string& name, const bool& is_moderator) {
if(!user_exists(name)) return;
try {
- write_detail(name, "user_is_moderator", int(is_moderator));
+ write_detail(name, "user_is_moderator", static_cast<int>(is_moderator));
} catch (const sql_error& e) {
ERR_UH << "Could not set is_moderator for user '" << name << "' :" << e.message << std::endl;
}
@@ -295,7 +295,7 @@ time_t fuh::get_registrationdate(const std::string& user) {
void fuh::set_lastlogin(const std::string& user, const time_t& lastlogin) {
try {
- write_detail(user, "user_lastvisit", int(lastlogin));
+ write_detail(user, "user_lastvisit", static_cast<int>(lastlogin));
} catch (const sql_error& e) {
ERR_UH << "Could not set last visit for user '" << user << "' :" << e.message << std::endl;
}
diff --git a/src/server/game.cpp b/src/server/game.cpp
index b8c0005d7dc..d5f25cdb70e 100644
--- a/src/server/game.cpp
+++ b/src/server/game.cpp
@@ -1121,7 +1121,7 @@ bool game::process_turn(simple_wml::document& data, const socket_ptr& user)
continue;
}
- std::unique_ptr<simple_wml::document> message(new simple_wml::document);
+ auto message = std::make_unique<simple_wml::document>();
simple_wml::node& message_turn = message->root().add_child("turn");
simple_wml::node& message_turn_command = message_turn.add_child("command");
message_turn_command.set_attr("undo", "no");
@@ -1542,12 +1542,11 @@ bool game::remove_player(const socket_ptr& player, const bool disconnect, const
auto owner_iter = player_connections_.find(owner_);
if(owner_iter == player_connections_.end())
ERR_GAME << "game owner " << client_address(owner_) << "is not in player_connections_\n";
- else {
+ else
owner_iter->info().set_status(player::PLAYING);
- observers_.erase(std::remove(observers_.begin(), observers_.end(), owner_), observers_.end());
- players_.push_back(owner_);
- send_observerquit(owner_);
- }
+ observers_.erase(std::remove(observers_.begin(), observers_.end(), owner_), observers_.end());
+ players_.push_back(owner_);
+ send_observerquit(owner_);
}
// send the host a notification of removal of this side
diff --git a/src/server/player_network.cpp b/src/server/player_network.cpp
index 1c6452d5572..d2286f1675f 100644
--- a/src/server/player_network.cpp
+++ b/src/server/player_network.cpp
@@ -29,10 +29,10 @@ const size_t max_message_length = 256;
void truncate_message(const simple_wml::string_span& str, simple_wml::node& message)
{
// testing for msg.size() is not sufficient but we're not getting false negatives
- // and it's cheaper than always converting to ucs4::string.
+ // and it's cheaper than always converting to std::u32string.
if(str.size() > static_cast<int>(chat_message::max_message_length)) {
std::string tmp(str.begin(), str.end());
- // The string can contain utf-8 characters so truncate as ucs4::string otherwise
+ // The string can contain utf-8 characters so truncate as std::u32string otherwise
// a corrupted utf-8 string can be returned.
utf8::truncate_as_ucs4(tmp, max_message_length);
message.set_attr_dup("message", tmp.c_str());
diff --git a/src/server/send_receive_wml_helpers.ipp b/src/server/send_receive_wml_helpers.ipp
index bb9fcbb3002..6b253eb8ed6 100644
--- a/src/server/send_receive_wml_helpers.ipp
+++ b/src/server/send_receive_wml_helpers.ipp
@@ -159,7 +159,7 @@ void async_send_file(socket_ptr socket, const std::string& filename, Handler han
{
std::vector<boost::asio::const_buffer> buffers;
- size_t filesize = filesystem::file_size(filename);
+ std::size_t filesize = filesystem::file_size(filename);
int in_file(open(filename.c_str(), O_RDONLY));
sendfile_op<Handler, ErrorHandler> op = { socket, in_file, handler, error_handler, 0, 0 };
@@ -182,7 +182,7 @@ struct sendfile_op
bool pending_;
std::shared_ptr<handle_doc<Handler, ErrorHandler>> handle_send_doc_;
- void operator()(boost::system::error_code ec, std::size_t)
+ void operator()(boost::system::error_code, std::size_t)
{
bool failed = false;
if (!pending_)
@@ -240,7 +240,7 @@ void async_send_file(socket_ptr socket, const std::string& filename, Handler han
SetLastError(ERROR_SUCCESS);
- size_t filesize = filesystem::file_size(filename);
+ std::size_t filesize = filesystem::file_size(filename);
std::wstring filename_ucs2 = unicode_cast<std::wstring>(filename);
HANDLE in_file = CreateFileW(filename_ucs2.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
@@ -249,7 +249,7 @@ void async_send_file(socket_ptr socket, const std::string& filename, Handler han
throw std::runtime_error("Failed to open the file");
}
- sendfile_op<Handler, ErrorHandler> op = { socket, in_file, OVERLAPPED(), handler, error_handler, false };
+ sendfile_op<Handler, ErrorHandler> op = { socket, in_file, OVERLAPPED(), handler, error_handler, false, nullptr };
HANDLE event = CreateEvent(nullptr, TRUE, TRUE, nullptr);
if (GetLastError() != ERROR_SUCCESS)
diff --git a/src/server/server.cpp b/src/server/server.cpp
index 00edbc2a855..dbcbe935d70 100644
--- a/src/server/server.cpp
+++ b/src/server/server.cpp
@@ -455,7 +455,7 @@ void server::load_config()
admin_passwd_ = cfg_["passwd"].str();
motd_ = cfg_["motd"].str();
- lan_server_ = lexical_cast_default<time_t>(cfg_["lan_server"], 0);
+ lan_server_ = cfg_["lan_server"].to_time_t(0);
uh_name_ = cfg_["user_handler"].str();
deny_unregistered_login_ = cfg_["deny_unregistered_login"].to_bool();
@@ -497,7 +497,7 @@ void server::load_config()
if(versions.empty() == false) {
accepted_versions_ = utils::split(versions);
} else {
- accepted_versions_.push_back(game_config::version);
+ accepted_versions_.push_back(game_config::wesnoth_version.str());
accepted_versions_.push_back("test");
}
@@ -2359,7 +2359,7 @@ void server::version_handler(
assert(out != nullptr);
if(parameters.empty()) {
- *out << "Server version is " << game_config::version;
+ *out << "Server version is " << game_config::wesnoth_version.str();
return;
}
@@ -3021,7 +3021,7 @@ int main(int argc, char** argv)
<< " -V, --version Returns the server version.\n";
return 0;
} else if(val == "--version" || val == "-V") {
- std::cout << "Battle for Wesnoth server " << game_config::version << "\n";
+ std::cout << "Battle for Wesnoth server " << game_config::wesnoth_version.str() << "\n";
return 0;
} else if(val == "--daemon" || val == "-d") {
#ifdef _WIN32
diff --git a/src/show_dialog.cpp b/src/show_dialog.cpp
index 2a8ab92ca97..b5c3ba005db 100644
--- a/src/show_dialog.cpp
+++ b/src/show_dialog.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/show_dialog.hpp b/src/show_dialog.hpp
index 27d31f1120a..265bdbb24d2 100644
--- a/src/show_dialog.hpp
+++ b/src/show_dialog.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/side_filter.cpp b/src/side_filter.cpp
index 68f5a628647..7b49c2e3c12 100644
--- a/src/side_filter.cpp
+++ b/src/side_filter.cpp
@@ -158,7 +158,7 @@ bool side_filter::match_internal(const team &t) const
const std::vector<int>& teams = enemy_filter_->get_teams();
if(teams.empty()) return false;
for(const int side : teams) {
- if(!(fc_->get_disp_context().teams())[side - 1].is_enemy(t.side()))
+ if(!fc_->get_disp_context().get_team(side).is_enemy(t.side()))
return false;
}
}
@@ -170,7 +170,7 @@ bool side_filter::match_internal(const team &t) const
const std::vector<int>& teams = allied_filter_->get_teams();
if(teams.empty()) return false;
for(const int side : teams) {
- if((fc_->get_disp_context().teams())[side - 1].is_enemy(t.side()))
+ if(fc_->get_disp_context().get_team(side).is_enemy(t.side()))
return false;
}
}
@@ -182,7 +182,7 @@ bool side_filter::match_internal(const team &t) const
const std::vector<int>& teams = has_enemy_filter_->get_teams();
bool found = false;
for(const int side : teams) {
- if((fc_->get_disp_context().teams())[side - 1].is_enemy(t.side()))
+ if(fc_->get_disp_context().get_team(side).is_enemy(t.side()))
{
found = true;
break;
@@ -198,7 +198,7 @@ bool side_filter::match_internal(const team &t) const
const std::vector<int>& teams = has_ally_filter_->get_teams();
bool found = false;
for(const int side : teams) {
- if(!(fc_->get_disp_context().teams())[side - 1].is_enemy(t.side()))
+ if(!fc_->get_disp_context().get_team(side).is_enemy(t.side()))
{
found = true;
break;
diff --git a/src/statistics.cpp b/src/statistics.cpp
index ab615677960..c4150f91669 100644
--- a/src/statistics.cpp
+++ b/src/statistics.cpp
@@ -441,8 +441,8 @@ stats& attack_context::defender_stats()
void attack_context::attack_expected_damage(double attacker_inflict_, double defender_inflict_)
{
- int attacker_inflict = round_double(attacker_inflict_ * stats::decimal_shift);
- int defender_inflict = round_double(defender_inflict_ * stats::decimal_shift);
+ int attacker_inflict = std::round(attacker_inflict_ * stats::decimal_shift);
+ int defender_inflict = std::round(defender_inflict_ * stats::decimal_shift);
stats &att_stats = attacker_stats(), &def_stats = defender_stats();
att_stats.expected_damage_inflicted += attacker_inflict;
att_stats.expected_damage_taken += defender_inflict;
diff --git a/src/synced_commands.cpp b/src/synced_commands.cpp
index ef4c39f3f3b..b62ae99d7ba 100644
--- a/src/synced_commands.cpp
+++ b/src/synced_commands.cpp
@@ -406,10 +406,6 @@ namespace
std::string message;
utils::string_map i18n_vars = {{ "player", current_team.current_player() }};
- if(i18n_vars["player"].empty()) {
- i18n_vars["player"] = _("(unknown player)");
- }
-
if(message_is_command) {
i18n_vars["command"] = text;
message = VGETTEXT("The :$command debug command was used during $playerÔÇÖs turn", i18n_vars);
diff --git a/src/team.cpp b/src/team.cpp
index 3a803d73ce6..82d7f9d71d4 100644
--- a/src/team.cpp
+++ b/src/team.cpp
@@ -422,6 +422,18 @@ void team::write(config& cfg) const
cfg["action_bonus_count"] = action_bonus_count_;
}
+void team::fix_villages(const gamemap &map)
+{
+ for (auto it = villages_.begin(); it != villages_.end(); ) {
+ if (map.is_village(*it)) {
+ ++it;
+ }
+ else {
+ it = villages_.erase(it);
+ }
+ }
+}
+
game_events::pump_result_t team::get_village(const map_location& loc, const int owner_side, game_data* gamedata)
{
villages_.insert(loc);
@@ -741,7 +753,7 @@ void validate_side(int side)
return;
}
- if(side < 1 || side > int(resources::gameboard->teams().size())) {
+ if(side < 1 || side > static_cast<int>(resources::gameboard->teams().size())) {
throw game::game_error("invalid side(" + std::to_string(side) + ") found in unit definition");
}
}
diff --git a/src/team.hpp b/src/team.hpp
index 066e4c72f6f..76e32d214fe 100644
--- a/src/team.hpp
+++ b/src/team.hpp
@@ -177,6 +177,7 @@ public:
void write(config& cfg) const;
+ void fix_villages(const gamemap &map);
game_events::pump_result_t get_village(const map_location&, const int owner_side, game_data * fire_event); //!< Acquires a village from owner_side. Pointer fire_event should be the game_data for the game if it is desired to fire an event -- a "capture" event with owner_side variable scoped in will be fired. For no event, pass it nullptr. Default is the resources::gamedata pointer
void lose_village(const map_location&);
void clear_villages() { villages_.clear(); }
diff --git a/src/terrain/builder.cpp b/src/terrain/builder.cpp
index 314f68015ea..3c74a2ebeae 100644
--- a/src/terrain/builder.cpp
+++ b/src/terrain/builder.cpp
@@ -562,14 +562,14 @@ void terrain_builder::rotate(terrain_constraint& ret, int angle)
for(rule_imagelist::iterator itor = ret.images.begin(); itor != ret.images.end(); ++itor) {
double vx, vy, rx, ry;
- vx = double(itor->basex) - double(tilewidth_) / 2;
- vy = double(itor->basey) - double(tilewidth_) / 2;
+ vx = static_cast<double>(itor->basex) - static_cast<double>(tilewidth_) / 2;
+ vy = static_cast<double>(itor->basey) - static_cast<double>(tilewidth_) / 2;
rx = xyrotations[angle].xx * vx + xyrotations[angle].xy * vy;
ry = xyrotations[angle].yx * vx + xyrotations[angle].yy * vy;
- itor->basex = int(rx + tilewidth_ / 2);
- itor->basey = int(ry + tilewidth_ / 2);
+ itor->basex = static_cast<int>(rx + tilewidth_ / 2);
+ itor->basey = static_cast<int>(ry + tilewidth_ / 2);
// std::cerr << "Rotation: from " << vx << ", " << vy << " to " << itor->basex <<
// ", " << itor->basey << "\n";
diff --git a/src/terrain/filter.cpp b/src/terrain/filter.cpp
index 1bc230153a6..3dc91bc93d9 100644
--- a/src/terrain/filter.cpp
+++ b/src/terrain/filter.cpp
@@ -155,7 +155,14 @@ bool terrain_filter::match_internal(const map_location& loc, const unit* ref_uni
}
}
if (cfg_.has_attribute("location_id")) {
- if (loc != fc_->get_disp_context().map().special_location(cfg_["location_id"])) {
+ std::set<map_location> matching_locs;
+ for(const auto& id : utils::split(cfg_["location_id"])) {
+ map_location test_loc = fc_->get_disp_context().map().special_location(id);
+ if(test_loc.valid()) {
+ matching_locs.insert(test_loc);
+ }
+ }
+ if (matching_locs.count(loc) == 0) {
return false;
}
}
@@ -467,8 +474,14 @@ public:
static void filter_special_loc(T&& src, location_set& dest, const terrain_filter& filter, const F1& f1, const F2& f2)
{
if (filter.cfg_.has_attribute("location_id")) {
- map_location loc2 = filter.fc_->get_disp_context().map().special_location(filter.cfg_["location_id"]);
- filter_final(src, dest, filter, f1, f2, [loc2](const map_location& loc) { return loc == loc2; });
+ std::set<map_location> matching_locs;
+ for(const auto& id : utils::split(filter.cfg_["location_id"])) {
+ map_location test_loc = filter.fc_->get_disp_context().map().special_location(id);
+ if(test_loc.valid()) {
+ matching_locs.insert(test_loc);
+ }
+ }
+ filter_final(src, dest, filter, f1, f2, [matching_locs](const map_location& loc) { return matching_locs.count(loc) > 0; });
}
else {
filter_final(src, dest, filter, f1, f2, no_filter());
@@ -544,9 +557,11 @@ void terrain_filter::get_locs_impl(std::set<map_location>& locs, const unit* ref
terrain_filterimpl::filter_special_loc(area, match_set, *this, terrain_filterimpl::no_filter(), terrain_filterimpl::no_filter());
}
else if (cfg_.has_attribute("location_id")) {
- map_location loc2 = fc_->get_disp_context().map().special_location(cfg_["location_id"]);
- if (loc2.valid()) {
- match_set.insert(loc2);
+ for(const auto& id : utils::split(cfg_["location_id"])) {
+ map_location test_loc = fc_->get_disp_context().map().special_location(id);
+ if(test_loc.valid()) {
+ match_set.insert(test_loc);
+ }
}
}
else {
diff --git a/src/terrain/filter.hpp b/src/terrain/filter.hpp
index 41128256dcd..d9b548e6b98 100644
--- a/src/terrain/filter.hpp
+++ b/src/terrain/filter.hpp
@@ -14,7 +14,6 @@
#pragma once
-#include "game_config.hpp"
#include "pathutils.hpp"
#include "terrain/translation.hpp"
#include "variable.hpp"
diff --git a/src/terrain/translation.hpp b/src/terrain/translation.hpp
index 95e75476b1e..d6638338335 100644
--- a/src/terrain/translation.hpp
+++ b/src/terrain/translation.hpp
@@ -80,15 +80,12 @@ namespace t_translation {
ter_map() = default;
ter_map(const ter_map&) = default;
-#if !defined(_MSC_VER) || _MSC_VER >= 1900
ter_map(ter_map&&) = default;
-#endif
+
ter_map(int w, int h, terrain_code fill = terrain_code()) : data(w * h, fill), w(w), h(h) {}
ter_map & operator= (const ter_map &) = default;
-#if !defined(_MSC_VER) || _MSC_VER >= 1900
ter_map & operator= (ter_map &&) = default;
-#endif
terrain_code& get(int x, int y) { size_t index = x * h + y; return data.at(index); }
const terrain_code& get(int x, int y) const { size_t index = x * h + y; return data.at(index); }
diff --git a/src/tests/gui/test_gui2.cpp b/src/tests/gui/test_gui2.cpp
index fea17bec17e..4d1ba7bee40 100644
--- a/src/tests/gui/test_gui2.cpp
+++ b/src/tests/gui/test_gui2.cpp
@@ -852,7 +852,7 @@ struct dialog_tester<mp_lobby>
wesnothd_connection_init init;
std::vector<std::string> installed_addons;
mp::lobby_info li;
- dialog_tester() : connection(wesnothd_connection::create("", "")), init(*connection), li(game_config, installed_addons)
+ dialog_tester() : connection(wesnothd_connection::create("", "")), init(*connection), li(installed_addons)
{
}
mp_lobby* create()
@@ -881,7 +881,7 @@ struct dialog_tester<lobby_player_info>
mp::lobby_info li;
dialog_tester()
: connection(wesnothd_connection::create("", "")), init(*connection)
- , ui(c), li(c, installed_addons)
+ , ui(c), li(installed_addons)
{
}
lobby_player_info* create()
diff --git a/src/tests/test_formula_function.cpp b/src/tests/test_formula_function.cpp
index 02e7d397711..d076a8201e8 100644
--- a/src/tests/test_formula_function.cpp
+++ b/src/tests/test_formula_function.cpp
@@ -161,14 +161,14 @@ BOOST_AUTO_TEST_CASE(test_formula_function_math)
BOOST_CHECK_EQUAL(formula("log(8,2)").evaluate().as_int(), 3);
BOOST_CHECK_EQUAL(formula("log(12)").evaluate().as_decimal(),
- static_cast<int>(round(1000.0 * log(12))));
+ static_cast<int>(round(1000.0 * std::log(12))));
BOOST_CHECK_EQUAL(formula("exp(3)").evaluate().as_decimal(),
- static_cast<int>(round(1000.0 * exp(3))));
+ static_cast<int>(round(1000.0 * std::exp(3))));
}
BOOST_AUTO_TEST_CASE(test_formula_function_trig)
{
- const double pi = 4. * atan(1.);
+ const double pi = 4. * std::atan(1.);
map_formula_callable variables;
@@ -178,12 +178,12 @@ BOOST_AUTO_TEST_CASE(test_formula_function_trig)
BOOST_CHECK_EQUAL(
formula("sin(x)")
.evaluate(variables).as_decimal()
- , static_cast<int>(round(1000. * sin(x * pi / 180.))));
+ , static_cast<int>(round(1000. * std::sin(x * pi / 180.))));
BOOST_CHECK_EQUAL(
formula("cos(x)")
.evaluate(variables).as_decimal()
- , static_cast<int>(round(1000. * cos(x * pi / 180.))));
+ , static_cast<int>(round(1000. * std::cos(x * pi / 180.))));
if(x % 90 == 0 && x % 180 != 0) {
BOOST_CHECK(
@@ -193,7 +193,7 @@ BOOST_AUTO_TEST_CASE(test_formula_function_trig)
BOOST_CHECK_EQUAL(
formula("tan(x)")
.evaluate(variables).as_decimal(),
- static_cast<int>(round(1000. * tan(x * pi / 180.))));
+ static_cast<int>(round(1000. * std::tan(x * pi / 180.))));
}
}
}
diff --git a/src/tests/test_image_modifications.cpp b/src/tests/test_image_modifications.cpp
index e6745ae7553..61bf452442d 100644
--- a/src/tests/test_image_modifications.cpp
+++ b/src/tests/test_image_modifications.cpp
@@ -502,10 +502,9 @@ BOOST_AUTO_TEST_CASE(test_blit_modification_decoding_invalid_args)
modification::decode("~BLIT()"
"~BLIT(wesnoth-icon.png,1,-2)"
"~BLIT(wesnoth-icon.png,-1,2)"
- "~BLIT(wesnoth-icon.png,-1,-2)"
- "~BLIT(wesnoth-icon.png,1,2,3)");
+ "~BLIT(wesnoth-icon.png,-1,-2)");
- BOOST_CHECK_EQUAL(queue.size(), 3);
+ BOOST_CHECK_EQUAL(queue.size(), 0);
}
/** Tests if the MASK modification with one argument is correctly decoded
diff --git a/src/tests/test_sdl_utils.cpp b/src/tests/test_sdl_utils.cpp
deleted file mode 100644
index 33751e95cca..00000000000
--- a/src/tests/test_sdl_utils.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- Copyright (C) 2012 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
-*/
-
-//#define GETTEXT_DOMAIN "wesnoth-test"
-//
-//#include "tests/test_sdl_utils.hpp"
-//
-//#include "picture.hpp"
-//
-//#include "utils/functional.hpp"
-//#include <boost/test/auto_unit_test.hpp>
-//
-//#include <iomanip>
-
-//static const std::string root = "data/test/test/image";
-
-//static void
-//compare_image(
-// const surface& src
-// , const surface& dst
-// , const std::string message)
-//{
-// BOOST_REQUIRE_MESSAGE(
-// src->w == dst->w
-// , message
-// << "source width ┬╗"
-// << src->w
-// << "« destination width »"
-// << dst->w
-// << "«.\n"
-// );
-//
-// BOOST_REQUIRE_MESSAGE(
-// src->h == dst->h
-// , message
-// << "source height ┬╗"
-// << src->w
-// << "« destination height »"
-// << dst->w
-// << "«.\n"
-// );
-//
-// const_surface_lock src_lock(src);
-// const_surface_lock dst_lock(dst);
-//
-// const uint32_t* src_pixels = src_lock.pixels();
-// const uint32_t* dst_pixels = dst_lock.pixels();
-//
-// const unsigned pixels = src->w * src->h;
-//
-// unsigned matches = 0;
-//
-// for(unsigned i = 0; i < pixels; ++i, ++src_pixels, ++dst_pixels) {
-// matches += (*src_pixels == *dst_pixels);
-// }
-//
-// BOOST_CHECK_MESSAGE(
-// pixels == matches
-// , message
-// << "of the " << pixels
-// << " pixels in the image " << matches
-// << " match.\n"
-// );
-//}
-
-//static void
-//test_blend(const surface& dst, const uint8_t amount, const uint32_t color)
-//{
-// std::stringstream sstr;
-// sstr << std::hex << std::setfill('0')
-// << "Blend image amount ┬╗"
-// << std::setw(2) << static_cast<uint32_t>(amount)
-// << "« color »"
-// << std::setw(8) << color
-// << "« : ";
-//
-// const std::string filename =
-// blend_get_filename("data/test/test/image/blend/", amount, color);
-//
-// BOOST_REQUIRE_EQUAL(image::exists(filename), true);
-//
-// const surface& src = image::get_image(filename);
-// compare_image(src, dst, sstr.str());
-//}
-
-//BOOST_AUTO_TEST_CASE(test_blend_surface)
-//{
-//
-// BOOST_REQUIRE_EQUAL(image::exists(root + "/base.png"), true);
-//
-// const surface base = image::get_image(root + "/base.png");
-//
-// blend_image(base, std::bind(&test_blend, _1, _2, _3));
-//}
diff --git a/src/tests/test_sdl_utils.hpp b/src/tests/test_sdl_utils.hpp
deleted file mode 100644
index a6aebb8ce87..00000000000
--- a/src/tests/test_sdl_utils.hpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- Copyright (C) 2012 - 2018 by Mark de Wever <koraq@xs4all.nl>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY.
-
- See the COPYING file for more details.
-*/
-
-#pragma once
-
-#include "sdl/surface.hpp"
-
-#include "utils/functional.hpp"
-
-typedef std::function<
- void(const surface&, const double, const uint32_t)>
- tblend_functor;
-
-
-inline void
-blend_image(const surface& src, tblend_functor functor)
-{
- for(uint32_t color = 0x00FF0000; color != 0x00000000; color >>= 8) {
- for(int i = 0xf; i < 0x100; i += 0x10) {
- const surface dst = blend_surface(src, i / 255., color);
- if(functor) {
- functor(dst, i, color);
- }
- }
- }
-}
-
-inline std::string
-blend_get_filename(std::string root, const uint8_t amount, const uint32_t color)
-{
- // The name of the file is
- // A the amount of blended [0..256) as hex.
- // C the color to blend with as hex.
- char filename[] = "AA_CCCCCCCC.png";
- snprintf(filename, sizeof(filename), "%02X_%08X.png", amount, color);
-
- return root + filename;
-}
diff --git a/src/tests/test_serialization.cpp b/src/tests/test_serialization.cpp
index e81659e3b6e..1e9f449107a 100644
--- a/src/tests/test_serialization.cpp
+++ b/src/tests/test_serialization.cpp
@@ -41,7 +41,7 @@ BOOST_AUTO_TEST_CASE( utils_join_test )
BOOST_AUTO_TEST_CASE( utils_unicode_test )
{
- utf8::string unicode = "├╝nicodÔé¼ check";
+ std::string unicode = "├╝nicodÔé¼ check";
BOOST_CHECK( utf8::size(unicode) == 13 );
int euro = utf8::index(unicode,6);
@@ -49,23 +49,23 @@ BOOST_AUTO_TEST_CASE( utils_unicode_test )
BOOST_CHECK( utf8::truncate(unicode,3) == "├╝ni");
- utf8::string apple_u8("apple");
- ucs4::string apple_u4 = unicode_cast<ucs4::string>(apple_u8);
- utf16::string apple_u16 = unicode_cast<utf16::string>(apple_u4);
+ std::string apple_u8("apple");
+ std::u32string apple_u4 = unicode_cast<std::u32string>(apple_u8);
+ std::u16string apple_u16 = unicode_cast<std::u16string>(apple_u4);
BOOST_CHECK( apple_u4.size() == 5 );
- BOOST_CHECK_EQUAL( apple_u8, unicode_cast<utf8::string>(apple_u4) );
- BOOST_CHECK_EQUAL( apple_u8, unicode_cast<utf8::string>(apple_u16) );
- BOOST_CHECK( apple_u4 == unicode_cast<ucs4::string>(apple_u16) );
- BOOST_CHECK( apple_u16 == unicode_cast<utf16::string>(apple_u4) );
+ BOOST_CHECK_EQUAL( apple_u8, unicode_cast<std::string>(apple_u4) );
+ BOOST_CHECK_EQUAL( apple_u8, unicode_cast<std::string>(apple_u16) );
+ BOOST_CHECK( apple_u4 == unicode_cast<std::u32string>(apple_u16) );
+ BOOST_CHECK( apple_u16 == unicode_cast<std::u16string>(apple_u4) );
BOOST_CHECK_EQUAL( apple_u8.size(), apple_u16.size() );
- ucs4::string water_u4;
+ std::u32string water_u4;
water_u4.push_back(0x6C34);
- utf8::string water_u8 = unicode_cast<utf8::string>(water_u4);
- utf16::string water_u16 = unicode_cast<utf16::string>(water_u4);
+ std::string water_u8 = unicode_cast<std::string>(water_u4);
+ std::u16string water_u16 = unicode_cast<std::u16string>(water_u4);
- BOOST_CHECK_EQUAL(water_u4[0], static_cast<ucs4::char_t>(water_u16[0]));
+ BOOST_CHECK_EQUAL(water_u4[0], static_cast<char32_t>(water_u16[0]));
#if defined(_WIN32) || defined(_WIN64)
// Windows complains it can't be represented in the currentl code-page.
// So instead, check directly for its UTF-8 representation.
@@ -76,21 +76,21 @@ BOOST_AUTO_TEST_CASE( utils_unicode_test )
#if defined(_WIN32) || defined(_WIN64)
// Same as above.
- utf8::string nonbmp_u8("\xF0\x90\x80\x80");
+ std::string nonbmp_u8("\xF0\x90\x80\x80");
#else
- utf8::string nonbmp_u8("\U00010000");
+ std::string nonbmp_u8("\U00010000");
#endif
- ucs4::string nonbmp_u4 = unicode_cast<ucs4::string>(nonbmp_u8);
- utf16::string nonbmp_u16 = unicode_cast<utf16::string>(nonbmp_u4);
+ std::u32string nonbmp_u4 = unicode_cast<std::u32string>(nonbmp_u8);
+ std::u16string nonbmp_u16 = unicode_cast<std::u16string>(nonbmp_u4);
BOOST_CHECK_EQUAL(nonbmp_u8.size(), 4u);
BOOST_CHECK_EQUAL(nonbmp_u4[0], 0x10000u);
BOOST_CHECK_EQUAL(nonbmp_u16[0], 0xD800);
BOOST_CHECK_EQUAL(nonbmp_u16[1], 0xDC00);
- BOOST_CHECK_EQUAL(nonbmp_u8, unicode_cast<utf8::string>(nonbmp_u4));
- BOOST_CHECK_EQUAL(nonbmp_u8, unicode_cast<utf8::string>(nonbmp_u16));
- BOOST_CHECK(nonbmp_u16 == unicode_cast<utf16::string>(nonbmp_u4));
- BOOST_CHECK(nonbmp_u4 == unicode_cast<ucs4::string>(nonbmp_u16));
+ BOOST_CHECK_EQUAL(nonbmp_u8, unicode_cast<std::string>(nonbmp_u4));
+ BOOST_CHECK_EQUAL(nonbmp_u8, unicode_cast<std::string>(nonbmp_u16));
+ BOOST_CHECK(nonbmp_u16 == unicode_cast<std::u16string>(nonbmp_u4));
+ BOOST_CHECK(nonbmp_u4 == unicode_cast<std::u32string>(nonbmp_u16));
}
BOOST_AUTO_TEST_CASE( test_lowercase )
diff --git a/src/tests/utils/game_config_manager_tests.cpp b/src/tests/utils/game_config_manager_tests.cpp
index 31c6bde8d61..a6c59d36653 100644
--- a/src/tests/utils/game_config_manager_tests.cpp
+++ b/src/tests/utils/game_config_manager_tests.cpp
@@ -63,7 +63,6 @@ namespace test_utils {
setlocale(LC_ALL, "English");
#else
std::setlocale(LC_ALL, "C");
- translation::init();
#endif
const std::string& intl_dir = filesystem::get_intl_dir();
translation::bind_textdomain("wesnoth", intl_dir.c_str(), "UTF-8");
diff --git a/src/theme.cpp b/src/theme.cpp
index 88a332d7519..214cb858420 100644
--- a/src/theme.cpp
+++ b/src/theme.cpp
@@ -16,8 +16,6 @@
#include "theme.hpp"
-#include "desktop/battery_info.hpp"
-#include "display.hpp"
#include "gettext.hpp"
#include "hotkey/hotkey_command.hpp"
#include "hotkey/hotkey_item.hpp"
@@ -26,8 +24,6 @@
#include "serialization/string_utils.hpp"
#include "wml_exception.hpp"
-#include <utility>
-
static lg::log_domain log_display("display");
#define DBG_DP LOG_STREAM(debug, log_display)
#define LOG_DP LOG_STREAM(info, log_display)
@@ -460,19 +456,6 @@ theme::status_item::status_item(const config& cfg)
}
}
-SDL_Rect& theme::countdown::location(const SDL_Rect& screen) const
-{
- if(!desktop::battery_info::does_device_have_battery()) {
- const object* battery = display::get_singleton()->get_theme().
- get_status_item("battery");
- if(battery != nullptr) {
- return battery->location(screen);
- }
- }
-
- return status_item::location(screen);
-}
-
theme::panel::panel(const config& cfg)
: object(cfg)
, image_(cfg["image"])
@@ -600,29 +583,6 @@ theme::theme(const config& cfg, const SDL_Rect& screen)
set_resolution(screen);
}
-theme& theme::operator=(theme&& other)
-{
- theme_reset_event_ = other.theme_reset_event_;
- known_themes = std::move(other.known_themes);
- cur_theme = std::move(other.cur_theme);
- cfg_ = std::move(other.cfg_);
- panels_ = std::move(other.panels_);
- labels_ = std::move(other.labels_);
- menus_ = std::move(other.menus_);
- actions_ = std::move(other.actions_);
- sliders_ = std::move(other.sliders_);
- context_ = other.context_;
- action_context_ = other.action_context_;
- status_ = std::move(other.status_);
- main_map_ = other.main_map_;
- mini_map_ = other.mini_map_;
- unit_image_ = other.unit_image_;
- palette_ = other.palette_;
- border_ = other.border_;
-
- return *this;
-}
-
bool theme::set_resolution(const SDL_Rect& screen)
{
bool result = false;
@@ -708,11 +668,7 @@ void theme::add_object(const config& cfg)
if(const config& status_cfg = cfg.child("status")) {
for(const config::any_child& i : status_cfg.all_children_range()) {
- if(i.key != "report_countdown") {
- status_[i.key].reset(new status_item(i.cfg));
- } else {
- status_[i.key].reset(new countdown(i.cfg));
- }
+ status_.emplace(i.key, status_item(i.cfg));
}
if(const config& unit_image_cfg = status_cfg.child("unit_image")) {
unit_image_ = object(unit_image_cfg);
@@ -906,9 +862,9 @@ theme::object& theme::find_element(const std::string& id)
const theme::status_item* theme::get_status_item(const std::string& key) const
{
- const auto& i = status_.find(key);
+ const std::map<std::string, status_item>::const_iterator i = status_.find(key);
if(i != status_.end())
- return i->second.get();
+ return &i->second;
else
return nullptr;
}
diff --git a/src/theme.hpp b/src/theme.hpp
index a50f8c8cdb6..8db2e158dde 100644
--- a/src/theme.hpp
+++ b/src/theme.hpp
@@ -23,7 +23,6 @@
#include "config.hpp"
#include "generic_event.hpp"
-#include <memory>
#include <SDL_rect.h>
struct _rect { size_t x1,y1,x2,y2; };
@@ -45,7 +44,7 @@ class theme
object(const config& cfg);
virtual ~object() { }
- virtual SDL_Rect& location(const SDL_Rect& screen) const;
+ SDL_Rect& location(const SDL_Rect& screen) const;
const SDL_Rect& get_location() const { return loc_; }
const std::string& get_id() const { return id_; }
@@ -142,15 +141,6 @@ public:
color_t font_rgb_;
};
- class countdown : public status_item
- {
- public:
- explicit countdown(const config& cfg) : status_item(cfg)
- {}
-
- SDL_Rect& location(const SDL_Rect& screen) const override;
- };
-
class panel : public object
{
public:
@@ -248,10 +238,6 @@ public:
};
explicit theme(const config& cfg, const SDL_Rect& screen);
- theme(const theme&) = delete;
- theme& operator=(const theme&) = delete;
- theme& operator=(theme&&);
-
bool set_resolution(const SDL_Rect& screen);
void modify(const config &cfg);
@@ -312,7 +298,7 @@ private:
menu context_;
action action_context_;
- std::map<std::string, std::unique_ptr<status_item>> status_;
+ std::map<std::string,status_item> status_;
object main_map_, mini_map_, unit_image_, palette_;
diff --git a/src/tod_manager.cpp b/src/tod_manager.cpp
index 4568a459888..e425c3731e6 100644
--- a/src/tod_manager.cpp
+++ b/src/tod_manager.cpp
@@ -239,7 +239,7 @@ const time_of_day tod_manager::get_illuminated_time_of_day(const unit_map & unit
for ( size_t i = 0; i < locs.size(); ++i ) {
const unit_map::const_iterator itor = units.find(locs[i]);
if (itor != units.end() &&
- itor->get_ability_bool("illuminates", *resources::gameboard) &&
+ itor->get_ability_bool("illuminates") &&
!itor->incapacitated())
{
unit_ability_list illum = itor->get_abilities("illuminates");
diff --git a/src/tstring.cpp b/src/tstring.cpp
index 0aaa0ce1614..b434a08d6bd 100644
--- a/src/tstring.cpp
+++ b/src/tstring.cpp
@@ -275,8 +275,8 @@ t_string_base::t_string_base(const std::string& string, const std::string& textd
id = idi->second;
}
- value_ += char(id & 0xff);
- value_ += char(id >> 8);
+ value_ += static_cast<char>(id & 0xff);
+ value_ += static_cast<char>(id >> 8);
value_ += string;
}
@@ -304,8 +304,8 @@ t_string_base::t_string_base(const std::string& sing, const std::string& pl, int
id = idi->second;
}
- value_ += char(id & 0xff);
- value_ += char(id >> 8);
+ value_ += static_cast<char>(id & 0xff);
+ value_ += static_cast<char>(id >> 8);
value_ += sing;
value_ += PLURAL_PART;
diff --git a/src/units/abilities.cpp b/src/units/abilities.cpp
index 47c9737d8c9..a00ab2e7458 100644
--- a/src/units/abilities.cpp
+++ b/src/units/abilities.cpp
@@ -124,20 +124,21 @@ A poisoned unit cannot be cured of its poison by a healer, and must seek the car
namespace {
-bool affects_side(const config& cfg, const std::vector<team>& teams, size_t side, size_t other_side)
+bool affects_side(const config& cfg, size_t side, size_t other_side)
{
- if (side == other_side)
+ // display::get_singleton() has already been confirmed valid by both callers.
+ const team& side_team = display::get_singleton()->get_disp_context().get_team(side);
+
+ if(side == other_side || !side_team.is_enemy(other_side)) {
return cfg["affect_allies"].to_bool(true);
- if (teams[side - 1].is_enemy(other_side))
+ } else {
return cfg["affect_enemies"].to_bool();
- else
- return cfg["affect_allies"].to_bool();
+ }
}
}
-
-bool unit::get_ability_bool(const std::string& tag_name, const map_location& loc, const display_context& dc) const
+bool unit::get_ability_bool(const std::string& tag_name, const map_location& loc) const
{
for (const config &i : this->abilities_.child_range(tag_name)) {
if (ability_active(tag_name, i, loc) &&
@@ -164,7 +165,7 @@ bool unit::get_ability_bool(const std::string& tag_name, const map_location& loc
if ( &*it == this )
continue;
for (const config &j : it->abilities_.child_range(tag_name)) {
- if (affects_side(j, dc.teams(), side(), it->side()) &&
+ if (affects_side(j, side(), it->side()) &&
it->ability_active(tag_name, j, adjacent[i]) &&
ability_affects_adjacent(tag_name, j, i, loc, *it))
{
@@ -176,15 +177,18 @@ bool unit::get_ability_bool(const std::string& tag_name, const map_location& loc
return false;
}
-unit_ability_list unit::get_abilities(const std::string& tag_name, const map_location& loc) const
+
+unit_ability_list unit::get_abilities(const std::string& tag_name, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon) const
{
unit_ability_list res(loc_);
- for (const config &i : this->abilities_.child_range(tag_name)) {
- if (ability_active(tag_name, i, loc) &&
- ability_affects_self(tag_name, i, loc))
- {
- res.push_back(unit_ability(&i, loc));
+ for(const config& i : this->abilities_.child_range(tag_name)) {
+ if(ability_active(tag_name, i, loc)
+ && ability_affects_self(tag_name, i, loc)
+ && ability_affects_weapon(i, weapon, false)
+ && ability_affects_weapon(i, opp_weapon, true)
+ ) {
+ res.emplace_back(&i, loc);
}
}
@@ -204,12 +208,13 @@ unit_ability_list unit::get_abilities(const std::string& tag_name, const map_loc
// ourself.
if ( &*it == this )
continue;
- for (const config &j : it->abilities_.child_range(tag_name)) {
- if (affects_side(j, resources::gameboard->teams(), side(), it->side()) &&
- it->ability_active(tag_name, j, adjacent[i]) &&
- ability_affects_adjacent(tag_name, j, i, loc, *it))
- {
- res.push_back(unit_ability(&j, adjacent[i]));
+ for(const config& j : it->abilities_.child_range(tag_name)) {
+ if(affects_side(j, side(), it->side())
+ && it->ability_active(tag_name, j, adjacent[i])
+ && ability_affects_adjacent(tag_name, j, i, loc, *it) && ability_affects_weapon(j, weapon, false)
+ && ability_affects_weapon(j, opp_weapon, true)
+ ) {
+ res.emplace_back(&j, adjacent[i]);
}
}
}
@@ -409,6 +414,19 @@ bool unit::ability_affects_self(const std::string& ability,const config& cfg,con
return unit_filter(vconfig(filter)).set_use_flat_tod(ability == "illuminates").matches(*this, loc);
}
+bool unit::ability_affects_weapon(const config& cfg, const_attack_ptr weapon, bool is_opp) const
+{
+ const std::string filter_tag_name = is_opp ? "filter_second_weapon" : "filter_weapon";
+ if(!cfg.has_child(filter_tag_name)) {
+ return true;
+ }
+ const config& filter = cfg.child(filter_tag_name);
+ if(!weapon) {
+ return false;
+ }
+ return weapon->matches_filter(filter);
+}
+
bool unit::has_ability_type(const std::string& ability) const
{
return !abilities_.child_range(ability).empty();
@@ -574,7 +592,7 @@ namespace {
* Returns whether or not @a *this has a special with a tag or id equal to
* @a special. If @a simple_check is set to true, then the check is merely
* for being present. Otherwise (the default), the check is for a special
- * active in the current context (see specials_context), including
+ * active in the current context (see set_specials_context), including
* specials obtained from the opponent's attack.
*/
bool attack_type::get_special_bool(const std::string& special, bool simple_check) const
@@ -610,20 +628,27 @@ bool attack_type::get_special_bool(const std::string& special, bool simple_check
/**
* Returns the currently active specials as an ability list, given the current
- * context (see specials_context).
+ * context (see set_specials_context).
*/
unit_ability_list attack_type::get_specials(const std::string& special) const
{
//log_scope("get_specials");
unit_ability_list res(self_loc_);
- for (const config &i : specials_.child_range(special)) {
- if ( special_active(i, AFFECT_SELF) )
- res.push_back(unit_ability(&i, self_loc_));
+
+ for(const config& i : specials_.child_range(special)) {
+ if(special_active(i, AFFECT_SELF)) {
+ res.emplace_back(&i, self_loc_);
+ }
}
- if (!other_attack_) return res;
- for (const config &i : other_attack_->specials_.child_range(special)) {
- if ( other_attack_->special_active(i, AFFECT_OTHER) )
- res.push_back(unit_ability(&i, other_loc_));
+
+ if(!other_attack_) {
+ return res;
+ }
+
+ for(const config& i : other_attack_->specials_.child_range(special)) {
+ if(other_attack_->special_active(i, AFFECT_OTHER)) {
+ res.emplace_back(&i, other_loc_);
+ }
}
return res;
}
@@ -633,7 +658,7 @@ unit_ability_list attack_type::get_specials(const std::string& special) const
* Each std::pair in the vector has first = name and second = description.
*
* This uses either the active or inactive name/description for each special,
- * based on the current context (see specials_context), provided
+ * based on the current context (see set_specials_context), provided
* @a active_list is not nullptr. Otherwise specials are assumed active.
* If the appropriate name is empty, the special is skipped.
*/
@@ -670,7 +695,7 @@ std::vector<std::pair<t_string, t_string>> attack_type::special_tooltips(
* Empty names are skipped.
*
* This excludes inactive specials if only_active is true. Whether or not a
- * special is active depends on the current context (see specials_context)
+ * special is active depends on the current context (see set_specials_context)
* and the @a is_backstab parameter.
*/
std::string attack_type::weapon_specials(bool only_active, bool is_backstab) const
@@ -760,10 +785,11 @@ attack_type::specials_context_t::specials_context_t(const attack_type& weapon, c
weapon.is_for_listing_ = false;
}
-attack_type::specials_context_t::specials_context_t(const attack_type& weapon)
+attack_type::specials_context_t::specials_context_t(const attack_type& weapon, bool attacking)
: parent(weapon.shared_from_this())
{
weapon.is_for_listing_ = true;
+ weapon.is_attacker_ = attacking;
}
attack_type::specials_context_t::~specials_context_t()
@@ -784,13 +810,6 @@ attack_type::specials_context_t::specials_context_t(attack_type::specials_contex
other.was_moved = true;
}
-attack_type::specials_context_t& attack_type::specials_context_t::operator=(attack_type::specials_context_t&& other)
-{
- *this = other; // Copy assign.
- other.was_moved = true;
- return *this;
-}
-
/**
* Calculates the number of attacks this weapon has, considering specials.
* This returns two numbers because of the swarm special. The actual number of
@@ -940,7 +959,7 @@ namespace { // Helpers for attack_type::special_active()
/**
* Returns whether or not the given special is active for the specified unit,
- * based on the current context (see specials_context).
+ * based on the current context (see set_specials_context).
* @param[in] special a weapon special WML structure
* @param[in] whom specifies which combatant we care about
* @param[in] include_backstab false if backstab specials should not be active
@@ -1233,7 +1252,7 @@ effect::effect(const unit_ability_list& list, int def, bool backstab) :
effect_list_.push_back(val.second);
}
- composite_value_ = int((value_set + addition) * multiplier / divisor);
+ composite_value_ = static_cast<int>((value_set + addition) * multiplier / divisor);
}
} // end namespace unit_abilities
diff --git a/src/units/animation.hpp b/src/units/animation.hpp
index cf01943a75a..088d7d52b42 100644
--- a/src/units/animation.hpp
+++ b/src/units/animation.hpp
@@ -15,6 +15,7 @@
#pragma once
#include "animated.hpp"
+#include "color.hpp"
#include "config.hpp"
#include "halo.hpp"
#include "units/frame.hpp"
diff --git a/src/units/attack_type.cpp b/src/units/attack_type.cpp
index 6650cd06007..14d09547986 100644
--- a/src/units/attack_type.cpp
+++ b/src/units/attack_type.cpp
@@ -103,8 +103,8 @@ static bool matches_simple_filter(const attack_type & attack, const config & fil
const std::string& filter_movement = filter["movement_used"];
const std::vector<std::string> filter_name = utils::split(filter["name"]);
const std::vector<std::string> filter_type = utils::split(filter["type"]);
- const std::string filter_special = filter["special"];
- const std::string filter_special_active = filter["special_active"];
+ const std::vector<std::string> filter_special = utils::split(filter["special"]);
+ const std::vector<std::string> filter_special_active = utils::split(filter["special_active"]);
const std::string filter_formula = filter["formula"];
if ( !filter_range.empty() && std::find(filter_range.begin(), filter_range.end(), attack.range()) == filter_range.end() )
@@ -131,11 +131,31 @@ static bool matches_simple_filter(const attack_type & attack, const config & fil
if ( !filter_type.empty() && std::find(filter_type.begin(), filter_type.end(), attack.type()) == filter_type.end() )
return false;
- if ( !filter_special.empty() && !attack.get_special_bool(filter_special, true) )
- return false;
+ if(!filter_special.empty()) {
+ bool found = false;
+ for(auto& special : filter_special) {
+ if(attack.get_special_bool(special, true)) {
+ found = true;
+ break;
+ }
+ }
+ if(!found) {
+ return false;
+ }
+ }
- if ( !filter_special_active.empty() && !attack.get_special_bool(filter_special_active, false) )
- return false;
+ if(!filter_special_active.empty()) {
+ bool found = false;
+ for(auto& special : filter_special_active) {
+ if(attack.get_special_bool(special, false)) {
+ found = true;
+ break;
+ }
+ }
+ if(!found) {
+ return false;
+ }
+ }
if (!filter_formula.empty()) {
try {
@@ -267,7 +287,7 @@ bool attack_type::apply_modification(const config& cfg)
if(increase_damage.empty() == false) {
damage_ = utils::apply_modifier(damage_, increase_damage);
- if (damage_ < 0) {
+ if(damage_ < 0) {
damage_ = 0;
}
}
diff --git a/src/units/attack_type.hpp b/src/units/attack_type.hpp
index 599b409e2e5..a4c41ac4208 100644
--- a/src/units/attack_type.hpp
+++ b/src/units/attack_type.hpp
@@ -114,7 +114,7 @@ public:
std::shared_ptr<const attack_type> parent;
friend class attack_type;
/// Initialize weapon specials context for listing
- explicit specials_context_t(const attack_type& weapon);
+ explicit specials_context_t(const attack_type& weapon, bool attacking);
/// Initialize weapon specials context for a unit type
specials_context_t(const attack_type& weapon, const unit_type& self_type, const map_location& loc, bool attacking = true);
/// Initialize weapon specials context for a single unit
@@ -125,14 +125,11 @@ public:
/// Initialize weapon specials context for a pair of units
specials_context_t(const attack_type& weapon, unit_const_ptr self, const map_location& loc, bool attacking);
specials_context_t(const specials_context_t&) = delete;
- // Default assignment is needed as a base for the move assignment
- specials_context_t& operator=(const specials_context_t&) = default;
bool was_moved = false;
public:
// Destructor at least needs to be public for all this to work.
~specials_context_t();
specials_context_t(specials_context_t&&);
- specials_context_t& operator=(specials_context_t&&);
};
// Set up a specials context.
// Usage: auto ctx = weapon.specials_context(...);
@@ -147,8 +144,8 @@ public:
specials_context_t specials_context(const unit_type& self_type, const map_location& loc, bool attacking = true) const {
return specials_context_t(*this, self_type, loc, attacking);
}
- specials_context_t specials_context_for_listing() const {
- return specials_context_t(*this);
+ specials_context_t specials_context_for_listing(bool attacking = true) const {
+ return specials_context_t(*this, attacking);
}
private:
diff --git a/src/units/drawer.cpp b/src/units/drawer.cpp
index 89446d79062..d670e94dbeb 100644
--- a/src/units/drawer.cpp
+++ b/src/units/drawer.cpp
@@ -79,8 +79,7 @@ void unit_drawer::redraw_unit (const unit & u) const
std::string ellipse=u.image_ellipse();
- if ( hidden || is_blindfolded || !u.is_visible_to_team(viewing_team_ref, dc, show_everything) )
- {
+ if(hidden || is_blindfolded || !u.is_visible_to_team(viewing_team_ref, show_everything)) {
ac.clear_haloes();
if(ac.anim_) {
ac.anim_->update_last_draw_time();
@@ -105,8 +104,7 @@ void unit_drawer::redraw_unit (const unit & u) const
// instead use -1.0 (as in "negative depth", it will be ignored by rendering)
params.submerge= is_flying ? -1.0 : terrain_info.unit_submerge();
- if (u.invisible(loc, dc) &&
- params.highlight_ratio > 0.6) {
+ if(u.invisible(loc) && params.highlight_ratio > 0.6) {
params.highlight_ratio = 0.6;
}
if (loc == sel_hex && params.highlight_ratio == 1.0) {
@@ -291,7 +289,7 @@ void unit_drawer::redraw_unit (const unit & u) const
double unit_energy = 0.0;
if(max_hitpoints > 0) {
- unit_energy = double(hitpoints)/double(max_hitpoints);
+ unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
}
const int bar_shift = static_cast<int>(-5*zoom_factor);
const int hp_bar_height = static_cast<int>(max_hitpoints * u.hp_bar_scaling());
@@ -302,8 +300,7 @@ void unit_drawer::redraw_unit (const unit & u) const
loc, hp_bar_height, unit_energy,hp_color, bar_alpha);
if(experience > 0 && can_advance) {
- const double filled = double(experience)/double(max_experience);
-
+ const double filled = static_cast<double>(experience) / static_cast<double>(max_experience);
const int xp_bar_height = static_cast<int>(max_experience * u.xp_bar_scaling() / std::max<int>(u.level(),1));
draw_bar(*energy_file, xsrc+xoff, ysrc+yoff+adjusted_params.y,
diff --git a/src/units/filter.cpp b/src/units/filter.cpp
index 44a9f4ad907..257e41d216a 100644
--- a/src/units/filter.cpp
+++ b/src/units/filter.cpp
@@ -308,14 +308,6 @@ void unit_filter_compound::fill(vconfig cfg)
}
);
- create_attribute(literal["speaker"],
- [](const config::attribute_value& c) { return c.str(); },
- [](const std::string& speaker, const unit_filter_args& args)
- {
- return speaker == args.u.id();
- }
- );
-
create_attribute(literal["type"],
[](const config::attribute_value& c) { return utils::split(c.str()); },
[](const std::vector<std::string>& types, const unit_filter_args& args)
@@ -496,6 +488,14 @@ void unit_filter_compound::fill(vconfig cfg)
}
);
+ create_attribute(literal["alignment"],
+ [](const config::attribute_value& c) { return c.str(); },
+ [](const std::string& alignment, const unit_filter_args& args)
+ {
+ return args.u.alignment().to_string() == alignment;
+ }
+ );
+
create_attribute(literal["ai_special"],
[](const config::attribute_value& c) { return c.str(); },
[](const std::string& ai_special, const unit_filter_args& args)
@@ -504,6 +504,19 @@ void unit_filter_compound::fill(vconfig cfg)
}
);
+ create_attribute(literal["usage"],
+ [](const config::attribute_value& c) { return utils::split(c.str()); },
+ [](const std::vector<std::string>& usages, const unit_filter_args& args)
+ {
+ for(const std::string& usage : usages) {
+ if(args.u.usage() == usage) {
+ return true;
+ }
+ }
+ return false;
+ }
+ );
+
create_attribute(literal["canrecruit"],
[](const config::attribute_value& c) { return c.to_bool(); },
[](bool canrecruit, const unit_filter_args& args)
@@ -692,7 +705,7 @@ void unit_filter_compound::fill(vconfig cfg)
for (const int viewer : viewers) {
bool fogged = args.fc->get_disp_context().get_team(viewer).fogged(args.loc);
- bool hiding = args.u.invisible(args.loc, args.fc->get_disp_context()) && args.fc->get_disp_context().get_team(viewer).is_enemy(args.u.side());
+ bool hiding = args.u.invisible(args.loc) && args.fc->get_disp_context().get_team(viewer).is_enemy(args.u.side());
bool unit_hidden = fogged || hiding;
if (c["visible"].to_bool(true) != unit_hidden) {
return true;
diff --git a/src/units/filter.hpp b/src/units/filter.hpp
index c415dc1bd8e..e24362b946f 100644
--- a/src/units/filter.hpp
+++ b/src/units/filter.hpp
@@ -101,27 +101,8 @@ public:
unit_filter(const unit_filter&) = default;
unit_filter& operator=(const unit_filter&) = default;
-#if defined(_MSC_VER) && _MSC_VER < 1900
- unit_filter(unit_filter&& u)
- : cfg_(std::move(u.cfg_))
- , fc_(u.fc_)
- , use_flat_tod_(u.use_flat_tod_)
- , impl_(std::move(u.impl_))
- , max_matches_(u.max_matches_)
- {}
- unit_filter& operator=(unit_filter&& u)
- {
- cfg_ = std::move(u.cfg_);
- fc_ = u.fc_;
- use_flat_tod_ = u.use_flat_tod_;
- impl_ = std::move(u.impl_);
- max_matches_ = u.max_matches_;
- return *this;
- }
-#else
unit_filter(unit_filter&&) = default;
unit_filter& operator=(unit_filter&&) = default;
-#endif
unit_filter& set_use_flat_tod(bool value) {
use_flat_tod_ = value;
diff --git a/src/units/frame.cpp b/src/units/frame.cpp
index 8169c5f7578..3215fa4fa79 100644
--- a/src/units/frame.cpp
+++ b/src/units/frame.cpp
@@ -682,10 +682,6 @@ std::set<map_location> unit_frame::get_overlaped_hex(const int frame_time, const
} else {
int w = 0, h = 0;
-#ifdef _OPENMP
-#pragma omp critical(frame_surface) // with the way surfaces work it's hard to lock the refcount within sdl_utils
-#endif //_OPENMP
-
{
surface image;
if(!image_loc.is_void() && !image_loc.get_filename().empty()) { // invalid diag image, or not diagonal
diff --git a/src/units/frame.hpp b/src/units/frame.hpp
index 14836a6e45a..076308868b4 100644
--- a/src/units/frame.hpp
+++ b/src/units/frame.hpp
@@ -21,6 +21,7 @@
#include "units/frame_private.hpp"
+#include "color.hpp"
#include "halo.hpp"
#include "picture.hpp"
diff --git a/src/units/race.cpp b/src/units/race.cpp
index 58e69bb11cf..653157ed402 100644
--- a/src/units/race.cpp
+++ b/src/units/race.cpp
@@ -47,6 +47,7 @@ static const config &empty_topics() {
unit_race::unit_race() :
cfg_(),
id_(),
+ name_(),
plural_name_(),
description_(),
ntraits_(0),
@@ -55,10 +56,9 @@ unit_race::unit_race() :
global_traits_(true),
undead_variation_()
{
- name_[MALE] = "";
- name_[FEMALE] = "";
- name_generator_[MALE].reset(new name_generator());
- name_generator_[FEMALE].reset(new name_generator());
+ for(auto& generator : name_generator_) {
+ generator.reset(new name_generator());
+ }
}
unit_race::unit_race(const config& cfg) :
diff --git a/src/units/race.hpp b/src/units/race.hpp
index bad9d212393..67cca6ec3fe 100644
--- a/src/units/race.hpp
+++ b/src/units/race.hpp
@@ -16,6 +16,8 @@
#include "config.hpp"
#include "utils/name_generator.hpp"
+
+#include <array>
#include <memory>
class unit_race
@@ -71,11 +73,11 @@ private:
std::string id_;
std::string icon_;
- t_string name_[NUM_GENDERS];
+ std::array<t_string, NUM_GENDERS> name_;
t_string plural_name_;
t_string description_;
unsigned int ntraits_;
- std::shared_ptr<name_generator> name_generator_[NUM_GENDERS];
+ std::array<std::shared_ptr<name_generator>, NUM_GENDERS> name_generator_;
config::const_child_itors traits_;
config::const_child_itors topics_;
diff --git a/src/units/types.cpp b/src/units/types.cpp
index 821e2fa3a24..728f233328d 100644
--- a/src/units/types.cpp
+++ b/src/units/types.cpp
@@ -855,7 +855,7 @@ int unit_type::resistance_against(const std::string& damage_name, bool attacker)
continue;
}
- resistance_abilities.push_back(unit_ability(&cfg, map_location::null_location()));
+ resistance_abilities.emplace_back(&cfg, map_location::null_location());
}
}
diff --git a/src/units/udisplay.cpp b/src/units/udisplay.cpp
index 6fbc16420f1..6686575bf87 100644
--- a/src/units/udisplay.cpp
+++ b/src/units/udisplay.cpp
@@ -35,12 +35,16 @@
#define LOG_DP LOG_STREAM(info, display)
+namespace unit_display
+{
+namespace
+{
/**
* Returns a string whose first line is @a number, centered over a second line,
* which consists of @a text.
* If the number is 0, the first line is suppressed.
*/
-static std::string number_and_text(int number, const std::string & text)
+std::string number_and_text(int number, const std::string& text)
{
// Simple case.
if ( number == 0 )
@@ -65,8 +69,7 @@ static std::string number_and_text(int number, const std::string & text)
* @param temp_unit The unit to animate (historically, a temporary unit).
* @param disp The game display. Assumed neither locked nor faked.
*/
-static void teleport_unit_between(const map_location& a, const map_location& b,
- unit& temp_unit, display& disp)
+void teleport_unit_between(const map_location& a, const map_location& b, unit& temp_unit, display& disp)
{
if ( disp.fogged(a) && disp.fogged(b) ) {
return;
@@ -115,10 +118,13 @@ static void teleport_unit_between(const map_location& a, const map_location& b,
* @returns The animation potential until this animation will finish.
* INT_MIN indicates that no animation is pending.
*/
-static int move_unit_between(const map_location& a, const map_location& b,
- unit_ptr temp_unit, unsigned int step_num,
- unsigned int step_left, unit_animator & animator,
- display& disp)
+int move_unit_between(const map_location& a,
+ const map_location& b,
+ unit_ptr temp_unit,
+ unsigned int step_num,
+ unsigned int step_left,
+ unit_animator& animator,
+ display& disp)
{
if ( disp.fogged(a) && disp.fogged(b) ) {
return INT_MIN;
@@ -147,9 +153,14 @@ static int move_unit_between(const map_location& a, const map_location& b,
return target_time;
}
-namespace unit_display
+bool do_not_show_anims(display* disp)
{
+ return !disp || disp->video().update_locked() || disp->video().faked();
+}
+
+} // end anon namespace
+
/**
* The path must remain unchanged for the life of this object.
*/
@@ -263,7 +274,7 @@ void unit_mover::start(unit_ptr u)
disp_->invalidate(path_[0]);
// If the unit can be seen here by the viewing side:
- if ( !is_enemy_ || !temp_unit_ptr_->invisible(path_[0], disp_->get_disp_context()) ) {
+ if(!is_enemy_ || !temp_unit_ptr_->invisible(path_[0])) {
// Scroll to the path, but only if it fully fits on screen.
// If it does not fit we might be able to do a better scroll later.
disp_->scroll_to_tiles(path_, game_display::ONSCREEN, true, true, 0.0, false);
@@ -318,9 +329,10 @@ void unit_mover::proceed_to(unit_ptr u, size_t path_index, bool update, bool wai
for ( ; current_ < path_index; ++current_ )
// If the unit can be seen by the viewing side while making this step:
- if ( !is_enemy_ || !temp_unit_ptr_->invisible(path_[current_], disp_->get_disp_context()) ||
- !temp_unit_ptr_->invisible(path_[current_+1], disp_->get_disp_context()) )
- {
+ if(!is_enemy_
+ || !temp_unit_ptr_->invisible(path_[current_])
+ || !temp_unit_ptr_->invisible(path_[current_ + 1])
+ ) {
// Wait for the previous step to complete before drawing the next one.
wait_for_anims();
@@ -441,8 +453,7 @@ void unit_mover::finish(unit_ptr u, map_location::DIRECTION dir)
u->set_hidden(was_hidden_);
temp_unit_ptr_->set_hidden(true);
- events::mouse_handler* mousehandler = events::mouse_handler::get_singleton();
- if ( mousehandler ) {
+ if(events::mouse_handler* mousehandler = events::mouse_handler::get_singleton()) {
mousehandler->invalidate_reachmap();
}
}
@@ -496,7 +507,7 @@ void unit_draw_weapon(const map_location& loc, unit& attacker,
const_attack_ptr attack,const_attack_ptr secondary_attack, const map_location& defender_loc,unit* defender)
{
display* disp = display::get_singleton();
- if(!disp ||disp->video().update_locked() || disp->video().faked() || disp->fogged(loc) || preferences::show_combat() == false) {
+ if(do_not_show_anims(disp) || disp->fogged(loc) || !preferences::show_combat()) {
return;
}
unit_animator animator;
@@ -514,7 +525,7 @@ void unit_sheath_weapon(const map_location& primary_loc, unit* primary_unit,
const_attack_ptr primary_attack,const_attack_ptr secondary_attack, const map_location& secondary_loc,unit* secondary_unit)
{
display* disp = display::get_singleton();
- if(!disp ||disp->video().update_locked() || disp->video().faked() || disp->fogged(primary_loc) || preferences::show_combat() == false) {
+ if(do_not_show_anims(disp) || disp->fogged(primary_loc) || !preferences::show_combat()) {
return;
}
unit_animator animator;
@@ -544,7 +555,7 @@ void unit_die(const map_location& loc, unit& loser,
const_attack_ptr attack,const_attack_ptr secondary_attack, const map_location& winner_loc,unit* winner)
{
display* disp = display::get_singleton();
- if(!disp ||disp->video().update_locked() || disp->video().faked() || disp->fogged(loc) || preferences::show_combat() == false) {
+ if(do_not_show_anims(disp) || disp->fogged(loc) || !preferences::show_combat()) {
return;
}
unit_animator animator;
@@ -556,9 +567,9 @@ void unit_die(const map_location& loc, unit& loser,
animator.start_animations();
animator.wait_for_end();
- reset_helpers(winner,&loser);
- events::mouse_handler* mousehandler = events::mouse_handler::get_singleton();
- if (mousehandler) {
+ reset_helpers(winner, &loser);
+
+ if(events::mouse_handler* mousehandler = events::mouse_handler::get_singleton()) {
mousehandler->invalidate_reachmap();
}
}
@@ -569,8 +580,7 @@ void unit_attack(display * disp, game_board & board,
const attack_type& attack, const_attack_ptr secondary_attack,
int swing,const std::string& hit_text,int drain_amount,const std::string& att_text, const std::vector<std::string>* extra_hit_sounds)
{
- if(!disp ||disp->video().update_locked() || disp->video().faked() ||
- (disp->fogged(a) && disp->fogged(b)) || preferences::show_combat() == false) {
+ if(do_not_show_anims(disp) || (disp->fogged(a) && disp->fogged(b)) || !preferences::show_combat()) {
return;
}
//const unit_map& units = disp->get_units();
@@ -594,12 +604,7 @@ void unit_attack(display * disp, game_board & board,
def->set_facing(b.get_relative_dir(a));
defender.set_facing(b.get_relative_dir(a));
-
- unit_animator animator;
- unit_ability_list leaders = attacker.get_abilities("leadership");
- unit_ability_list helpers = defender.get_abilities("resistance");
-
- std::string text = number_and_text(damage, hit_text);
+ std::string text = number_and_text(damage, hit_text);
std::string text_2 = number_and_text(std::abs(drain_amount), att_text);
unit_animation::hit_type hit_type;
@@ -610,21 +615,28 @@ void unit_attack(display * disp, game_board & board,
}else {
hit_type = unit_animation::hit_type::MISS;
}
- animator.add_animation(&attacker, "attack", att->get_location(),
- def->get_location(), damage, true, text_2,
- (drain_amount >= 0) ? color_t(0,255,0) : color_t(255,0,0),
- hit_type, attack.shared_from_this(), secondary_attack, swing);
+
+ unit_animator animator;
+
+ animator.add_animation(&attacker, "attack", att->get_location(), def->get_location(), damage, true, text_2,
+ (drain_amount >= 0) ? color_t(0, 255, 0) : color_t(255, 0, 0), hit_type, attack.shared_from_this(),
+ secondary_attack, swing);
// note that we take an anim from the real unit, we'll use it later
- const unit_animation *defender_anim = def->anim_comp().choose_animation(*disp,
- def->get_location(), "defend", att->get_location(), damage,
- hit_type, attack.shared_from_this(), secondary_attack, swing);
- animator.add_animation(&defender, defender_anim, def->get_location(),
- true, text , {255,0,0});
-
- for (const unit_ability & ability : leaders) {
- if(ability.second == a) continue;
- if(ability.second == b) continue;
+ const unit_animation* defender_anim = def->anim_comp().choose_animation(*disp, def->get_location(), "defend",
+ att->get_location(), damage, hit_type, attack.shared_from_this(), secondary_attack, swing);
+
+ animator.add_animation(&defender, defender_anim, def->get_location(), true, text, {255, 0, 0});
+
+ for(const unit_ability& ability : attacker.get_abilities("leadership")) {
+ if(ability.second == a) {
+ continue;
+ }
+
+ if(ability.second == b) {
+ continue;
+ }
+
unit_map::const_iterator leader = board.units().find(ability.second);
assert(leader.valid());
leader->set_facing(ability.second.get_relative_dir(a));
@@ -632,9 +644,16 @@ void unit_attack(display * disp, game_board & board,
att->get_location(), damage, true, "", {0,0,0},
hit_type, attack.shared_from_this(), secondary_attack, swing);
}
- for (const unit_ability & ability : helpers) {
- if(ability.second == a) continue;
- if(ability.second == b) continue;
+
+ for(const unit_ability& ability : defender.get_abilities("resistance")) {
+ if(ability.second == a) {
+ continue;
+ }
+
+ if(ability.second == b) {
+ continue;
+ }
+
unit_map::const_iterator helper = board.units().find(ability.second);
assert(helper.valid());
helper->set_facing(ability.second.get_relative_dir(b));
@@ -677,8 +696,7 @@ void reset_helpers(const unit *attacker,const unit *defender)
display* disp = display::get_singleton();
const unit_map& units = disp->get_units();
if(attacker) {
- unit_ability_list leaders = attacker->get_abilities("leadership");
- for (const unit_ability & ability : leaders) {
+ for(const unit_ability& ability : attacker->get_abilities("leadership")) {
unit_map::const_iterator leader = units.find(ability.second);
assert(leader != units.end());
leader->anim_comp().set_standing();
@@ -686,8 +704,7 @@ void reset_helpers(const unit *attacker,const unit *defender)
}
if(defender) {
- unit_ability_list helpers = defender->get_abilities("resistance");
- for (const unit_ability & ability : helpers) {
+ for(const unit_ability& ability : defender->get_abilities("resistance")) {
unit_map::const_iterator helper = units.find(ability.second);
assert(helper != units.end());
helper->anim_comp().set_standing();
@@ -698,21 +715,24 @@ void reset_helpers(const unit *attacker,const unit *defender)
void unit_recruited(const map_location& loc,const map_location& leader_loc)
{
game_display* disp = game_display::get_singleton();
+ if(do_not_show_anims(disp) || disp->fogged(loc)) {
+ return;
+ }
+
const display_context& dc = disp->get_disp_context();
const team& viewing_team = dc.get_team(disp->viewing_side());
- if(!disp || disp->video().update_locked() || disp->video().faked() ||
- (disp->fogged(loc) && disp->fogged(leader_loc))) return;
unit_map::const_iterator u = disp->get_units().find(loc);
if(u == disp->get_units().end()) return;
- const bool unit_visible = u->is_visible_to_team(viewing_team, dc, false);
+ const bool unit_visible = u->is_visible_to_team(viewing_team, false);
unit_map::const_iterator leader = disp->get_units().find(leader_loc); // may be null_location
- const bool leader_visible = (leader != disp->get_units().end()) && leader->is_visible_to_team(viewing_team, dc, false);
+ const bool leader_visible = (leader != disp->get_units().end()) && leader->is_visible_to_team(viewing_team, false);
u->set_hidden(true);
unit_animator animator;
+
if (leader_visible && unit_visible) {
disp->scroll_to_tiles(loc,leader_loc,game_display::ONSCREEN,true,0.0,false);
} else if (leader_visible) {
@@ -742,8 +762,11 @@ void unit_healing(unit &healed, const std::vector<unit *> &healers, int healing,
const std::string & extra_text)
{
game_display* disp = game_display::get_singleton();
- const map_location &healed_loc = healed.get_location();
- if(!disp || disp->video().update_locked() || disp->video().faked() || disp->fogged(healed_loc)) return;
+ const map_location& healed_loc = healed.get_location();
+
+ if(do_not_show_anims(disp) || disp->fogged(healed_loc)) {
+ return;
+ }
// This is all the pretty stuff.
disp->scroll_to_tile(healed_loc, game_display::ONSCREEN,true,false);
diff --git a/src/units/unit.cpp b/src/units/unit.cpp
index ab05ef2acc7..1494f268aa9 100644
--- a/src/units/unit.cpp
+++ b/src/units/unit.cpp
@@ -21,7 +21,7 @@
#include "color.hpp"
#include "deprecation.hpp"
-#include "display_context.hpp"
+#include "display.hpp"
#include "formatter.hpp"
#include "formula/string_utils.hpp" // for VGETTEXT
#include "game_board.hpp" // for game_board
@@ -577,6 +577,7 @@ void unit::init(const config& cfg, bool use_traits, const vconfig* vcfg)
max_experience_ = std::max(1, cfg["max_experience"].to_int(max_experience_));
vision_ = cfg["vision"].to_int(vision_);
+ jamming_ = cfg["jamming"].to_int(jamming_);
std::vector<std::string> temp_advances = utils::split(cfg["advances_to"]);
if(temp_advances.size() == 1 && temp_advances.front() == "null") {
@@ -1037,7 +1038,7 @@ static color_t hp_color_impl(int hitpoints, int max_hitpoints)
color_t energy_color {0,0,0,255};
if(max_hitpoints > 0) {
- unit_energy = double(hitpoints)/double(max_hitpoints);
+ unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
}
if(1.0 == unit_energy) {
@@ -1579,11 +1580,11 @@ bool unit::resistance_filter_matches(const config& cfg, bool attacker, const std
return true;
}
-int unit::resistance_against(const std::string& damage_name,bool attacker,const map_location& loc) const
+int unit::resistance_against(const std::string& damage_name,bool attacker,const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon) const
{
int res = movement_type_.resistance_against(damage_name);
- unit_ability_list resistance_abilities = get_abilities("resistance",loc);
+ unit_ability_list resistance_abilities = get_abilities("resistance",loc, weapon, opp_weapon);
for(unit_ability_list::iterator i = resistance_abilities.begin(); i != resistance_abilities.end();) {
if(!resistance_filter_matches(*i->first, attacker, damage_name, 100-res)) {
i = resistance_abilities.erase(i);
@@ -2312,7 +2313,7 @@ void unit::apply_modifications()
max_experience_ = std::max<int>(1, (max_experience_ * exp_accel + 50)/100);
}
-bool unit::invisible(const map_location& loc, const display_context& dc, bool see_all) const
+bool unit::invisible(const map_location& loc, bool see_all) const
{
if(loc != get_location()) {
DBG_UT << "unit::invisible called: id = " << id() << " loc = " << loc << " get_loc = " << get_location() << std::endl;
@@ -2338,7 +2339,7 @@ bool unit::invisible(const map_location& loc, const display_context& dc, bool se
// Test hidden status
static const std::string hides("hides");
- bool is_inv = get_ability_bool(hides, loc, dc);
+ bool is_inv = get_ability_bool(hides, loc);
if(is_inv){
is_inv = (resources::gameboard ? !resources::gameboard->would_be_discovered(loc, side_,see_all) : true);
}
@@ -2355,10 +2356,10 @@ bool unit::invisible(const map_location& loc, const display_context& dc, bool se
return is_inv;
}
-bool unit::is_visible_to_team(const team& team,const display_context& dc, bool const see_all) const
+bool unit::is_visible_to_team(const team& team, bool const see_all) const
{
const map_location& loc = get_location();
- if(!dc.map().on_board(loc)) {
+ if(!display::get_singleton()->get_map().on_board(loc)) {
return false;
}
@@ -2366,7 +2367,7 @@ bool unit::is_visible_to_team(const team& team,const display_context& dc, bool
return true;
}
- if(team.is_enemy(side()) && invisible(loc, dc)) {
+ if(team.is_enemy(side()) && invisible(loc)) {
return false;
}
diff --git a/src/units/unit.hpp b/src/units/unit.hpp
index 7a56f14055d..9d072cb9e64 100644
--- a/src/units/unit.hpp
+++ b/src/units/unit.hpp
@@ -18,15 +18,12 @@
#include "units/ptr.hpp"
#include "units/types.hpp"
-#include "utils/type_trait_aliases.hpp"
-
#include <bitset>
#include <boost/dynamic_bitset_fwd.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/variant.hpp>
class display;
-class display_context;
class team;
class unit_animation_component;
class unit_formula_manager;
@@ -85,7 +82,9 @@ public:
const unit_ability& back() const { return cfgs_.back(); }
iterator erase(const iterator& erase_it) { return cfgs_.erase(erase_it); }
- void push_back(const unit_ability& ability) { cfgs_.push_back(ability); }
+
+ template<typename... T>
+ void emplace_back(T&&... args) { cfgs_.emplace_back(args...); }
const map_location& loc() const { return loc_; }
private:
@@ -847,9 +846,9 @@ public:
*
* @returns The expected damage.
*/
- int damage_from(const attack_type& attack, bool attacker, const map_location& loc) const
+ int damage_from(const attack_type& attack, bool attacker, const map_location& loc, const_attack_ptr weapon = nullptr) const
{
- return resistance_against(attack, attacker, loc);
+ return resistance_against(attack, attacker, loc, weapon);
}
/** The maximum number of attacks this unit may perform per turn, usually 1. */
@@ -901,7 +900,7 @@ public:
* @param attacker True if this unit is on the offensive (to resolve [resistance] abilities)
* @param loc The unit's location (to resolve [resistance] abilities)
*/
- int resistance_against(const std::string& damage_name, bool attacker, const map_location& loc) const;
+ int resistance_against(const std::string& damage_name, bool attacker, const map_location& loc, const_attack_ptr weapon = nullptr, const_attack_ptr opp_weapon = nullptr) const;
/**
* The unit's resistance against a given attack
@@ -909,9 +908,9 @@ public:
* @param attacker True if this unit is on the offensive (to resolve [resistance] abilities)
* @param loc The unit's location (to resolve [resistance] abilities)
*/
- int resistance_against(const attack_type& atk, bool attacker, const map_location& loc) const
+ int resistance_against(const attack_type& atk, bool attacker, const map_location& loc, const_attack_ptr weapon = nullptr) const
{
- return resistance_against(atk.type(), attacker, loc);
+ return resistance_against(atk.type(), attacker, loc , weapon, atk.shared_from_this());
}
/** Gets resistances without any abilities applied. */
@@ -1034,7 +1033,7 @@ public:
struct upkeep_type_visitor : public boost::static_visitor<std::string>
{
template<typename T>
- utils::enable_if_t<!std::is_same<int, T>::value, std::string>
+ std::enable_if_t<!std::is_same<int, T>::value, std::string>
operator()(T&) const
{
// Any special upkeep type should have an associated @ref type getter in its helper struct.
@@ -1456,9 +1455,8 @@ public:
* @param tag_name The name of the ability to check for.
* @param loc The location around which to check for affected units. This may or
* may not be the location of this unit.
- * @param dc A display_context object, used in calculations.
*/
- bool get_ability_bool(const std::string& tag_name, const map_location& loc, const display_context& dc) const;
+ bool get_ability_bool(const std::string& tag_name, const map_location& loc) const;
/**
* Checks whether this unit currently possesses or is affected by a given ability.
@@ -1469,11 +1467,10 @@ public:
* This overload uses the location of this unit for calculations.
*
* @param tag_name The name of the ability to check for.
- * @param dc A display_context object, used in calculations.
*/
- bool get_ability_bool(const std::string& tag_name, const display_context& dc) const
+ bool get_ability_bool(const std::string& tag_name) const
{
- return get_ability_bool(tag_name, loc_, dc);
+ return get_ability_bool(tag_name, loc_);
}
/**
@@ -1482,16 +1479,16 @@ public:
* @param loc The location to use for resolving abilities
* @return A list of active abilities, paired with the location they are active on
*/
- unit_ability_list get_abilities(const std::string& tag_name, const map_location& loc) const;
+ unit_ability_list get_abilities(const std::string& tag_name, const map_location& loc, const_attack_ptr weapon = nullptr, const_attack_ptr opp_weapon = nullptr) const;
/**
* Gets the unit's active abilities of a particular type.
* @param tag_name The type of ability to check for
* @return A list of active abilities, paired with the location they are active on
*/
- unit_ability_list get_abilities(const std::string& tag_name) const
+ unit_ability_list get_abilities(const std::string& tag_name, const_attack_ptr weapon = nullptr, const_attack_ptr opp_weapon = nullptr) const
{
- return get_abilities(tag_name, loc_);
+ return get_abilities(tag_name, loc_, weapon, opp_weapon);
}
/**
@@ -1557,6 +1554,8 @@ private:
*/
bool ability_affects_self(const std::string& ability, const config& cfg, const map_location& loc) const;
+ bool ability_affects_weapon(const config& cfg, const_attack_ptr weapon, bool is_opp) const;
+
public:
/** Get the unit formula manager. */
unit_formula_manager& formula_manager() const
@@ -1568,9 +1567,9 @@ public:
void generate_name();
// Only see_all = true use caching
- bool invisible(const map_location& loc, const display_context& dc, bool see_all = true) const;
+ bool invisible(const map_location& loc, bool see_all = true) const;
- bool is_visible_to_team(const team& team, const display_context& dc, bool const see_all = true) const;
+ bool is_visible_to_team(const team& team, bool const see_all = true) const;
/**
* Serializes the current unit metadata values.
diff --git a/src/utils/const_clone.hpp b/src/utils/const_clone.hpp
index 72f3af740a6..475032cd7d1 100644
--- a/src/utils/const_clone.hpp
+++ b/src/utils/const_clone.hpp
@@ -14,8 +14,6 @@
#pragma once
-#include "utils/type_trait_aliases.hpp"
-
#include <type_traits>
namespace utils
@@ -39,22 +37,22 @@ struct const_clone
{
static const bool is_source_const =
std::is_const<
- utils::remove_pointer_t<
- utils::remove_reference_t<S>
+ std::remove_pointer_t<
+ std::remove_reference_t<S>
>
>::value;
/** The destination type, possibly const qualified. */
using type =
- utils::conditional_t<is_source_const, const D, D>;
+ std::conditional_t<is_source_const, const D, D>;
/** A reference to the destination type, possibly const qualified. */
using reference =
- utils::conditional_t<is_source_const, const D&, D&>;
+ std::conditional_t<is_source_const, const D&, D&>;
/** A pointer to the destination type, possibly const qualified. */
using pointer =
- utils::conditional_t<is_source_const, const D*, D*>;
+ std::conditional_t<is_source_const, const D*, D*>;
};
template<typename D, typename S>
diff --git a/src/utils/functional.hpp b/src/utils/functional.hpp
index 327e9f1c383..bedb75d5b87 100644
--- a/src/utils/functional.hpp
+++ b/src/utils/functional.hpp
@@ -17,7 +17,6 @@
#pragma once
-#include "global.hpp"
#include <functional>
#include <boost/bind.hpp>
@@ -30,87 +29,3 @@ namespace std { // Some compilers can't handle it being specialized in the globa
template<int N>
struct is_placeholder<boost::arg<N>> : public integral_constant<int, N> {};
}
-
-namespace detail {
- template<typename Ret, typename... T>
- struct apply {
- using result_type = void;
- apply(const std::function<Ret(T...)>& fcn) : fcn(fcn) {}
- apply(Ret(*fcn)(T...)) : fcn(fcn) {}
- void operator()(T... params) {
- fcn(std::forward<T>(params)...);
- }
- private:
- std::function<Ret(T...)> fcn;
- };
-
- template<typename Ret, typename... T>
- apply<Ret, T...> make_apply(std::function<Ret(T...)> fcn) {
- return apply<Ret, T...>(fcn);
- }
-
- template<typename F>
- struct function_base {
- using type = typename function_base<decltype(&F::operator())>::type;
- };
-
- template<typename Ret, typename... P>
- struct function_base<Ret(P...)> {
- typedef Ret type(P...);
- };
-
- template<typename Ret, typename... P>
- struct function_base<Ret(*)(P...)> {
- typedef Ret type(P...);
- };
-
- template<typename Ret, typename Class, typename... P>
- struct function_base<Ret(Class::*)(P...)> {
- typedef Ret type(Class,P...);
- };
-
- template<typename Ret, typename Class, typename... P>
- struct function_base<Ret(Class::*)(P...)const> {
- typedef Ret type(const Class,P...);
- };
-
- template<typename Ret, typename Class, typename... P>
- struct function_base<Ret(Class::*)(P...)volatile > {
- typedef Ret type(volatile Class,P...);
- };
-
- template<typename Ret, typename Class, typename... P>
- struct function_base<Ret(Class::*)(P...)const volatile> {
- typedef Ret type(const volatile Class,P...);
- };
-
- template<typename Ret, typename... P>
- struct function_base<std::function<Ret(P...)>> {
- typedef Ret type(P...);
- };
-}
-
-template<typename F, typename... P>
-auto bind_void(F fcn, P... bindings)
-#ifndef HAVE_CXX14
--> decltype(
- std::bind(detail::make_apply(std::function<typename detail::function_base<F>::type>(fcn)), bindings...)
-)
-#endif
-{
- using T = typename detail::function_base<F>::type;
- return std::bind(detail::make_apply(std::function<T>(fcn)), bindings...);
-}
-
-/* A note on why std::bind is not flexible enough:
-
-1. The functions produced do not silently consume extra parameters passed to them.
-This is not a bad thing per se, but some of Wesnoth's code relied on it.
-It's useful behaviour, as well.
-
-2. A function that returns a value cannot be bound in a function type that returns void.
-This is also relied upon in several places.
-
-If behaviour #1 is needed, we can use boost::bind, though a lambda with unused arguments may be better.
-For behaviour #2, the bind_void function is provided.
-*/
diff --git a/src/utils/io.hpp b/src/utils/io.hpp
deleted file mode 100644
index caa874dd8d2..00000000000
--- a/src/utils/io.hpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-Copyright (C) 2003 - 2018 the Battle for Wesnoth Project https://www.wesnoth.org/
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY.
-
-See the COPYING file for more details.
-*/
-
-#include "global.hpp"
-
-// The version of libstdc++ shipped with GCC 4.x does not have put_time in the <iomanip> header
-// Thus if GCC is the compiler being used, we can simply check the compiler version.
-// However, if clang is being used, this won't work.
-// Instead, we check for the presence of the <experimental/any> header.
-// This was introduced in GCC 5.1, so it's not a perfect check, but it appears to be the best available.
-// (Boost also uses the same check internally.)
-#if !HAVE_PUT_TIME
-
-#include <ctime>
-
-namespace utils {
- inline std::string put_time(struct tm* time, const char* fmt) {
- char buf[256];
- if(strftime(buf, 256, fmt, time)) {
- return buf;
- }
- return "<badtime>";
- }
-}
-
-#else
-
-#include <iomanip>
-
-namespace utils {
- using std::put_time;
-}
-
-#endif
diff --git a/src/utils/markov_generator.cpp b/src/utils/markov_generator.cpp
index 9ce41d9f356..20eaf5c334c 100644
--- a/src/utils/markov_generator.cpp
+++ b/src/utils/markov_generator.cpp
@@ -22,12 +22,12 @@
#include "serialization/unicode_cast.hpp"
#include "random.hpp"
-static void add_prefixes(const ucs4::string& str, size_t length, markov_prefix_map& res)
+static void add_prefixes(const std::u32string& str, size_t length, markov_prefix_map& res)
{
for(size_t i = 0; i <= str.size(); ++i) {
const size_t start = i > length ? i - length : 0;
- const ucs4::string key(str.begin() + start, str.begin() + i);
- const ucs4::char_t c = i != str.size() ? str[i] : 0;
+ const std::u32string key(str.begin() + start, str.begin() + i);
+ const char32_t c = i != str.size() ? str[i] : 0;
res[key].push_back(c);
}
}
@@ -37,20 +37,20 @@ static markov_prefix_map markov_prefixes(const std::vector<std::string>& items,
markov_prefix_map res;
for(std::vector<std::string>::const_iterator i = items.begin(); i != items.end(); ++i) {
- add_prefixes(unicode_cast<ucs4::string>(*i),length,res);
+ add_prefixes(unicode_cast<std::u32string>(*i),length,res);
}
return res;
}
-static ucs4::string markov_generate_name(const markov_prefix_map& prefixes,
+static std::u32string markov_generate_name(const markov_prefix_map& prefixes,
size_t chain_size, size_t max_len)
{
if(prefixes.empty() || chain_size == 0) {
- return ucs4::string();
+ return std::u32string();
}
- ucs4::string prefix, res;
+ std::u32string prefix, res;
// Since this function is called in the name description in a MP game it
// uses the local locale. The locale between players can be different and
@@ -75,7 +75,7 @@ static ucs4::string markov_generate_name(const markov_prefix_map& prefixes,
return res;
}
- const ucs4::char_t c = i->second[random[j++]%i->second.size()];
+ const char32_t c = i->second[random[j++]%i->second.size()];
if(c == 0) {
return res;
}
@@ -98,16 +98,16 @@ static ucs4::string markov_generate_name(const markov_prefix_map& prefixes,
// name has end-of-string as a possible next character in the
// markov prefix map. If no valid ending is found, use the
// originally generated name.
- ucs4::string originalRes = res;
+ std::u32string originalRes = res;
while(!res.empty()) {
const int prefixLen = chain_size < res.size() ? chain_size : res.size();
- prefix = ucs4::string(res.end() - prefixLen, res.end());
+ prefix = std::u32string(res.end() - prefixLen, res.end());
const markov_prefix_map::const_iterator i = prefixes.find(prefix);
if (i == prefixes.end() || i->second.empty()) {
return res;
}
- if (std::find(i->second.begin(), i->second.end(), static_cast<ucs4::char_t>(0))
+ if (std::find(i->second.begin(), i->second.end(), static_cast<char32_t>(0))
!= i->second.end()) {
// This ending is valid.
return res;
@@ -132,6 +132,6 @@ markov_generator::markov_generator(const std::vector<std::string>& items, size_t
std::string markov_generator::generate() const
{
- ucs4::string name = markov_generate_name(prefixes_, chain_size_, max_len_);
- return unicode_cast<utf8::string>(name);
+ std::u32string name = markov_generate_name(prefixes_, chain_size_, max_len_);
+ return unicode_cast<std::string>(name);
}
diff --git a/src/utils/markov_generator.hpp b/src/utils/markov_generator.hpp
index 4bbd5eb7cd4..3f2b7ee0e24 100644
--- a/src/utils/markov_generator.hpp
+++ b/src/utils/markov_generator.hpp
@@ -14,11 +14,11 @@
#pragma once
-#include "serialization/unicode_types.hpp"
#include "utils/name_generator.hpp"
#include <map>
+#include <vector>
-typedef std::map<ucs4::string, ucs4::string> markov_prefix_map;
+typedef std::map<std::u32string, std::u32string> markov_prefix_map;
class markov_generator : public name_generator {
markov_prefix_map prefixes_;
diff --git a/src/utils/math.hpp b/src/utils/math.hpp
index 826b9b2938d..e13b342327b 100644
--- a/src/utils/math.hpp
+++ b/src/utils/math.hpp
@@ -24,7 +24,6 @@
#include <cstdint>
#include <cstdlib>
#include <limits>
-#include <math.h> // cmath may not provide round()
#include <vector>
#include <algorithm>
@@ -63,20 +62,6 @@ inline int round_damage(int base_damage, int bonus, int divisor) {
return std::max<int>(1, (base_damage * bonus + rounding) / divisor);
}
-// not guaranteed to have exactly the same result on different platforms
-inline int round_double(double d) {
-#ifdef HAVE_ROUND
- return static_cast<int>(round(d)); //surprisingly, not implemented everywhere
-#else
- return static_cast<int>((d >= 0.0)? std::floor(d + 0.5) : std::ceil(d - 0.5));
-#endif
-}
-
-// Guaranteed to have portable results across different platforms
-inline double round_portable(double d) {
- return (d >= 0.0) ? std::floor(d + 0.5) : std::ceil(d - 0.5);
-}
-
template<typename Cmp>
bool in_ranges(const Cmp c, const std::vector<std::pair<Cmp, Cmp>>& ranges)
{
diff --git a/src/utils/type_trait_aliases.hpp b/src/utils/type_trait_aliases.hpp
index 5c9ace8ac23..00c93023a85 100644
--- a/src/utils/type_trait_aliases.hpp
+++ b/src/utils/type_trait_aliases.hpp
@@ -19,60 +19,6 @@
namespace utils
{
-//
-// These aliases are part of the standard starting with C++14.
-// MSVC included them itself starting from VS2013 (our min supported version).
-// However, they can't be used via alias templates in VS2013 due to lack of
-// support for expression SFINAE.
-// Forward to their declarations as appropriate.
-//
-#if defined(HAVE_CXX14) || _MSC_VER >= 1900
-
-template<typename T>
-using add_const_t = std::add_const_t<T>;
-template<bool B, typename T, typename F>
-using conditional_t = std::conditional_t<B, T, F>;
-template<bool B, typename T = void>
-using enable_if_t = std::enable_if_t<B, T>;
-template<typename T>
-using remove_const_t = std::remove_const_t<T>;
-template<typename T>
-using remove_reference_t = std::remove_reference_t<T>;
-template<typename T>
-using remove_pointer_t = std::remove_pointer_t<T>;
-
-#else // We do not have C++14 or MSVC >= 2015
-
-// add_const
-template<typename T>
-using add_const_t = typename std::add_const<T>::type;
-
-// conditional
-template<bool B, typename T, typename F>
-using conditional_t = typename std::conditional<B, T, F>::type;
-
-// enable_if
-template<bool B, typename T = void>
-using enable_if_t = typename std::enable_if<B, T>::type;
-
-// remove_const
-template<typename T>
-using remove_const_t = typename std::remove_const<T>::type;
-
-// remove_reference
-template<typename T>
-using remove_reference_t = typename std::remove_reference<T>::type;
-
-// remove_pointer
-template<typename T>
-using remove_pointer_t = typename std::remove_pointer<T>::type;
-
-#endif // defined(HAVE_CXX14) || _MSC_VER >= 1900
-
-// Since there's really no way to implement these without variable templates, I've commented
-// this whole section out until we bump our min compiler support to VS 2015 and GCC 5.
-#if 0
-
//
// These aliases are part of the standard starting with C++17.
// However, MSVC includes them as of VS 2015 Update 2, and they can also be implemented
@@ -83,18 +29,16 @@ using remove_pointer_t = typename std::remove_pointer<T>::type;
using std::is_base_of_v;
using std::is_same_v;
-#elif defined(HAVE_CXX14)
+#else
// is_base_of
template<typename Base, typename Derived>
-static constexpr bool is_base_of_v = std::is_base_of<Base, Derived>::value;
+static CONSTEXPR bool is_base_of_v = std::is_base_of<Base, Derived>::value;
// is_same
template<typename T, typename U>
-static constexpr bool is_same_v = std::is_same<T, U>::value;
+static CONSTEXPR bool is_same_v = std::is_same<T, U>::value;
#endif // HAVE_CXX17
-#endif
-
} // end namespace utils
diff --git a/src/variable.cpp b/src/variable.cpp
index 115c7ef4516..6370ae169d8 100644
--- a/src/variable.cpp
+++ b/src/variable.cpp
@@ -356,7 +356,7 @@ vconfig::all_children_iterator& vconfig::all_children_iterator::operator++()
config::const_child_itors range = vinfo.as_array();
- if (++inner_index_ < int(range.size()))
+ if (++inner_index_ < static_cast<int>(range.size()))
{
return *this;
}
diff --git a/src/variable_info.cpp b/src/variable_info.cpp
index 62c262164c2..faf0b00c165 100644
--- a/src/variable_info.cpp
+++ b/src/variable_info.cpp
@@ -39,7 +39,7 @@ typename V::result_t apply_visitor(typename V::param_t state, T&&... args)
static_assert(std::is_base_of<
info_visitor_base<
typename V::result_t,
- utils::remove_reference_t<typename V::param_t>>,
+ std::remove_reference_t<typename V::param_t>>,
V>::value, "Invalid visitor type.");
// Create the visitor.
diff --git a/src/variable_info.hpp b/src/variable_info.hpp
index af23b19edc8..155780bec67 100644
--- a/src/variable_info.hpp
+++ b/src/variable_info.hpp
@@ -17,7 +17,6 @@
#pragma once
#include "config.hpp"
-#include "utils/type_trait_aliases.hpp"
#include <string>
#include <type_traits>
@@ -100,7 +99,7 @@ public:
: variable_info<V>(name, game_vars)
{
static_assert(!std::is_same<
- variable_info_implementation::vi_policy_const, utils::remove_const_t<V>>::value,
+ variable_info_implementation::vi_policy_const, std::remove_const_t<V>>::value,
"variable_info_mutable cannot be specialized with 'vi_policy_const'"
);
}
diff --git a/src/video.cpp b/src/video.cpp
index f1f1038fd51..644d3d1b847 100644
--- a/src/video.cpp
+++ b/src/video.cpp
@@ -232,7 +232,9 @@ void CVideo::init_window()
// Add any more default flags here
window_flags |= SDL_WINDOW_RESIZABLE;
+#ifdef __APPLE__
window_flags |= SDL_WINDOW_ALLOW_HIGHDPI;
+#endif
if(preferences::fullscreen()) {
window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
diff --git a/src/wesconfig.h b/src/wesconfig.h
index f3c225ba312..0c5d1c410dc 100644
--- a/src/wesconfig.h
+++ b/src/wesconfig.h
@@ -40,11 +40,11 @@
#undef VERSION
#endif
-#define VERSION "1.14.5+dev"
+#define VERSION "1.15.0-dev"
// Used for the Windows executables' version info resource.
#define RC_VERSION_MAJOR 1
-#define RC_VERSION_MINOR 14
-#define RC_VERSION_REVISION 6
+#define RC_VERSION_MINOR 15
+#define RC_VERSION_REVISION 0
#endif
diff --git a/src/wesnoth.cpp b/src/wesnoth.cpp
index 50fa58b9147..714d48e1bf3 100644
--- a/src/wesnoth.cpp
+++ b/src/wesnoth.cpp
@@ -34,7 +34,7 @@
#include "gui/dialogs/message.hpp" // for show_error_message
#include "gui/dialogs/title_screen.hpp" // for title_screen, etc
#include "gui/gui.hpp" // for init
-#include "picture.hpp" // for flush_cache, etc
+#include "picture.hpp" // for flush_cache, etc
#include "log.hpp" // for LOG_STREAM, general, logger, etc
#include "preferences/general.hpp" // for core_id, etc
#include "scripting/application_lua_kernel.hpp"
@@ -50,7 +50,7 @@
#include "sound.hpp" // for commit_music_changes, etc
#include "statistics.hpp" // for fresh_stats
#include "utils/functional.hpp"
-#include "game_version.hpp"// for version_info
+#include "game_version.hpp" // for version_info
#include "video.hpp" // for CVideo
#include "wesconfig.h" // for PACKAGE
#include "widgets/button.hpp" // for button
@@ -116,10 +116,6 @@
#include <windows.h>
-#if defined(_OPENMP) && _MSC_VER >= 1600
-#include <process.h>
-#endif
-
#endif // _WIN32
#ifdef DEBUG_WINDOW_LAYOUT_GRAPHS
@@ -471,7 +467,7 @@ static int process_command_args(const commandline_options& cmdline_opts)
}
if(cmdline_opts.version) {
- std::cout << "Battle for Wesnoth" << " " << game_config::version << "\n\n";
+ std::cout << "Battle for Wesnoth" << " " << game_config::wesnoth_version.str() << "\n\n";
std::cout << "Library versions:\n" << game_config::library_versions_report() << '\n';
std::cout << "Optional features:\n" << game_config::optional_features_report();
@@ -506,7 +502,6 @@ static void init_locale()
setlocale(LC_ALL, "English");
#else
std::setlocale(LC_ALL, "C");
- translation::init();
#endif
const std::string& intl_dir = filesystem::get_intl_dir();
@@ -646,7 +641,7 @@ static int do_gameloop(const std::vector<std::string>& args)
return finished;
}
- const std::unique_ptr<game_launcher> game(new game_launcher(cmdline_opts, args[0].c_str()));
+ const auto game = std::make_unique<game_launcher>(cmdline_opts, args[0].c_str());
const int start_ticks = SDL_GetTicks();
init_locale();
@@ -963,42 +958,6 @@ static void wesnoth_terminate_handler(int)
}
#endif
-#if defined(_OPENMP) && _MSC_VER >= 1600
-static void restart_process()
-{
- wchar_t process_path[MAX_PATH];
- SetLastError(ERROR_SUCCESS);
- GetModuleFileNameW(nullptr, process_path, MAX_PATH);
-
- if(GetLastError() != ERROR_SUCCESS) {
- throw std::runtime_error("Failed to retrieve the process path");
- }
-
- std::wstring commandline_str(GetCommandLineW());
-
- // CreateProcessW is allowed to modify the passed command line.
- // Therefore we need to copy it.
- wchar_t* commandline_c_str = new wchar_t[commandline_str.length() + 1];
- commandline_str.copy(commandline_c_str, commandline_str.length());
- commandline_c_str[commandline_str.length()] = L'\0';
-
- STARTUPINFOW startup_info;
- ZeroMemory(&startup_info, sizeof(startup_info));
- startup_info.cb = sizeof(startup_info);
-
- PROCESS_INFORMATION process_info;
- ZeroMemory(&process_info, sizeof(process_info));
-
- CreateProcessW(
- process_path, commandline_c_str, nullptr, nullptr, false, 0u, nullptr, nullptr, &startup_info, &process_info);
-
- CloseHandle(process_info.hProcess);
- CloseHandle(process_info.hThread);
-
- std::exit(EXIT_SUCCESS);
-}
-#endif
-
#ifdef _WIN32
#define error_exit(res) \
do { \
@@ -1060,32 +1019,6 @@ int main(int argc, char** argv)
assert(!args.empty());
-#ifdef _OPENMP
- // Wesnoth is a special case for OMP
- // OMP wait strategy is to have threads busy-loop for 100ms
- // if there is nothing to do, they then go to sleep.
- // this avoids the scheduler putting the thread to sleep when work
- // is about to be available
- //
- // However Wesnoth has a lot of very small jobs that need to be done
- // at each redraw => 50fps every 2ms.
- // All the threads are thus busy-waiting all the time, hogging the CPU
- // To avoid that problem, we need to set the OMP_WAIT_POLICY env var
- // but that var is read by OMP at library loading time (before main)
- // thus the relaunching of ourselves after setting the variable.
-#if !defined(_WIN32) && !defined(__APPLE__)
- if(!getenv("OMP_WAIT_POLICY")) {
- setenv("OMP_WAIT_POLICY", "PASSIVE", 1);
- execv(argv[0], argv);
- }
-#elif _MSC_VER >= 1600
- if(!getenv("OMP_WAIT_POLICY")) {
- _putenv_s("OMP_WAIT_POLICY", "PASSIVE");
- restart_process();
- }
-#endif
-#endif //_OPENMP
-
filesystem::init();
if(SDL_Init(SDL_INIT_TIMER) < 0) {
@@ -1103,14 +1036,6 @@ int main(int argc, char** argv)
sigaction(SIGINT, &terminate_handler, nullptr);
#endif
- // Mac's touchpad generates touch events too.
- // Ignore them until Macs have a touchscreen: https://forums.libsdl.org/viewtopic.php?p=45758
-#if defined(__APPLE__) && !defined(__IPHONEOS__)
- SDL_EventState(SDL_FINGERMOTION, SDL_DISABLE);
- SDL_EventState(SDL_FINGERDOWN, SDL_DISABLE);
- SDL_EventState(SDL_FINGERUP, SDL_DISABLE);
-#endif
-
// declare this here so that it will always be at the front of the event queue.
events::event_context global_context;
diff --git a/src/wesnothd_connection.cpp b/src/wesnothd_connection.cpp
index 4e8fa36900b..67776d0df99 100644
--- a/src/wesnothd_connection.cpp
+++ b/src/wesnothd_connection.cpp
@@ -84,6 +84,10 @@ wesnothd_connection::wesnothd_connection(const std::string& host, const std::str
wesnothd_connection::~wesnothd_connection()
{
MPTEST_LOG;
+
+ // Stop the io_service and wait for the worker thread to terminate.
+ stop();
+ worker_thread_->join();
}
// main thread
@@ -152,9 +156,6 @@ void wesnothd_connection::handle_handshake(const error_code& ec)
recv();
worker_thread_.reset(new boost::thread([this]() {
- // worker thread
- std::shared_ptr<wesnothd_connection> this_ptr = this->shared_from_this();
-
io_service_.run();
LOG_NW << "wesnothd_connection::io_service::run() returned\n";
}));
@@ -435,31 +436,3 @@ bool wesnothd_connection::fetch_data_with_loading_screen(config& cfg, loading_st
return res;
}
-
-// wesnothd_connection_ptr
-
-wesnothd_connection_ptr& wesnothd_connection_ptr::operator=(wesnothd_connection_ptr&& other)
-{
- MPTEST_LOG;
- if(ptr_) {
- ptr_->stop();
- ptr_.reset();
- }
-
- ptr_ = std::move(other.ptr_);
- return *this;
-}
-
-wesnothd_connection_ptr wesnothd_connection::create(const std::string& host, const std::string& service)
-{
- // Can't use make_shared because the ctor is private
- return wesnothd_connection_ptr(std::shared_ptr<wesnothd_connection>(new wesnothd_connection(host, service)));
-}
-
-wesnothd_connection_ptr::~wesnothd_connection_ptr()
-{
- MPTEST_LOG;
- if(ptr_) {
- ptr_->stop();
- }
-}
diff --git a/src/wesnothd_connection.hpp b/src/wesnothd_connection.hpp
index de47b10991e..d55c535c365 100644
--- a/src/wesnothd_connection.hpp
+++ b/src/wesnothd_connection.hpp
@@ -16,10 +16,6 @@
#ifdef _WIN32
-#if _WIN32_WINNT < _WIN32_WINNT_VISTA
-#define BOOST_ASIO_DISABLE_IOCP
-#endif
-
#ifdef INADDR_ANY
#undef INADDR_ANY
#endif
@@ -49,7 +45,6 @@ class thread;
}
class config;
-class wesnothd_connection_ptr;
enum class loading_stage;
union data_union {
@@ -58,7 +53,7 @@ union data_union {
};
/** A class that represents a TCP/IP connection to the wesnothd server. */
-class wesnothd_connection : public std::enable_shared_from_this<wesnothd_connection>
+class wesnothd_connection
{
public:
using error = wesnothd_connection_error;
@@ -68,20 +63,15 @@ public:
~wesnothd_connection();
-private:
+public:
/**
* Constructor.
*
- * May only be called via wesnothd_connection_ptr
- *
* @param host Name of the host to connect to
* @param service Service identifier such as "80" or "http"
*/
wesnothd_connection(const std::string& host, const std::string& service);
-public:
- static wesnothd_connection_ptr create(const std::string& host, const std::string& service);
-
bool fetch_data_with_loading_screen(config& cfg, loading_stage stage);
void send_data(const configr_of& request);
@@ -190,72 +180,4 @@ private:
size_t bytes_read_;
};
-/**
- * This class acts like a unique_ptr<wesnothd_connection>, wesnothd_connection objects may only be owned though this
- * pointer. The reason why we need this is that wesnothd_connection runs a workerthread so we use a shared_ptr to make
- * sure the wesnothd_connection isn't destroyed before the worker thread has finished. When this object is destroyed, it
- * calls wesnothd_connection::stop() which stops the worker thread which will then destroy the other
- * shared_ptr<wesnothd_connection> which destroys the wesnothd_connection object.
- */
-class wesnothd_connection_ptr
-{
-private:
- friend class wesnothd_connection;
-
- wesnothd_connection_ptr(std::shared_ptr<wesnothd_connection>&& ptr)
- : ptr_(std::move(ptr))
- {
- }
-
-public:
- wesnothd_connection_ptr() = default;
-
- wesnothd_connection_ptr(const wesnothd_connection_ptr&) = delete;
- wesnothd_connection_ptr& operator=(const wesnothd_connection_ptr&) = delete;
-
-#if defined(_MSC_VER) && _MSC_VER == 1800
- wesnothd_connection_ptr(wesnothd_connection_ptr&& other)
- : ptr_(std::move(other.ptr_))
- {
- }
-
-#else
- wesnothd_connection_ptr(wesnothd_connection_ptr&&) = default;
-#endif
- wesnothd_connection_ptr& operator=(wesnothd_connection_ptr&&);
-
- ~wesnothd_connection_ptr();
-
- explicit operator bool() const
- {
- return !!ptr_;
- }
-
- wesnothd_connection& operator*()
- {
- return *ptr_;
- }
-
- const wesnothd_connection& operator*() const
- {
- return *ptr_;
- }
-
- wesnothd_connection* operator->()
- {
- return ptr_.get();
- }
-
- const wesnothd_connection* operator->() const
- {
- return ptr_.get();
- }
-
- wesnothd_connection* get() const
- {
- return ptr_.get();
- }
-
-private:
- std::shared_ptr<wesnothd_connection> ptr_;
-};
+using wesnothd_connection_ptr = std::unique_ptr<wesnothd_connection>;
diff --git a/src/whiteboard/manager.cpp b/src/whiteboard/manager.cpp
index 55a0f339a7e..c71e036208e 100644
--- a/src/whiteboard/manager.cpp
+++ b/src/whiteboard/manager.cpp
@@ -163,7 +163,7 @@ bool manager::can_modify_game_state() const
bool manager::can_activate() const
{
//any more than one reference means a lock on whiteboard state was requested
- if(!activation_state_lock_.unique())
+ if(activation_state_lock_.use_count() != 1)
return false;
return can_modify_game_state();
@@ -202,7 +202,7 @@ void manager::set_active(bool active)
void manager::set_invert_behavior(bool invert)
{
//any more than one reference means a lock on whiteboard state was requested
- if(!activation_state_lock_.unique())
+ if(activation_state_lock_.use_count() != 1)
return;
bool block_whiteboard_activation = false;
@@ -272,7 +272,7 @@ bool manager::allow_leader_to_move(const unit& leader) const
//Look for another leader on another keep in the same castle
{ wb::future_map future; // start planned unit map scope
-
+
// TODO: when the game executes all whiteboard moves at turn end applying the future map
// will fail because we are currently executing actions, and if one of those actions
// was a movement of the leader this function will be called, resulting the the error
@@ -479,7 +479,7 @@ static void draw_numbers(const map_location& hex, side_actions::numbers_t number
std::string number_text = std::to_string(number);
size_t font_size;
- if (int(i) == main_number) font_size = 19;
+ if (static_cast<int>(i) == main_number) font_size = 19;
else if (secondary_numbers.find(i)!=secondary_numbers.end()) font_size = 17;
else font_size = 15;
@@ -538,7 +538,7 @@ namespace
void manager::pre_draw()
{
- if (can_modify_game_state() && has_actions() && unit_map_lock_.unique()) {
+ if (can_modify_game_state() && has_actions() && unit_map_lock_.use_count() == 1) {
move_owners_finder move_finder;
for_each_action(std::ref(move_finder));
units_owning_moves_ = move_finder.get_units_owning_moves();
@@ -1173,7 +1173,7 @@ void manager::set_planned_unit_map()
return;
}
//any more than one reference means a lock on unit map was requested
- if(!unit_map_lock_.unique()) {
+ if(unit_map_lock_.use_count() != 1) {
LOG_WB << "Not building planned unit map: unit map locked.\n";
return;
}
diff --git a/src/whiteboard/mapbuilder.cpp b/src/whiteboard/mapbuilder.cpp
index 3aa9ea16f34..0cc942329fe 100644
--- a/src/whiteboard/mapbuilder.cpp
+++ b/src/whiteboard/mapbuilder.cpp
@@ -68,7 +68,7 @@ void mapbuilder::pre_build()
//Remove any unit the current side cannot see to avoid their detection by planning
//Units will be restored to the unit map by destruction of removers_
- if(!on_current_side && !u.is_visible_to_team(resources::gameboard->teams()[viewer_team()], *resources::gameboard, false)) {
+ if(!on_current_side && !u.is_visible_to_team(resources::gameboard->teams()[viewer_team()], false)) {
removers_.push_back(new temporary_unit_remover(resources::gameboard->units(), u.get_location()));
//Don't do anything else to the removed unit!
diff --git a/src/whiteboard/side_actions.cpp b/src/whiteboard/side_actions.cpp
index b6e5b8c151c..d021a3c0223 100644
--- a/src/whiteboard/side_actions.cpp
+++ b/src/whiteboard/side_actions.cpp
@@ -703,7 +703,6 @@ void side_actions::update_recruited_unit(size_t old_id, unit& new_unit)
}
}
-
side_actions::iterator side_actions::safe_insert(size_t turn, size_t pos, action_ptr act)
{
assert(act);
diff --git a/src/widgets/button.cpp b/src/widgets/button.cpp
index 573e7a00423..81611912dfb 100644
--- a/src/widgets/button.cpp
+++ b/src/widgets/button.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/button.hpp b/src/widgets/button.hpp
index 5684dd315de..131c5d7a027 100644
--- a/src/widgets/button.hpp
+++ b/src/widgets/button.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/menu.cpp b/src/widgets/menu.cpp
index 526789b5343..1eedef3de05 100644
--- a/src/widgets/menu.cpp
+++ b/src/widgets/menu.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/menu.hpp b/src/widgets/menu.hpp
index b735a88e7a8..7d4b5dba715 100644
--- a/src/widgets/menu.hpp
+++ b/src/widgets/menu.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/menu_style.cpp b/src/widgets/menu_style.cpp
index 3a8e4558c91..e748bdaed72 100644
--- a/src/widgets/menu_style.cpp
+++ b/src/widgets/menu_style.cpp
@@ -1,7 +1,7 @@
/*
wesnoth menu styles Copyright (C) 2006 - 2018 by Patrick Parker <patrick_x99@hotmail.com>
wesnoth menu Copyright (C) 2003-5 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/scrollarea.cpp b/src/widgets/scrollarea.cpp
index b7765a68b71..5f77aa9fe72 100644
--- a/src/widgets/scrollarea.cpp
+++ b/src/widgets/scrollarea.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2004 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -18,7 +18,6 @@
#include "widgets/scrollarea.hpp"
#include "sdl/rect.hpp"
-#include "video.hpp"
namespace gui {
@@ -26,7 +25,7 @@ namespace gui {
scrollarea::scrollarea(CVideo &video, const bool auto_join)
: widget(video, auto_join), scrollbar_(video),
old_position_(0), recursive_(false), shown_scrollbar_(false),
- shown_size_(0), full_size_(0), swipe_dy_(0)
+ shown_size_(0), full_size_(0)
{
scrollbar_.hide(true);
}
@@ -154,59 +153,19 @@ void scrollarea::handle_event(const SDL_Event& event)
if (mouse_locked() || hidden())
return;
- if (event.type == SDL_MOUSEWHEEL) {
- const SDL_MouseWheelEvent &ev = event.wheel;
- int x, y;
- SDL_GetMouseState(&x, &y);
- if (sdl::point_in_rect(x, y, inner_location())) {
- if (ev.y > 0) {
- scrollbar_.scroll_up();
- } else if (ev.y < 0) {
- scrollbar_.scroll_down();
- }
- }
- }
-
- if (event.type == SDL_FINGERUP) {
- swipe_dy_ = 0;
- }
-
- if (event.type == SDL_FINGERDOWN || event.type == SDL_FINGERMOTION) {
- SDL_Rect r = video().screen_area();
- auto tx = static_cast<int>(event.tfinger.x * r.w);
- auto ty = static_cast<int>(event.tfinger.y * r.h);
- auto dy = static_cast<int>(event.tfinger.dy * r.h);
-
- if (event.type == SDL_FINGERDOWN) {
- swipe_dy_ = 0;
- swipe_origin_.x = tx;
- swipe_origin_.y = ty;
- }
+ if (event.type != SDL_MOUSEWHEEL)
+ return;
- if (event.type == SDL_FINGERMOTION) {
-
- swipe_dy_ += dy;
- if (scrollbar_.get_max_position() == 0) {
- return;
- }
-
- int scrollbar_step = scrollbar_.height() / scrollbar_.get_max_position();
- if (scrollbar_step <= 0) {
- return;
- }
-
- if (sdl::point_in_rect(swipe_origin_.x, swipe_origin_.y, inner_location())
- && abs(swipe_dy_) >= scrollbar_step)
- {
- unsigned int pos = std::max(
- static_cast<int>(scrollbar_.get_position() - swipe_dy_ / scrollbar_step),
- 0);
- scrollbar_.set_position(pos);
- swipe_dy_ %= scrollbar_step;
- }
+ const SDL_MouseWheelEvent &ev = event.wheel;
+ int x, y;
+ SDL_GetMouseState(&x, &y);
+ if (sdl::point_in_rect(x, y, inner_location())) {
+ if (ev.y > 0) {
+ scrollbar_.scroll_up();
+ } else if (ev.y < 0) {
+ scrollbar_.scroll_down();
}
}
-
}
} // end namespace gui
diff --git a/src/widgets/scrollarea.hpp b/src/widgets/scrollarea.hpp
index 6fe0d11ec56..0f87681d8e2 100644
--- a/src/widgets/scrollarea.hpp
+++ b/src/widgets/scrollarea.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2004 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -60,11 +60,6 @@ private:
bool recursive_, shown_scrollbar_;
unsigned shown_size_;
unsigned full_size_;
- int swipe_dy_;
- struct {
- int x;
- int y;
- } swipe_origin_;
void test_scrollbar();
};
diff --git a/src/widgets/scrollbar.cpp b/src/widgets/scrollbar.cpp
index a181f04a512..7b737ccd880 100644
--- a/src/widgets/scrollbar.cpp
+++ b/src/widgets/scrollbar.cpp
@@ -1,7 +1,7 @@
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
2004 - 2015 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/scrollbar.hpp b/src/widgets/scrollbar.hpp
index 94891670af6..673f84d167c 100644
--- a/src/widgets/scrollbar.hpp
+++ b/src/widgets/scrollbar.hpp
@@ -1,7 +1,7 @@
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
2004 - 2015 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
diff --git a/src/widgets/textbox.cpp b/src/widgets/textbox.cpp
index 6c8826ffcc1..cccdf8baa87 100644
--- a/src/widgets/textbox.cpp
+++ b/src/widgets/textbox.cpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -30,7 +30,7 @@ static lg::log_domain log_display("display");
namespace gui {
textbox::textbox(CVideo &video, int width, const std::string& text, bool editable, size_t max_size, int font_size, double alpha, double alpha_focus, const bool auto_join)
- : scrollarea(video, auto_join), max_size_(max_size), font_size_(font_size), text_(unicode_cast<ucs4::string>(text)),
+ : scrollarea(video, auto_join), max_size_(max_size), font_size_(font_size), text_(unicode_cast<std::u32string>(text)),
cursor_(text_.size()), selstart_(-1), selend_(-1),
grabmouse_(false), text_pos_(0), editable_(editable),
show_cursor_(true), show_cursor_at_(0), text_image_(nullptr),
@@ -67,14 +67,14 @@ void textbox::set_inner_location(const SDL_Rect& rect)
const std::string textbox::text() const
{
- const std::string &ret = unicode_cast<utf8::string>(text_);
+ const std::string &ret = unicode_cast<std::string>(text_);
return ret;
}
// set_text does not respect max_size_
void textbox::set_text(const std::string& text, const color_t& color)
{
- text_ = unicode_cast<ucs4::string>(text);
+ text_ = unicode_cast<std::u32string>(text);
cursor_ = text_.size();
text_pos_ = 0;
selstart_ = -1;
@@ -96,7 +96,7 @@ void textbox::append_text(const std::string& text, bool auto_scroll, const color
return;
}
const bool is_at_bottom = get_position() == get_max_position();
- const ucs4::string& wtext = unicode_cast<ucs4::string>(text);
+ const std::u32string& wtext = unicode_cast<std::u32string>(text);
surface new_text = add_text_line(wtext, color);
surface new_surface = create_compatible_surface(text_image_,std::max<size_t>(text_image_->w,new_text->w),text_image_->h+new_text->h);
@@ -295,7 +295,7 @@ void textbox::scroll(unsigned int pos)
set_dirty(true);
}
-surface textbox::add_text_line(const ucs4::string& text, const color_t& color)
+surface textbox::add_text_line(const std::u32string& text, const color_t& color)
{
line_height_ = font::get_max_height(font_size_);
@@ -312,17 +312,17 @@ surface textbox::add_text_line(const ucs4::string& text, const color_t& color)
// some more complex scripts (that is, RTL languages). This part of the work should
// actually be done by the font-rendering system.
std::string visible_string;
- ucs4::string wrapped_text;
+ std::u32string wrapped_text;
- ucs4::string::const_iterator backup_itor = text.end();
+ std::u32string::const_iterator backup_itor = text.end();
- ucs4::string::const_iterator itor = text.begin();
+ std::u32string::const_iterator itor = text.begin();
while(itor != text.end()) {
//If this is a space, save copies of the current state so we can roll back
if(char(*itor) == ' ') {
backup_itor = itor;
}
- visible_string.append(unicode_cast<utf8::string>(*itor));
+ visible_string.append(unicode_cast<std::string>(*itor));
if(char(*itor) == '\n') {
backup_itor = text.end();
@@ -341,12 +341,12 @@ surface textbox::add_text_line(const ucs4::string& text, const color_t& color)
wrapped_text.erase(wrapped_text.end()-backup, wrapped_text.end());
}
} else {
- if (visible_string == std::string("").append(unicode_cast<utf8::string>(*itor))) {
+ if (visible_string == std::string("").append(unicode_cast<std::string>(*itor))) {
break; //breaks infinite loop where when running with a fake display, we word wrap a single character infinitely.
}
}
backup_itor = text.end();
- wrapped_text.push_back(ucs4::char_t('\n'));
+ wrapped_text.push_back(char32_t('\n'));
char_x_.push_back(0);
char_y_.push_back(char_y_.back() + line_height_);
visible_string = "";
@@ -358,7 +358,7 @@ surface textbox::add_text_line(const ucs4::string& text, const color_t& color)
}
}
- const std::string s = unicode_cast<utf8::string>(wrapped_text);
+ const std::string s = unicode_cast<std::string>(wrapped_text);
const surface res(font::get_rendered_text(s, font_size_, color));
return res;
@@ -399,7 +399,7 @@ void textbox::erase_selection()
if(!is_selection())
return;
- ucs4::string::iterator itor = text_.begin() + std::min(selstart_, selend_);
+ std::u32string::iterator itor = text_.begin() + std::min(selstart_, selend_);
text_.erase(itor, itor + std::abs(selend_ - selstart_));
cursor_ = std::min(selstart_, selend_);
selstart_ = selend_ = -1;
@@ -452,8 +452,8 @@ void textbox::handle_event(const SDL_Event& event)
bool textbox::handle_text_input(const SDL_Event& event)
{
bool changed = false;
- utf8::string str = event.text.text;
- ucs4::string s = unicode_cast<ucs4::string>(str);
+ std::string str = event.text.text;
+ std::u32string s = unicode_cast<std::u32string>(str);
DBG_G << "Char: " << str << "\n";
@@ -567,7 +567,7 @@ bool textbox::handle_key_down(const SDL_Event &event)
//cut off anything after the first newline
str.erase(std::find_if(str.begin(),str.end(),utils::isnewline),str.end());
- ucs4::string s = unicode_cast<ucs4::string>(str);
+ std::u32string s = unicode_cast<std::u32string>(str);
if(text_.size() < max_size_) {
if(s.size() + text_.size() > max_size_) {
@@ -588,33 +588,13 @@ bool textbox::handle_key_down(const SDL_Event &event)
const size_t beg = std::min<size_t>(size_t(selstart_),size_t(selend_));
const size_t end = std::max<size_t>(size_t(selstart_),size_t(selend_));
- ucs4::string ws(text_.begin() + beg, text_.begin() + end);
- std::string s = unicode_cast<utf8::string>(ws);
+ std::u32string ws(text_.begin() + beg, text_.begin() + end);
+ std::string s = unicode_cast<std::string>(ws);
desktop::clipboard::copy_to_clipboard(s, false);
}
}
break;
-
- case SDLK_x: // cut
- {
- if(is_selection())
- {
- const size_t beg = std::min<size_t>(size_t(selstart_),size_t(selend_));
- const size_t end = std::max<size_t>(size_t(selstart_),size_t(selend_));
-
- ucs4::string ws(text_.begin() + beg, text_.begin() + end);
- std::string s = unicode_cast<utf8::string>(ws);
- desktop::clipboard::copy_to_clipboard(s, false);
- erase_selection();
- }
- break;
- }
- case SDLK_a: // selectall
- {
- set_selection(0, text_.size());
- break;
}
- }//end switch
}
else {
pass_event_to_target(event);
diff --git a/src/widgets/textbox.hpp b/src/widgets/textbox.hpp
index d65b2264a07..45df06f2d3b 100644
--- a/src/widgets/textbox.hpp
+++ b/src/widgets/textbox.hpp
@@ -1,6 +1,6 @@
/*
Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
- Part of the Battle for Wesnoth Project https://www.wesnoth.org/
+ Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -55,13 +55,13 @@ protected:
virtual void scroll(unsigned int pos);
private:
- virtual void handle_text_changed(const ucs4::string&) {}
+ virtual void handle_text_changed(const std::u32string&) {}
size_t max_size_;
int font_size_;
- ucs4::string text_;
+ std::u32string text_;
// mutable unsigned int firstOnScreen_;
int cursor_;
@@ -106,7 +106,7 @@ private:
void draw_cursor(int pos) const;
void update_text_cache(bool reset = false, const color_t& color =font::NORMAL_COLOR);
- surface add_text_line(const ucs4::string& text, const color_t& color =font::NORMAL_COLOR);
+ surface add_text_line(const std::u32string& text, const color_t& color =font::NORMAL_COLOR);
bool is_selection();
void erase_selection();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment