Revert token t_token commits from 2011-09-08T19:15:40Z!thonsew@yahoo.com on.

This commit is contained in:
Alexander van Gessel 2011-10-10 03:43:29 +01:00
parent 5c4410abee
commit 81e0a2007f
152 changed files with 5247 additions and 10743 deletions

View file

@ -49,10 +49,6 @@ Version 1.9.9+svn:
* Fixed handling of #ifver and #ifnver preprocessor directives in wmllint
* Made it possible to switch themes from Preferences in the main menu
(bug #10969)
* Fixed bug #18715 where deleting of .cache directory and then regenerating
the cache F5 in a running instance of wesnoth caused a crash
* Fixed bug #18777: #ifver/#ifnver directives with the --preprocess command
don't throw anymore "undefined macro" errors
Version 1.9.9:
* AI:

View file

@ -2061,7 +2061,6 @@
# pick one random ghost_spawn from which
# to store all locations in range
{RANDOM 1..$ghost_spawn.length}
{VARIABLE_OP random sub 1}
{VARIABLE ghost_x $ghost_spawn[$random].x}
{VARIABLE ghost_y $ghost_spawn[$random].y}
{CLEAR_VARIABLE ghost_spawn}

View file

@ -166,14 +166,6 @@ Recruiting"
[event]
name=start
{VARIABLE next_turn.advice_chain[0].turn -1 }
{VARIABLE next_turn.advice_chain[1].turn -1 }
{VARIABLE next_turn.advice_chain[2].turn -1 }
{VARIABLE next_turn.advice_chain[3].turn -1 }
{VARIABLE next_turn.advice_chain[4].turn -1 }
{VARIABLE next_turn.advice_chain[5].turn -1 }
[message]
speaker=narrator
message= _"Who would you like to play?"

View file

@ -1019,20 +1019,12 @@ Also, 0..9 = $below_ten, one,two,three = $ascii and the bonus answer is $mixed."
to_local=territory
[/get_global_variable]
[if]
[or]
[not]
[variable]
name=territory[0].length
equals=$empty
[/variable]
[/not]
[not]
[variable]
name=territory[0].x
equals=$empty
[/variable]
[/not]
[/or]
[then]
{FOREACH territory i}
[capture_village]

View file

@ -355,7 +355,6 @@ set(wesnoth-main_SRC
editor/map_context.cpp
editor/map_fragment.cpp
editor/mouse_action.cpp
exceptions.cpp
filechooser.cpp
floating_textbox.cpp
formula.cpp
@ -363,7 +362,6 @@ set(wesnoth-main_SRC
formula_debugger_fwd.cpp
formula_function.cpp
formula_string_utils.cpp
formula_string_utils_backend.cpp
formula_tokenizer.cpp
game_controller.cpp
game_controller_abstract.cpp
@ -557,7 +555,6 @@ set(wesnoth-main_SRC
storyscreen/part.cpp
storyscreen/render.cpp
team.cpp
team_builder.cpp
terrain_filter.cpp
tod_manager.cpp
tooltips.cpp

View file

@ -23,7 +23,6 @@ libwesnoth_core_sources = Split("""
map_location.cpp
md5.cpp
thread.cpp
token.cpp
tstring.cpp
util.cpp
version.cpp
@ -114,7 +113,6 @@ libwesnoth_sources = Split("""
tooltips.cpp
video.cpp
theme.cpp
utils/interned.cpp
widgets/button.cpp
widgets/file_menu.cpp
widgets/label.cpp
@ -220,7 +218,6 @@ wesnoth_sources = Split("""
editor/map_context.cpp
editor/map_fragment.cpp
editor/mouse_action.cpp
exceptions.cpp
filechooser.cpp
floating_textbox.cpp
formula.cpp
@ -228,7 +225,6 @@ wesnoth_sources = Split("""
formula_debugger_fwd.cpp
formula_function.cpp
formula_string_utils.cpp
formula_string_utils_backend.cpp
formula_tokenizer.cpp
game_controller.cpp
game_controller_abstract.cpp
@ -420,7 +416,6 @@ wesnoth_sources = Split("""
storyscreen/part.cpp
storyscreen/render.cpp
team.cpp
team_builder.cpp
terrain_filter.cpp
tod_manager.cpp
unit.cpp
@ -546,15 +541,12 @@ test_sources = Split("""
tests/test_formula_ai.cpp
tests/test_formula_function.cpp
tests/test_image_modifications.cpp
tests/test_interpolate_variables_into_thing.cpp
tests/test_lexical_cast.cpp
tests/test_lru_cache.cpp
tests/test_network_worker.cpp
tests/test_team.cpp
tests/test_unit_map.cpp
tests/test_util.cpp
tests/test_serialization.cpp
tests/test_token.cpp
tests/test_version.cpp
tests/gui/fire_event.cpp
tests/gui/iterator.cpp

View file

@ -100,7 +100,7 @@ void set_about(const config &cfg)
foreach (const config &about, cfg.child_range("about"))
{
about_list.add_child("about", about);
const std::string im = about["images"];
const std::string &im = about["images"];
if (!images.empty())
{
if (images_default.empty())
@ -117,14 +117,14 @@ void set_about(const config &cfg)
config temp;
std::ostringstream text;
const std::string id = campaign["id"];
const std::string &id = campaign["id"];
temp["title"] = campaign["name"];
temp["id"] = id;
std::string campaign_images;
foreach (const config &about, abouts)
{
const std::string subtitle = about["title"];
const std::string &subtitle = about["title"];
if (!subtitle.empty())
{
text << '+';
@ -145,7 +145,7 @@ void set_about(const config &cfg)
text << " " << entry["name"] << '\n';
}
const std::string im = about["images"];
const std::string &im = about["images"];
if (!im.empty())
{
if (campaign_images.empty())

View file

@ -198,32 +198,23 @@ unit_creator& unit_creator::allow_add_to_recall(bool b)
map_location unit_creator::find_location(const config &cfg, const unit* pass_check)
{
static const config::t_token & z_id( generate_safe_static_const_t_interned(n_token::t_token("id")) );
static const config::t_token & z_placement( generate_safe_static_const_t_interned(n_token::t_token("placement")) );
static const config::t_token & z_x( generate_safe_static_const_t_interned(n_token::t_token("x")) );
static const config::t_token & z_y( generate_safe_static_const_t_interned(n_token::t_token("y")) );
static const config::t_token & z_map( generate_safe_static_const_t_interned(n_token::t_token("map")) );
static const config::t_token & z_recall( generate_safe_static_const_t_interned(n_token::t_token("recall")) );
static const config::t_token & z_leader_passable( generate_safe_static_const_t_interned(n_token::t_token("leader_passable")) );
static const config::t_token & z_map_passable( generate_safe_static_const_t_interned(n_token::t_token("map_passable")) );
static const config::t_token & z_leader( generate_safe_static_const_t_interned(n_token::t_token("leader")) );
DBG_NG << "finding location for unit with id=["<<cfg[z_id]<<"] placement=["<<cfg[z_placement]<<"] x=["<<cfg[z_x]<<"] y=["<<cfg[z_y]<<"] for side " << team_.side() << "\n";
DBG_NG << "finding location for unit with id=["<<cfg["id"]<<"] placement=["<<cfg["placement"]<<"] x=["<<cfg["x"]<<"] y=["<<cfg["y"]<<"] for side " << team_.side() << "\n";
std::vector< config::t_token > placements = utils::split_attr(cfg[z_placement]);
std::vector< std::string > placements = utils::split(cfg["placement"]);
placements.push_back(z_map);
placements.push_back(z_recall);
placements.push_back("map");
placements.push_back("recall");
foreach(config::t_token place, placements) {
foreach(std::string place, placements) {
map_location loc;
bool pass((place == z_leader_passable) || (place == z_map_passable));
bool pass((place == "leader_passable") || (place == "map_passable"));
if (place == z_recall ) {
if (place == "recall" ) {
return map_location::null_location;
}
if (place == z_leader || place == z_leader_passable) {
if (place == "leader" || place == "leader_passable") {
unit_map::const_iterator leader = resources::units->find_leader(team_.side());
//todo: take 'leader in recall list' possibility into account
if (leader.valid()) {
@ -233,7 +224,7 @@ map_location unit_creator::find_location(const config &cfg, const unit* pass_che
}
}
if (place==z_map || place == z_map_passable) {
if (place=="map" || place == "map_passable") {
loc = map_location(cfg,resources::state_of_game);
}
@ -256,21 +247,14 @@ map_location unit_creator::find_location(const config &cfg, const unit* pass_che
void unit_creator::add_unit(const config &cfg)
{
static const config::t_token & z_side( generate_safe_static_const_t_interned(n_token::t_token("side")) );
static const config::t_token & z_player_id( generate_safe_static_const_t_interned(n_token::t_token("player_id")) );
static const config::t_token & z_faction_from_recruit( generate_safe_static_const_t_interned(n_token::t_token("faction_from_recruit")) );
static const config::t_token & z_id( generate_safe_static_const_t_interned(n_token::t_token("id")) );
static const config::t_token & z_animate( generate_safe_static_const_t_interned(n_token::t_token("animate")) );
config temp_cfg(cfg);
temp_cfg[z_side] = team_.side();
temp_cfg.remove_attribute(z_player_id);
temp_cfg.remove_attribute(z_faction_from_recruit);
temp_cfg["side"] = team_.side();
temp_cfg.remove_attribute("player_id");
temp_cfg.remove_attribute("faction_from_recruit");
const config::attribute_value& aid =(cfg)[z_id];
const config::t_token& id = aid.token();
bool animate = temp_cfg[z_animate].to_bool();
temp_cfg.remove_attribute(z_animate);
const std::string& id =(cfg)["id"];
bool animate = temp_cfg["animate"].to_bool();
temp_cfg.remove_attribute("animate");
std::vector<unit>::iterator recall_list_element = std::find_if(team_.recall_list().begin(), team_.recall_list().end(), boost::bind(&unit::matches_id, _1, id));
@ -298,7 +282,7 @@ void unit_creator::add_unit(const config &cfg)
//get unit from recall list
map_location loc = find_location(temp_cfg, &(*recall_list_element));
if(!loc.valid()) {
LOG_NG << "wanted to insert unit on recall list, but recall list for side " << (cfg)[z_side] << "already contains id=" <<id<<"\n";
LOG_NG << "wanted to insert unit on recall list, but recall list for side " << (cfg)["side"] << "already contains id=" <<id<<"\n";
return;
} else {
resources::units->add(loc, *recall_list_element);
@ -586,12 +570,6 @@ void place_recruit(const unit &u, const map_location &recruit_location,
bool is_recall, bool show, bool fire_event, bool full_movement,
bool wml_triggered)
{
static const config::t_token & z_prerecall( generate_safe_static_const_t_interned(n_token::t_token("prerecall")) );
static const config::t_token & z_prerecruit( generate_safe_static_const_t_interned(n_token::t_token("prerecruit")) );
static const config::t_token & z_recall( generate_safe_static_const_t_interned(n_token::t_token("recall")) );
static const config::t_token & z_recruit( generate_safe_static_const_t_interned(n_token::t_token("recruit")) );
static const config::t_token & z_checksum( generate_safe_static_const_t_interned(n_token::t_token("checksum")) );
LOG_NG << "placing new unit on location " << recruit_location << "\n";
assert(resources::units->count(recruit_location) == 0);
@ -612,13 +590,13 @@ void place_recruit(const unit &u, const map_location &recruit_location,
{
if (fire_event) {
LOG_NG << "firing prerecall event\n";
game_events::fire(z_prerecall,recruit_location);
game_events::fire("prerecall",recruit_location);
}
}
else
{
LOG_NG << "firing prerecruit event\n";
game_events::fire(z_prerecruit,recruit_location);
game_events::fire("prerecruit",recruit_location);
}
const unit_map::iterator new_unit_itor = resources::units->find(recruit_location);
if (new_unit_itor.valid()) {
@ -648,13 +626,13 @@ void place_recruit(const unit &u, const map_location &recruit_location,
{
if (fire_event) {
LOG_NG << "firing recall event\n";
game_events::fire(z_recall,recruit_location);
game_events::fire("recall",recruit_location);
}
}
else
{
LOG_NG << "firing recruit event\n";
game_events::fire(z_recruit,recruit_location);
game_events::fire("recruit",recruit_location);
}
const std::string checksum = get_checksum(new_unit);
@ -664,7 +642,7 @@ void place_recruit(const unit &u, const map_location &recruit_location,
// When recalling from WML there should be no random results, if we use
// random we might get the replay out of sync.
assert(!wml_triggered);
const std::string rc = (*ran_results)[z_checksum];
const std::string rc = (*ran_results)["checksum"];
if(rc != checksum) {
std::stringstream error_msg;
error_msg << "SYNC: In recruit " << new_unit.type_id() <<
@ -681,7 +659,7 @@ void place_recruit(const unit &u, const map_location &recruit_location,
} else if(wml_triggered == false) {
config cfg;
cfg[z_checksum] = checksum;
cfg["checksum"] = checksum;
set_random_results(cfg);
}
@ -691,18 +669,16 @@ void place_recruit(const unit &u, const map_location &recruit_location,
map_location under_leadership(const unit_map& units,
const map_location& loc, int* bonus)
{
static const config::t_token & z_leadership( generate_safe_static_const_t_interned(n_token::t_token("leadership")) );
static const config::t_token & z_value( generate_safe_static_const_t_interned(n_token::t_token("value")) );
const unit_map::const_iterator un = units.find(loc);
if(un == units.end()) {
return map_location::null_location;
}
unit_ability_list abil = un->get_abilities(z_leadership);
unit_ability_list abil = un->get_abilities("leadership");
if(bonus) {
*bonus = abil.highest(z_value).first;
*bonus = abil.highest("value").first;
}
return abil.highest(z_value).second;
return abil.highest("value").second;
}
battle_context::battle_context(const unit_map& units,
@ -1032,24 +1008,6 @@ battle_context_unit_stats::battle_context_unit_stats(const unit &u, const map_lo
swarm_max(0),
plague_type()
{
static const config::t_token & z_null( generate_safe_static_const_t_interned(n_token::t_token("null")) );
static const config::t_token & z_not_living( generate_safe_static_const_t_interned(n_token::t_token("not_living")) );
static const config::t_token & z_slow( generate_safe_static_const_t_interned(n_token::t_token("slow")) );
static const config::t_token & z_drains( generate_safe_static_const_t_interned(n_token::t_token("drains")) );
static const config::t_token & z_petrifies( generate_safe_static_const_t_interned(n_token::t_token("petrifies")) );
static const config::t_token & z_poison( generate_safe_static_const_t_interned(n_token::t_token("poison")) );
static const config::t_token & z_berserk( generate_safe_static_const_t_interned(n_token::t_token("berserk")) );
static const config::t_token & z_value( generate_safe_static_const_t_interned(n_token::t_token("value")) );
static const config::t_token & z_firststrike( generate_safe_static_const_t_interned(n_token::t_token("firststrike")) );
static const config::t_token & z_plague( generate_safe_static_const_t_interned(n_token::t_token("plague")) );
static const config::t_token & z_type( generate_safe_static_const_t_interned(n_token::t_token("type")) );
static const config::t_token & z_chance_to_hit( generate_safe_static_const_t_interned(n_token::t_token("chance_to_hit")) );
static const config::t_token & z_damage( generate_safe_static_const_t_interned(n_token::t_token("damage")) );
static const config::t_token & z_swarm( generate_safe_static_const_t_interned(n_token::t_token("swarm")) );
static const config::t_token & z_swarm_attacks_min( generate_safe_static_const_t_interned(n_token::t_token("swarm_attacks_min")) );
static const config::t_token & z_swarm_attacks_max( generate_safe_static_const_t_interned(n_token::t_token("swarm_attacks_max")) );
static const config::t_token & z_attacks( generate_safe_static_const_t_interned(n_token::t_token("attacks")) );
// Get the current state of the unit.
if (attack_num >= 0) {
weapon = &u.attacks()[attack_num];
@ -1079,22 +1037,22 @@ battle_context_unit_stats::battle_context_unit_stats(const unit &u, const map_lo
weapon->set_specials_context(*aloc, *dloc, units, attacking, opp_weapon);
if (opp_weapon)
opp_weapon->set_specials_context(*aloc, *dloc, units, !attacking, weapon);
bool not_living = opp.get_state(z_not_living);
slows = weapon->get_special_bool(z_slow);
drains = !not_living && weapon->get_special_bool(z_drains);
petrifies = weapon->get_special_bool(z_petrifies);
poisons = !not_living && weapon->get_special_bool(z_poison) && !opp.get_state(unit::STATE_POISONED);
bool not_living = opp.get_state("not_living");
slows = weapon->get_special_bool("slow");
drains = !not_living && weapon->get_special_bool("drains");
petrifies = weapon->get_special_bool("petrifies");
poisons = !not_living && weapon->get_special_bool("poison") && !opp.get_state(unit::STATE_POISONED);
backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, *resources::teams);
rounds = weapon->get_specials(z_berserk).highest(z_value, 1).first;
firststrike = weapon->get_special_bool(z_firststrike);
rounds = weapon->get_specials("berserk").highest("value", 1).first;
firststrike = weapon->get_special_bool("firststrike");
// Handle plague.
unit_ability_list plague_specials = weapon->get_specials(z_plague);
unit_ability_list plague_specials = weapon->get_specials("plague");
plagues = !not_living && !plague_specials.empty() &&
(opp.undead_variation() != z_null) && !resources::game_map->is_village(opp_loc);
strcmp(opp.undead_variation().c_str(), "null") && !resources::game_map->is_village(opp_loc);
if (plagues) {
plague_type = (*plague_specials.cfgs.front().first)[z_type].token();
plague_type = (*plague_specials.cfgs.front().first)["type"].str();
if (plague_type.empty())
plague_type = u.type_id();
}
@ -1105,13 +1063,13 @@ battle_context_unit_stats::battle_context_unit_stats(const unit &u, const map_lo
chance_to_hit = 100;
}
unit_ability_list cth_specials = weapon->get_specials(z_chance_to_hit);
unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
unit_abilities::effect cth_effects(cth_specials, chance_to_hit, backstab_pos);
chance_to_hit = cth_effects.get_composite_value();
// Compute base damage done with the weapon.
int base_damage = weapon->damage();
unit_ability_list dmg_specials = weapon->get_specials(z_damage);
unit_ability_list dmg_specials = weapon->get_specials("damage");
unit_abilities::effect dmg_effect(dmg_specials, base_damage, backstab_pos);
base_damage = dmg_effect.get_composite_value();
@ -1137,17 +1095,17 @@ battle_context_unit_stats::battle_context_unit_stats(const unit &u, const map_lo
damage = slow_damage;
// Compute the number of blows and handle swarm.
unit_ability_list swarm_specials = weapon->get_specials(z_swarm);
unit_ability_list swarm_specials = weapon->get_specials("swarm");
if (!swarm_specials.empty()) {
swarm = true;
swarm_min = swarm_specials.highest(z_swarm_attacks_min).first;
swarm_max = swarm_specials.highest(z_swarm_attacks_max, weapon->num_attacks()).first;
swarm_min = swarm_specials.highest("swarm_attacks_min").first;
swarm_max = swarm_specials.highest("swarm_attacks_max", weapon->num_attacks()).first;
num_blows = swarm_min + (swarm_max - swarm_min) * hp / max_hp;
} else {
swarm = false;
num_blows = weapon->num_attacks();
unit_ability_list attacks_specials = weapon->get_specials(z_attacks);
unit_ability_list attacks_specials = weapon->get_specials("attacks");
unit_abilities::effect attacks_effect(attacks_specials,num_blows,backstab_pos);
const int num_blows_with_specials = attacks_effect.get_composite_value();
if(num_blows_with_specials >= 0) {
@ -1210,7 +1168,7 @@ class attack
~attack();
class attack_end_exception {};
void fire_event(const config::t_token& n);
void fire_event(const std::string& n);
void refresh_bc();
/** Structure holding unit info used in the attack action. */
@ -1249,32 +1207,26 @@ class attack
bool OOS_error_;
};
void attack::fire_event(const config::t_token& n)
void attack::fire_event(const std::string& n)
{
static const config::t_token & z_first( generate_safe_static_const_t_interned(n_token::t_token("first")) );
static const config::t_token & z_second( generate_safe_static_const_t_interned(n_token::t_token("second")) );
static const config::t_token & z_name( generate_safe_static_const_t_interned(n_token::t_token("name")) );
static const config::t_token & z_none( generate_safe_static_const_t_interned(n_token::t_token("none")) );
static const config::t_token & z_attack_end( generate_safe_static_const_t_interned(n_token::t_token("attack_end")) );
LOG_NG << "firing " << n << " event\n";
//prepare the event data for weapon filtering
config ev_data;
config& a_weapon_cfg = ev_data.add_child(z_first);
config& d_weapon_cfg = ev_data.add_child(z_second);
config& a_weapon_cfg = ev_data.add_child("first");
config& d_weapon_cfg = ev_data.add_child("second");
if(a_stats_->weapon != NULL && a_.valid()) {
a_weapon_cfg = a_stats_->weapon->get_cfg();
}
if(d_stats_->weapon != NULL && d_.valid()) {
d_weapon_cfg = d_stats_->weapon->get_cfg();
}
if(a_weapon_cfg[z_name].empty()) {
a_weapon_cfg[z_name] = z_none;
if(a_weapon_cfg["name"].empty()) {
a_weapon_cfg["name"] = "none";
}
if(d_weapon_cfg[z_name].empty()) {
d_weapon_cfg[z_name] = z_none;
if(d_weapon_cfg["name"].empty()) {
d_weapon_cfg["name"] = "none";
}
if(n == z_attack_end) {
if(n == "attack_end") {
// We want to fire attack_end event in any case! Even if one of units was removed by WML
game_events::fire(n, a_.loc_, d_.loc_, ev_data);
return;
@ -1294,7 +1246,7 @@ void attack::fire_event(const config::t_token& n)
resources::screen->recalculate_minimap();
resources::screen->draw(true, true);
}
fire_event(z_attack_end);
fire_event("attack_end");
throw attack_end_exception();
}
}
@ -1306,14 +1258,14 @@ namespace {
weap_index = -1;
return;
}
if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == config::t_token(weap_id)) {
if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
//the currently selected attack fits
return;
}
if(!weap_id.empty()) {
//lookup the weapon by id
for(int i=0; i<static_cast<int>(attacks.size()); ++i) {
if(attacks[i].id() == config::t_token(weap_id)) {
if(attacks[i].id() == weap_id) {
weap_index = i;
return;
}
@ -1429,35 +1381,6 @@ attack::attack(const map_location &attacker, const map_location &defender,
bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
{
static const config::t_token & z_damage_inflicted( generate_safe_static_const_t_interned(n_token::t_token("damage_inflicted")) );
static const config::t_token & z_chance( generate_safe_static_const_t_interned(n_token::t_token("chance")) );
static const config::t_token & z_hits( generate_safe_static_const_t_interned(n_token::t_token("hits")) );
static const config::t_token & z_damage( generate_safe_static_const_t_interned(n_token::t_token("damage")) );
static const config::t_token & z_successful( generate_safe_static_const_t_interned(n_token::t_token("successful")) );
static const config::t_token & z_unsuccessful( generate_safe_static_const_t_interned(n_token::t_token("unsuccessful")) );
static const config::t_token & z_dies( generate_safe_static_const_t_interned(n_token::t_token("dies")) );
static const config::t_token & z_unit_hit( generate_safe_static_const_t_interned(n_token::t_token("unit_hit")) );
static const config::t_token & z_defender( generate_safe_static_const_t_interned(n_token::t_token("defender")) );
static const config::t_token & z_attacker( generate_safe_static_const_t_interned(n_token::t_token("attacker")) );
static const config::t_token & z_perished( generate_safe_static_const_t_interned(n_token::t_token("perished")) );
static const config::t_token & z_survived( generate_safe_static_const_t_interned(n_token::t_token("survived")) );
static const config::t_token & z_attacker_hits( generate_safe_static_const_t_interned(n_token::t_token("attacker_hits")) );
static const config::t_token & z_defender_hits( generate_safe_static_const_t_interned(n_token::t_token("defender_hits")) );
static const config::t_token & z_attacker_misses( generate_safe_static_const_t_interned(n_token::t_token("attacker_misses")) );
static const config::t_token & z_defender_misses( generate_safe_static_const_t_interned(n_token::t_token("defender_misses")) );
static const config::t_token & z_attack_end( generate_safe_static_const_t_interned(n_token::t_token("attack_end")) );
static const config::t_token & z_first( generate_safe_static_const_t_interned(n_token::t_token("first")) );
static const config::t_token & z_second( generate_safe_static_const_t_interned(n_token::t_token("second")) );
static const config::t_token & z_last_breath( generate_safe_static_const_t_interned(n_token::t_token("last_breath")) );
static const config::t_token & z_die( generate_safe_static_const_t_interned(n_token::t_token("die")) );
static const config::t_token & z_null( generate_safe_static_const_t_interned(n_token::t_token("null")) );
static const config::t_token & z_effect( generate_safe_static_const_t_interned(n_token::t_token("effect")) );
static const config::t_token & z_apply_to( generate_safe_static_const_t_interned(n_token::t_token("apply_to")) );
static const config::t_token & z_variation( generate_safe_static_const_t_interned(n_token::t_token("variation")) );
static const config::t_token & z_name( generate_safe_static_const_t_interned(n_token::t_token("name")) );
static const config::t_token & z_petrified( generate_safe_static_const_t_interned(n_token::t_token("petrified")) );
static const config::t_token & z_none( generate_safe_static_const_t_interned(n_token::t_token("none")) );
unit_info
&attacker = *(attacker_turn ? &a_ : &d_),
&defender = *(attacker_turn ? &d_ : &a_);
@ -1473,7 +1396,7 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
int damage = 0;
if (hits) {
damage = attacker.damage_;
resources::state_of_game->get_variable(z_damage_inflicted) = damage;
resources::state_of_game->get_variable("damage_inflicted") = damage;
}
// Make sure that if we're serializing a game here,
@ -1481,9 +1404,9 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
const config *ran_results = get_random_results();
if (ran_results)
{
int results_chance = (*ran_results)[z_chance];
bool results_hits = (*ran_results)[z_hits].to_bool();
int results_damage = (*ran_results)[z_damage];
int results_chance = (*ran_results)["chance"];
bool results_hits = (*ran_results)["hits"].to_bool();
int results_damage = (*ran_results)["damage"];
if (results_chance != attacker.cth_)
{
@ -1499,9 +1422,9 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
{
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
<< ": the data source says the hit was "
<< (results_hits ? z_successful : z_unsuccessful)
<< (results_hits ? "successful" : "unsuccessful")
<< ", while in-game calculations say the hit was "
<< (hits ? z_successful : z_unsuccessful)
<< (hits ? "successful" : "unsuccessful")
<< " random number: " << ran_num << " = "
<< (ran_num % 100) << "/" << results_chance
<< " (over-riding game calculations with data source results)\n";
@ -1529,23 +1452,23 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
const unit &defender_unit = defender.get_unit();
if (attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
float_text << (defender_unit.gender() == unit_race::FEMALE ?
_("female^poisoned") : _("poisoned")) << '\n';
_("female^poisoned") : _("poisoned")) << '\n';
}
if (attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
float_text << (defender_unit.gender() == unit_race::FEMALE ?
_("female^slowed") : _("slowed")) << '\n';
_("female^slowed") : _("slowed")) << '\n';
}
if (attacker_stats->petrifies) {
float_text << (defender_unit.gender() == unit_race::FEMALE ?
_("female^petrified") : _("petrified")) << '\n';
_("female^petrified") : _("petrified")) << '\n';
}
}
unit_display::unit_attack(attacker.loc_, defender.loc_, damage,
*attacker_stats->weapon, defender_stats->weapon,
abs_n, float_text.str(), attacker_stats->drains, n_token::t_token::z_empty());
abs_n, float_text.str(), attacker_stats->drains, "");
}
int drains_damage = 0;
@ -1573,25 +1496,25 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
{
log_scope2(log_engine, "setting random results");
config cfg;
cfg[z_hits] = hits;
cfg[z_dies] = dies;
cfg[z_unit_hit] = z_defender;
cfg[z_damage] = damage;
cfg[z_chance] = attacker.cth_;
cfg["hits"] = hits;
cfg["dies"] = dies;
cfg["unit_hit"] = "defender";
cfg["damage"] = damage;
cfg["chance"] = attacker.cth_;
set_random_results(cfg);
}
else
{
bool results_dies = (*ran_results)[z_dies].to_bool();
bool results_dies = (*ran_results)["dies"].to_bool();
if (results_dies != dies)
{
errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
<< ": the data source says the "
<< (attacker_turn ? z_defender : z_attacker) << ' '
<< (results_dies ? z_perished : z_survived)
<< (attacker_turn ? "defender" : "attacker") << ' '
<< (results_dies ? "perished" : "survived")
<< " while in-game calculations show it "
<< (dies ? z_perished : z_survived)
<< (dies ? "perished" : "survived")
<< " (over-riding game calculations with data source results)\n";
dies = results_dies;
// Set hitpoints to 0 so later checks don't invalidate the death.
@ -1604,7 +1527,7 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
if (hits)
{
try {
fire_event(attacker_turn ? z_attacker_hits : z_defender_hits);
fire_event(attacker_turn ? "attacker_hits" : "defender_hits");
} catch (attack_end_exception) {
refresh_bc();
return false;
@ -1613,7 +1536,7 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
else
{
try {
fire_event(attacker_turn ? z_attacker_misses : z_defender_misses);
fire_event(attacker_turn ? "attacker_misses" : "defender_misses");
} catch (attack_end_exception) {
refresh_bc();
return false;
@ -1633,8 +1556,8 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
game_events::entity_location death_loc(defender.loc_, defender.id_);
game_events::entity_location attacker_loc(attacker.loc_, attacker.id_);
n_token::t_token undead_variation = defender.get_unit().undead_variation();
fire_event(z_attack_end);
std::string undead_variation = defender.get_unit().undead_variation();
fire_event("attack_end");
refresh_bc();
// get weapon info for last_breath and die events
@ -1643,14 +1566,14 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
attacker_stats->weapon->get_cfg() : config();
config d_weapon_cfg = defender_stats->weapon && defender.valid() ?
defender_stats->weapon->get_cfg() : config();
if (a_weapon_cfg[z_name].empty())
a_weapon_cfg[z_name] = z_none;
if (d_weapon_cfg[z_name].empty())
d_weapon_cfg[z_name] = z_none;
dat.add_child(z_first, d_weapon_cfg);
dat.add_child(z_second, a_weapon_cfg);
if (a_weapon_cfg["name"].empty())
a_weapon_cfg["name"] = "none";
if (d_weapon_cfg["name"].empty())
d_weapon_cfg["name"] = "none";
dat.add_child("first", d_weapon_cfg);
dat.add_child("second", a_weapon_cfg);
game_events::fire(z_last_breath, death_loc, attacker_loc, dat);
game_events::fire("last breath", death_loc, attacker_loc, dat);
refresh_bc();
if (!defender.valid() || defender.get_unit().hitpoints() > 0) {
@ -1667,7 +1590,7 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
attacker.loc_, &attacker.get_unit());
}
game_events::fire(z_die, death_loc, attacker_loc, dat);
game_events::fire("die", death_loc, attacker_loc, dat);
refresh_bc();
if (!defender.valid() || defender.get_unit().hitpoints() > 0) {
@ -1691,13 +1614,13 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
newunit.set_attacks(0);
newunit.set_movement(0);
// Apply variation
if (undead_variation != z_null)
if (undead_variation != "null")
{
config mod;
config &variation = mod.add_child(z_effect);
variation[z_apply_to] = z_variation;
variation[z_name] = undead_variation;
newunit.add_modification(z_variation,mod);
config &variation = mod.add_child("effect");
variation["apply_to"] = "variation";
variation["name"] = undead_variation;
newunit.add_modification("variation",mod);
newunit.heal_all();
}
units_.add(death_loc, newunit);
@ -1738,7 +1661,7 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
update_fog = true;
attacker.n_attacks_ = 0;
defender.n_attacks_ = -1; // Petrified.
game_events::fire(z_petrified, defender.loc_, attacker.loc_);
game_events::fire("petrified", defender.loc_, attacker.loc_);
refresh_bc();
}
}
@ -1749,8 +1672,6 @@ bool attack::perform_hit(bool attacker_turn, statistics::attack_context &stats)
void attack::perform()
{
static const config::t_token & z_attack( generate_safe_static_const_t_interned(n_token::t_token("attack")) );
// Stop the user from issuing any commands while the units are fighting
const events::command_disabler disable_commands;
@ -1788,7 +1709,7 @@ void attack::perform()
}
try {
fire_event(z_attack);
fire_event("attack");
} catch (attack_end_exception) {
return;
}
@ -1820,6 +1741,8 @@ void attack::perform()
const int attacker_side = a_.get_unit().side();
const int defender_side = d_.get_unit().side();
static const std::string poison_string("poison");
LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " " << a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit << "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-" << d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)" << (defender_strikes_first ? " defender first-strike" : "") << "\n";
// Play the pre-fight animation
@ -1851,9 +1774,8 @@ void attack::perform()
defender_strikes_first = (d_stats_->firststrike && ! a_stats_->firststrike);
}
static const config::t_token & z_attack_end( generate_safe_static_const_t_interned(n_token::t_token("attack_end")) );
if (a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) {
fire_event(z_attack_end);
fire_event("attack_end");
refresh_bc();
break;
}
@ -1909,7 +1831,7 @@ void attack::perform()
}
int village_owner(const map_location& loc, const t_teams& teams)
int village_owner(const map_location& loc, const std::vector<team>& teams)
{
for(size_t i = 0; i != teams.size(); ++i) {
if(teams[i].owns_village(loc))
@ -1921,7 +1843,7 @@ int village_owner(const map_location& loc, const t_teams& teams)
bool get_village(const map_location& loc, int side, int *action_timebonus)
{
t_teams &teams = *resources::teams;
std::vector<team> &teams = *resources::teams;
team *t = unsigned(side - 1) < teams.size() ? &teams[side - 1] : NULL;
if (t && t->owns_village(loc)) {
return false;
@ -1932,7 +1854,7 @@ bool get_village(const map_location& loc, int side, int *action_timebonus)
// We strip the village off all other sides, unless it is held by an ally
// and we don't have a leader (and thus can't occupy it)
for(t_teams::iterator i = teams.begin(); i != teams.end(); ++i) {
for(std::vector<team>::iterator i = teams.begin(); i != teams.end(); ++i) {
int i_side = i - teams.begin() + 1;
if (!t || has_leader || t->is_enemy(i_side)) {
i->lose_village(loc);
@ -1977,13 +1899,6 @@ struct unit_healing_struct {
void calculate_healing(int side, bool update_display)
{
static const config::t_token & z_unhealable( generate_safe_static_const_t_interned(n_token::t_token("unhealable")) );
static const config::t_token & z_heals( generate_safe_static_const_t_interned(n_token::t_token("heals")) );
static const config::t_token & z_poison( generate_safe_static_const_t_interned(n_token::t_token("poison")) );
static const config::t_token & z_cured( generate_safe_static_const_t_interned(n_token::t_token("cured")) );
static const config::t_token & z_slowed( generate_safe_static_const_t_interned(n_token::t_token("slowed")) );
static const config::t_token & z_regenerate( generate_safe_static_const_t_interned(n_token::t_token("regenerate")) );
DBG_NG << "beginning of healing calculations\n";
unit_map &units = *resources::units;
@ -1992,7 +1907,7 @@ void calculate_healing(int side, bool update_display)
// We look for all allied units, then we see if our healer is near them.
foreach (unit &u, units) {
if (u.get_state(z_unhealable) || u.incapacitated())
if (u.get_state("unhealable") || u.incapacitated())
continue;
DBG_NG << "found healable unit at (" << u.get_location() << ")\n";
@ -2005,7 +1920,7 @@ void calculate_healing(int side, bool update_display)
std::string curing;
unit_ability_list heal = u.get_abilities(z_heals);
unit_ability_list heal = u.get_abilities("heals");
const bool is_poisoned = u.get_state(unit::STATE_POISONED);
if(is_poisoned) {
@ -2025,17 +1940,17 @@ void calculate_healing(int side, bool update_display)
for (std::vector<std::pair<const config *, map_location> >::const_iterator
heal_it = heal.cfgs.begin(); heal_it != heal.cfgs.end(); ++heal_it) {
if((*heal_it->first)[z_poison] == z_cured) {
if((*heal_it->first)["poison"] == "cured") {
curer = units.find(heal_it->second);
// Full curing only occurs on the healer turn (may be changed)
if(curer->side() == side) {
curing = z_cured;
} else if(curing != z_cured) {
curing = z_slowed;
curing = "cured";
} else if(curing != "cured") {
curing = "slowed";
}
} else if(curing != z_cured && (*heal_it->first)[z_poison] == z_slowed) {
} else if(curing != "cured" && (*heal_it->first)["poison"] == "slowed") {
curer = units.find(heal_it->second);
curing = z_slowed;
curing = "slowed";
}
}
}
@ -2066,7 +1981,7 @@ void calculate_healing(int side, bool update_display)
}
if (u.side() == side) {
unit_ability_list regen = u.get_abilities(z_regenerate);
unit_ability_list regen = u.get_abilities("regenerate");
unit_abilities::effect regen_effect(regen,0,false);
if(regen_effect.get_composite_value() > healing) {
healing = regen_effect.get_composite_value();
@ -2074,12 +1989,12 @@ void calculate_healing(int side, bool update_display)
}
if(!regen.cfgs.empty()) {
for (std::vector<std::pair<const config *, map_location> >::const_iterator regen_it = regen.cfgs.begin(); regen_it != regen.cfgs.end(); ++regen_it) {
if((*regen_it->first)[z_poison] == z_cured) {
if((*regen_it->first)["poison"] == "cured") {
curer = units.end();
curing = z_cured;
} else if(curing != z_cured && (*regen_it->first)[z_poison] == z_slowed) {
curing = "cured";
} else if(curing != "cured" && (*regen_it->first)["poison"] == "slowed") {
curer = units.end();
curing = z_slowed;
curing = "slowed";
}
}
}
@ -2089,7 +2004,7 @@ void calculate_healing(int side, bool update_display)
healers.clear();
}
/** @todo FIXME */
curing = z_cured;
curing = "cured";
curer = units.end();
}
if (u.resting() || u.is_healthy()) {
@ -2098,13 +2013,13 @@ void calculate_healing(int side, bool update_display)
}
}
if(is_poisoned) {
if(curing == z_cured) {
if(curing == "cured") {
u.set_state(unit::STATE_POISONED, false);
healing = rest_healing;
healers.clear();
if (curer != units.end())
healers.push_back(&*curer);
} else if(curing == z_slowed) {
} else if(curing == "slowed") {
healing = rest_healing;
healers.clear();
if (curer != units.end())
@ -2118,7 +2033,7 @@ void calculate_healing(int side, bool update_display)
}
}
if (curing == n_token::t_token::z_empty() && healing==0) {
if (curing == "" && healing==0) {
continue;
}
@ -2212,20 +2127,17 @@ unit get_advanced_unit(const unit &u, const std::string& advance_to)
void advance_unit(map_location loc, const std::string &advance_to, const bool &fire_event)
{
static const config::t_token & z_advance( generate_safe_static_const_t_interned(n_token::t_token("advance")) );
static const config::t_token & z_post_advance( generate_safe_static_const_t_interned(n_token::t_token("post_advance")) );
unit_map::unit_iterator u = resources::units->find(loc);
if(!u.valid()) {
return;
}
// original_type is not a reference, since the unit may disappear at any moment.
config::t_token const &original_type = u->type_id();
std::string original_type = u->type_id();
if(fire_event)
{
LOG_NG << "firing advance event at " << loc <<"\n";
game_events::fire(z_advance,loc);
game_events::fire("advance",loc);
if (!u.valid() || u->experience() < u->max_experience() ||
u->type_id() != original_type)
@ -2247,7 +2159,7 @@ void advance_unit(map_location loc, const std::string &advance_to, const bool &f
if(fire_event)
{
LOG_NG << "firing post_advance event at " << loc << "\n";
game_events::fire(z_post_advance,loc);
game_events::fire("post_advance",loc);
}
resources::whiteboard->on_gamestate_change();
@ -2452,17 +2364,6 @@ size_t move_unit(move_unit_spectator *move_spectator,
{
assert(route.empty() == false);
static const config::t_token & z_hides( generate_safe_static_const_t_interned(n_token::t_token("hides")) );
static const config::t_token & z_alert( generate_safe_static_const_t_interned(n_token::t_token("alert")) );
static const config::t_token & z_sighted( generate_safe_static_const_t_interned(n_token::t_token("sighted")) );
static const config::t_token & z_moveto( generate_safe_static_const_t_interned(n_token::t_token("moveto")) );
static const config::t_token & z_friends( generate_safe_static_const_t_interned(n_token::t_token("friends")) );
static const config::t_token & z_enemies( generate_safe_static_const_t_interned(n_token::t_token("enemies")) );
static const config::t_token & z_friendphrase( generate_safe_static_const_t_interned(n_token::t_token("friendphrase")) );
static const config::t_token & z_enemyphrase( generate_safe_static_const_t_interned(n_token::t_token("enemyphrase")) );
static const config::t_token & z_hotkey( generate_safe_static_const_t_interned(n_token::t_token("hotkey")) );
if (route.size() <= 2 && route.front() == route.back()) {
DBG_NG << "Ignore an unit trying to jump on its hex at " << route.front() << "\n";
}
@ -2472,7 +2373,7 @@ size_t move_unit(move_unit_spectator *move_spectator,
gamemap &map = *resources::game_map;
unit_map &units = *resources::units;
t_teams &teams = *resources::teams;
std::vector<team> &teams = *resources::teams;
game_display &disp = *resources::screen;
unit_map::iterator ui = units.find(route.front());
@ -2512,9 +2413,8 @@ size_t move_unit(move_unit_spectator *move_spectator,
std::vector<map_location>::const_iterator step;
std::string ambushed_string;
static const config::t_token & z_skirmisher(generate_safe_static_const_t_interned(n_token::t_token("skirmisher")) );
for(step = route.begin()+1; step != route.end(); ++step) {
const bool skirmisher = ui->get_ability_bool(z_skirmisher,*step);
const bool skirmisher = ui->get_ability_bool("skirmisher",*step);
const t_translation::t_terrain terrain = map[*step];
const int cost = ui->movement_cost(terrain);
@ -2627,12 +2527,12 @@ size_t move_unit(move_unit_spectator *move_spectator,
move_spectator->set_ambusher(it);
}
unit_ability_list hides = it->get_abilities(z_hides);
unit_ability_list hides = it->get_abilities("hides");
std::vector<std::pair<const config *, map_location> >::const_iterator hide_it = hides.cfgs.begin();
// we only use the first valid alert message
for(;hide_it != hides.cfgs.end() && ambushed_string.empty(); ++hide_it) {
ambushed_string = (*hide_it->first)[z_alert].str();
ambushed_string = (*hide_it->first)["alert"].str();
}
}
}
@ -2728,7 +2628,7 @@ size_t move_unit(move_unit_spectator *move_spectator,
if (teams[ui->side() - 1].uses_shroud() || teams[ui->side() - 1].uses_fog())
{
std::set<map_location>::iterator sight_it;
const config::t_token & sighted_str(z_sighted);
const std::string sighted_str("sighted");
// Fire sighted event here
for (sight_it = seen_units.begin();
sight_it != seen_units.end(); ++sight_it)
@ -2743,7 +2643,7 @@ size_t move_unit(move_unit_spectator *move_spectator,
}
}
game_events::raise(z_moveto,steps.back(),steps.front());
game_events::raise("moveto",steps.back(),steps.front());
event_mutated |= game_events::pump();
@ -2822,8 +2722,8 @@ size_t move_unit(move_unit_spectator *move_spectator,
// whether the units sighted were enemies or friends,
// and their respective number.
utils::string_map symbols;
symbols[z_friends] = lexical_cast<std::string>(nfriends);
symbols[z_enemies] = lexical_cast<std::string>(nenemies);
symbols["friends"] = lexical_cast<std::string>(nfriends);
symbols["enemies"] = lexical_cast<std::string>(nenemies);
std::string message;
SDL_Color msg_color;
if(nfriends == 0 || nenemies == 0) {
@ -2836,8 +2736,8 @@ size_t move_unit(move_unit_spectator *move_spectator,
}
}
else {
symbols[z_friendphrase] = vngettext("Part of 'Units sighted! (...)' sentence^1 friendly", "$friends friendly", nfriends, symbols);
symbols[z_enemyphrase] = vngettext("Part of 'Units sighted! (...)' sentence^1 enemy", "$enemies enemy", nenemies, symbols);
symbols["friendphrase"] = vngettext("Part of 'Units sighted! (...)' sentence^1 friendly", "$friends friendly", nfriends, symbols);
symbols["enemyphrase"] = vngettext("Part of 'Units sighted! (...)' sentence^1 enemy", "$enemies enemy", nenemies, symbols);
message = vgettext("Units sighted! ($friendphrase, $enemyphrase)", symbols);
msg_color = font::NORMAL_COLOR;
}
@ -2846,7 +2746,7 @@ size_t move_unit(move_unit_spectator *move_spectator,
// See if the "Continue Move" action has an associated hotkey
const hotkey::hotkey_item& hk = hotkey::get_hotkey(hotkey::HOTKEY_CONTINUE_MOVE);
if(!hk.null()) {
symbols[z_hotkey] = hk.get_name();
symbols["hotkey"] = hk.get_name();
message += "\n" + vgettext("(press $hotkey to keep moving)", symbols);
}
}
@ -2899,7 +2799,6 @@ bool unit_can_move(const unit &u)
void apply_shroud_changes(undo_list &undos, int side)
{
static const config::t_token & z_sighted( generate_safe_static_const_t_interned(n_token::t_token("sighted")) );
team &tm = (*resources::teams)[side - 1];
// No need to do this if the team isn't using fog or shroud.
if (!tm.uses_shroud() && !tm.uses_fog())
@ -2982,7 +2881,7 @@ void apply_shroud_changes(undo_list &undos, int side)
assert(new_unit != units.end());
tm.see(new_unit->side() - 1);
game_events::raise(z_sighted, *sight_it, actual_location);
game_events::raise("sighted", *sight_it, actual_location);
sighted_event = true;
}
for (std::set<map_location>::iterator sight_it = petrified_units.begin();
@ -2992,7 +2891,7 @@ void apply_shroud_changes(undo_list &undos, int side)
assert(new_unit != units.end());
tm.see(new_unit->side() - 1);
game_events::raise(z_sighted, *sight_it, actual_location);
game_events::raise("sighted", *sight_it, actual_location);
sighted_event = true;
}
}
@ -3022,7 +2921,7 @@ void apply_shroud_changes(undo_list &undos, int side)
bool backstab_check(const map_location& attacker_loc,
const map_location& defender_loc,
const unit_map& units, const t_teams& teams)
const unit_map& units, const std::vector<team>& teams)
{
const unit_map::const_iterator defender =
units.find(defender_loc);

View file

@ -158,7 +158,7 @@ struct battle_context_unit_stats
unsigned int swarm_min; /**< Minimum number of blows with swarm (equal to num_blows if swarm isn't used). */
unsigned int swarm_max; /**< Maximum number of blows with swarm (equal to num_blows if swarm isn't used). */
n_token::t_token plague_type; /**< The plague type used by the attack, if any. */
std::string plague_type; /**< The plague type used by the attack, if any. */
battle_context_unit_stats(const unit &u, const map_location& u_loc,
int u_attack_num, bool attacking,

View file

@ -1490,7 +1490,7 @@ void refresh_addon_version_info_cache()
if (!info_cfg) {
continue;
}
std::string const version = info_cfg["version"];
std::string const& version = info_cfg["version"];
LOG_CFG << "caching add-on version info: " << addon << " [" << version << "]\n";
version_info_cache.insert(std::make_pair(addon, version_info(version)));
}

View file

@ -47,7 +47,7 @@ engine_cpp::~engine_cpp()
void engine_cpp::do_parse_aspect_from_config( const config &cfg, const std::string &id, std::back_insert_iterator<std::vector< aspect_ptr > > b )
{
const std::string aspect_factory_key = id+"*"+cfg["name"].str();//@note: hack which combines aspect id and name to get the std::string key of the aspect factory
const std::string aspect_factory_key = id+"*"+cfg["name"];//@note: hack which combines aspect id and name to get the std::string key of the aspect factory
aspect_factory::factory_map::iterator f = aspect_factory::get_list().find(aspect_factory_key);
if (f == aspect_factory::get_list().end()){
ERR_AI_ENGINE_CPP << "side "<<ai_.get_side()<< " : UNKNOWN aspect["<<aspect_factory_key<<"]" << std::endl;

View file

@ -104,7 +104,7 @@ void engine_fai::do_parse_stage_from_config( ai_context &context, const config &
if (!cfg) {
return;
}
const std::string name = cfg["name"];
const std::string &name = cfg["name"];
stage_ptr st_ptr;
//dropped from 1.8, as it's not ready

View file

@ -171,7 +171,7 @@ void target_location_goal::add_targets(std::back_insert_iterator< std::vector< t
if (!filter_ptr_) return;
map_location::t_maploc_set items;
std::set<map_location> items;
filter_ptr_->get_locations(items);
foreach (const map_location &loc, items)
{
@ -250,7 +250,7 @@ void protect_goal::add_targets(std::back_insert_iterator< std::vector< target >
unit_map &units = *resources::units;
map_location::t_maploc_set items;
std::set<map_location> items;
if (protect_unit_) {
foreach (const unit &u, units)
{

View file

@ -94,7 +94,7 @@ void configuration::init(const config &game_config)
foreach (const config &ai_configuration, ais.child_range("ai")) {
const std::string id = ai_configuration["id"];
const std::string &id = ai_configuration["id"];
if (id.empty()){
ERR_AI_CONFIGURATION << "skipped AI config due to missing id" << ". Config contains:"<< std::endl << ai_configuration << std::endl;
@ -119,7 +119,7 @@ void configuration::add_era_ai_from_config(const config &era)
{
era_ai_configurations_.clear();
foreach (const config &ai_configuration, era.child_range("ai")) {
const std::string id = ai_configuration["id"];
const std::string &id = ai_configuration["id"];
if (id.empty()){
ERR_AI_CONFIGURATION << "skipped AI config due to missing id" << ". Config contains:"<< std::endl << ai_configuration << std::endl;

View file

@ -849,7 +849,7 @@ void readonly_context_impl::invalidate_move_maps() const
}
const map_location::t_maploc_set & readonly_context_impl::keeps() const
const std::set<map_location>& readonly_context_impl::keeps() const
{
return keeps_.get();
}
@ -881,7 +881,7 @@ void keeps_cache::init(gamemap &map)
map_ = &map;
}
const map_location::t_maploc_set & keeps_cache::get()
const std::set<map_location>& keeps_cache::get()
{
if(keeps_.empty()) {
// Generate the list of keeps:
@ -933,9 +933,9 @@ bool readonly_context_impl::leader_can_reach_keep() const
const map_location& readonly_context_impl::nearest_keep(const map_location& loc) const
{
map_location::t_maploc_set avoided_locations;
std::set<map_location> avoided_locations;
get_avoid().get_locations(avoided_locations);
const map_location::t_maploc_set & keeps = this->keeps();
const std::set<map_location>& keeps = this->keeps();
if(keeps.empty()) {
static const map_location dummy;
return dummy;
@ -943,7 +943,7 @@ const map_location& readonly_context_impl::nearest_keep(const map_location& loc)
const map_location* res = NULL;
int closest = -1;
for(map_location::t_maploc_set::const_iterator i = keeps.begin(); i != keeps.end(); ++i) {
for(std::set<map_location>::const_iterator i = keeps.begin(); i != keeps.end(); ++i) {
if (avoided_locations.find(*i)!=avoided_locations.end()) {
continue;
}

View file

@ -114,11 +114,11 @@ public:
~keeps_cache();
void handle_generic_event(const std::string& event_name);
void clear();
const map_location::t_maploc_set & get();
const std::set<map_location>& get();
void init(gamemap &map);
private:
gamemap *map_;
map_location::t_maploc_set keeps_;
std::set<map_location> keeps_;
};
// side context
@ -336,7 +336,7 @@ public:
virtual void invalidate_keeps_cache() const= 0;
virtual const map_location::t_maploc_set & keeps() const= 0;
virtual const std::set<map_location>& keeps() const= 0;
virtual bool leader_can_reach_keep() const = 0;
@ -851,7 +851,7 @@ public:
}
virtual const map_location::t_maploc_set& keeps() const
virtual const std::set<map_location>& keeps() const
{
return target_->keeps();
}
@ -1320,7 +1320,7 @@ public:
virtual void invalidate_keeps_cache() const;
virtual const map_location::t_maploc_set & keeps() const;
virtual const std::set<map_location>& keeps() const;
virtual bool leader_can_reach_keep() const;

View file

@ -100,8 +100,7 @@ int idle_ai::get_recursion_count() const
void idle_ai::play_turn()
{
static const config::t_token & z_ai_turn( generate_safe_static_const_t_interned(n_token::t_token("ai turn")) );
game_events::fire(z_ai_turn);
game_events::fire("ai turn");
}
@ -199,7 +198,7 @@ bool ai_default_recruitment_stage::recruit_usage(const std::string& usage)
const unit_type *ut = unit_types.find(name);
if (!ut) continue;
// If usage is empty consider any unit.
if (usage.empty() || ut->usage() == config::t_token(usage)) {
if (usage.empty() || ut->usage() == usage) {
LOG_AI << name << " considered for " << usage << " recruitment\n";
found = true;
@ -220,7 +219,7 @@ bool ai_default_recruitment_stage::recruit_usage(const std::string& usage)
if (imc != maximum_counts_.end()) {
int count_active = 0;
for (unit_map::const_iterator u = resources::units->begin(); u != resources::units->end(); ++u) {
if (u->side() == get_side() && !u->incapacitated() && u->type_id() == config::t_token(name)) {
if (u->side() == get_side() && !u->incapacitated() && u->type_id() == name) {
++count_active;
}
}
@ -358,12 +357,9 @@ int ai_default_recruitment_stage::average_resistance_against(const unit_type& a,
LOG_AI << "average defense of '" << a.id() << "': " << defense << "\n";
int sum = 0, weight_sum = 0;
static const config::t_token & z_chance_to_hit( generate_safe_static_const_t_interned(n_token::t_token("chance_to_hit")) );
static const config::t_token & z_poison( generate_safe_static_const_t_interned(n_token::t_token("poison")) );
static const config::t_token & z_steadfast( generate_safe_static_const_t_interned(n_token::t_token("steadfast")) );
// calculation of the average damage taken
bool steadfast = a.has_ability_by_id(z_steadfast);
bool steadfast = a.has_ability_by_id("steadfast");
bool living = !a.not_living();
const std::vector<attack_type>& attacks = b.attacks();
for (std::vector<attack_type>::const_iterator i = attacks.begin(),
@ -374,10 +370,10 @@ int ai_default_recruitment_stage::average_resistance_against(const unit_type& a,
if (steadfast && resistance < 100)
resistance = std::max<int>(resistance * 2 - 100, 50);
// Do not look for filters or values, simply assume 70% if CTH is customized.
int cth = i->get_special_bool(z_chance_to_hit, true) ? 70 : defense;
int cth = i->get_special_bool("chance_to_hit", true) ? 70 : defense;
int weight = i->damage() * i->num_attacks();
// if cth == 0 the division will do 0/0 so don't execute this part
if (living && cth != 0 && i->get_special_bool(z_poison, true)) {
if (living && cth != 0 && i->get_special_bool("poison", true)) {
// Compute the probability of not poisoning the unit.
int prob = 100;
for (int j = 0; j < i->num_attacks(); ++j)

View file

@ -573,7 +573,7 @@ variant formula_ai::get_value(const std::string& key) const
} else if(key == "avoid")
{
map_location::t_maploc_set av_locs;
std::set<map_location> av_locs;
get_avoid().get_locations(av_locs);
return villages_from_set(av_locs);
@ -926,9 +926,9 @@ void formula_ai::on_create(){
foreach (const config &func, cfg_.child_range("function"))
{
const config::attribute_value &name = func["name"];
const config::attribute_value &inputs = func["inputs"];
const config::attribute_value &formula_str = func["formula"];
const t_string &name = func["name"];
const t_string &inputs = func["inputs"];
const t_string &formula_str = func["formula"];
std::vector<std::string> args = utils::split(inputs);
try {
@ -938,7 +938,7 @@ void formula_ai::on_create(){
args);
}
catch(game_logic::formula_error& e) {
handle_exception(e, "Error while registering function '" + name.str() + "'");
handle_exception(e, "Error while registering function '" + name + "'");
}
}

View file

@ -46,9 +46,9 @@ void candidate_action_manager::load_config(const config& cfg, ai::formula_ai* ai
candidate_action_ptr candidate_action_manager::load_candidate_action_from_config(const config& rc_action, ai::formula_ai* ai, function_symbol_table* function_table)
{
candidate_action_ptr new_ca;
const config::attribute_value &name = rc_action["name"];
const t_string &name = rc_action["name"];
try {
const config::attribute_value &type = rc_action["type"];
const t_string &type = rc_action["type"];
if( type == "movement") {
new_ca = candidate_action_ptr(new move_candidate_action(name, type, rc_action, function_table ));
@ -58,7 +58,7 @@ candidate_action_ptr candidate_action_manager::load_candidate_action_from_config
ERR_AI << "Unknown candidate action type: " << type << "\n";
}
} catch(formula_error& e) {
ai->handle_exception(e, "Error while registering candidate action '" + name.str() + "'");
ai->handle_exception(e, "Error while registering candidate action '" + name + "'");
}
return new_ca;
}

View file

@ -72,7 +72,7 @@ bool stage_unit_formulas::do_play_stage()
} catch(game_logic::formula_error& e) {
if(e.filename == "formula")
e.line = 0;
fai_.handle_exception( e, "Unit priority formula error for unit: '" + (*i->type_id()) + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
fai_.handle_exception( e, "Unit priority formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
priority = 0;
} catch(type_error& e) {
@ -108,7 +108,7 @@ bool stage_unit_formulas::do_play_stage()
if(e.filename == "formula") {
e.line = 0;
}
fai_.handle_exception( e, "Unit formula error for unit: '" +(* i->type_id() ) + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
fai_.handle_exception( e, "Unit formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
}
}
}
@ -132,7 +132,7 @@ bool stage_unit_formulas::do_play_stage()
if (e.filename == "formula") {
e.line = 0;
}
fai_.handle_exception( e, "Unit loop formula error for unit: '" +(* i->type_id()) + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
fai_.handle_exception( e, "Unit loop formula error for unit: '" + i->type_id() + "' standing at (" + str_cast(i->get_location().x + 1) + "," + str_cast(i->get_location().y + 1) + ")");
}
}
}

View file

@ -337,14 +337,14 @@ static int cfun_ai_get_attack_depth(lua_State *L)
static int cfun_ai_get_avoid(lua_State *L)
{
map_location::t_maploc_set locs;
std::set<map_location> locs;
terrain_filter avoid = get_readonly_context(L).get_avoid();
avoid.get_locations(locs, true); // is it true here?
int sz = locs.size();
lua_createtable(L, sz, 0); // create a table that we'll use as an array
map_location::t_maploc_set::iterator it = locs.begin();
std::set<map_location>::iterator it = locs.begin();
for (int i = 0; it != locs.end(); ++it, ++i)
{
lua_pushinteger(L, i + 1); // Index for the map location

View file

@ -164,7 +164,7 @@ void holder::modify_ai(const config &cfg)
// if not initialized, initialize now.
get_ai_ref();
}
const std::string act = cfg["action"];
const std::string &act = cfg["action"];
LOG_AI_MOD << "side "<< side_ << " [modify_ai] "<<act<<" \""<<cfg["path"]<<"\""<<std::endl;
DBG_AI_MOD << std::endl << cfg << std::endl;
DBG_AI_MOD << "side "<< side_ << " before [modify_ai]"<<std::endl << to_config() << std::endl;
@ -226,7 +226,7 @@ const std::string holder::describe_ai()
if (this->ai_!=NULL) {
return this->ai_->describe_self()+std::string(" for side ")+sidestr+std::string(" : ");
} else {
return std::string("not initialized ai with id=[")+cfg_["id"].str()+std::string("] for side ")+sidestr+std::string(" : ");
return std::string("not initialized ai with id=[")+cfg_["id"]+std::string("] for side ")+sidestr+std::string(" : ");
}
}
@ -734,8 +734,7 @@ void manager::play_turn( side_number side ){
/*hack. @todo 1.9 rework via extended event system*/
get_ai_info().recent_attacks.clear();
interface& ai_obj = get_active_ai_for_side(side);
static const config::t_token & z_ai_turn( generate_safe_static_const_t_interned(n_token::t_token("ai turn")) );
game_events::fire(z_ai_turn);
game_events::fire("ai turn");
raise_turn_started();
ai_obj.new_turn();
ai_obj.play_turn();

View file

@ -40,7 +40,6 @@ static lg::log_domain log_ai_testing_aspect_attacks("ai/aspect/attacks");
#define LOG_AI LOG_STREAM(info, log_ai_testing_aspect_attacks)
#define ERR_AI LOG_STREAM(err, log_ai_testing_aspect_attacks)
aspect_attacks::aspect_attacks(readonly_context &context, const config &cfg, const std::string &id)
: typesafe_aspect<attacks_vector>(context,cfg,id)
, filter_own_()
@ -157,10 +156,6 @@ void aspect_attacks::do_attack_analysis(
unit_map::iterator unit_itor = units_.find(current_unit);
assert(unit_itor != units_.end());
static const config::t_token & z_backstab( generate_safe_static_const_t_interned(n_token::t_token("backstab")) );
static const config::t_token & z_slow( generate_safe_static_const_t_interned(n_token::t_token("slow")) );
static const config::t_token & z_value( generate_safe_static_const_t_interned(n_token::t_token("value")) );
// See if the unit has the backstab ability.
// Units with backstab will want to try to have a
// friendly unit opposite the position they move to.
@ -170,11 +165,11 @@ void aspect_attacks::do_attack_analysis(
std::vector<attack_type>& attacks = unit_itor->attacks();
for(std::vector<attack_type>::iterator a = attacks.begin(); a != attacks.end(); ++a) {
a->set_specials_context(map_location(), map_location(), units_, true, NULL);
if(a->get_special_bool(z_backstab)) {
if(a->get_special_bool("backstab")) {
backstab = true;
}
if(a->get_special_bool(z_slow)) {
if(a->get_special_bool("slow")) {
slow = true;
}
}
@ -260,7 +255,7 @@ void aspect_attacks::do_attack_analysis(
}
unit_ability_list abil = unit_itor->get_abilities("leadership",tiles[j]);
int best_leadership_bonus = abil.highest(z_value).first;
int best_leadership_bonus = abil.highest("value").first;
double leadership_bonus = static_cast<double>(best_leadership_bonus+100)/100.0;
if (leadership_bonus > 1.1) {
LOG_AI << unit_itor->name() << " is getting leadership " << leadership_bonus << "\n";

View file

@ -311,7 +311,7 @@ bool recruitment_phase::recruit_usage(const std::string& usage)
const unit_type *ut = unit_types.find(name);
if (!ut) continue;
// If usage is empty consider any unit.
if (usage.empty() || ut->usage() == config::t_token(usage)) { ///todo remove when upgrade to t_token
if (usage.empty() || ut->usage() == usage) {
LOG_AI_TESTING_AI_DEFAULT << name << " considered for " << usage << " recruitment\n";
found = true;
@ -402,12 +402,8 @@ int recruitment_phase::average_resistance_against(const unit_type& a, const unit
int sum = 0, weight_sum = 0;
static const config::t_token & z_chance_to_hit( generate_safe_static_const_t_interned(n_token::t_token("chance_to_hit")) );
static const config::t_token & z_poison( generate_safe_static_const_t_interned(n_token::t_token("poison")) );
static const config::t_token & z_steadfast( generate_safe_static_const_t_interned(n_token::t_token("steadfast")) );
// calculation of the average damage taken
bool steadfast = a.has_ability_by_id(z_steadfast);
bool steadfast = a.has_ability_by_id("steadfast");
bool living = !a.not_living();
const std::vector<attack_type>& attacks = b.attacks();
for (std::vector<attack_type>::const_iterator i = attacks.begin(),
@ -418,10 +414,10 @@ int recruitment_phase::average_resistance_against(const unit_type& a, const unit
if (steadfast && resistance < 100)
resistance = std::max<int>(resistance * 2 - 100, 50);
// Do not look for filters or values, simply assume 70% if CTH is customized.
int cth = i->get_special_bool(z_chance_to_hit, true) ? 70 : defense;
int cth = i->get_special_bool("chance_to_hit", true) ? 70 : defense;
int weight = i->damage() * i->num_attacks();
// if cth == 0 the division will do 0/0 so don't execute this part
if (living && cth != 0 && i->get_special_bool(z_poison, true)) {
if (living && cth != 0 && i->get_special_bool("poison", true)) {
// Compute the probability of not poisoning the unit.
int prob = 100;
for (int j = 0; j < i->num_attacks(); ++j)
@ -486,7 +482,7 @@ void recruitment_phase::analyze_potential_recruit_combat()
unit const &un = *j;
const unit_type *enemy_info = unit_types.find(un.type_id());
VALIDATE(enemy_info, "Unknown unit type : " + (*un.type_id()) + " while scoring units.");
VALIDATE(enemy_info, "Unknown unit type : " + un.type_id() + " while scoring units.");
int weight = un.cost() * un.hitpoints() / un.max_hitpoints();
weighting += weight;
@ -1032,10 +1028,8 @@ void get_villages_phase::find_villages(
vulnerability.insert(std::pair<map_location,double>(current_loc,threat));
}
static const config::t_token & z_guardian( generate_safe_static_const_t_interned(n_token::t_token("guardian")) );
const unit_map::const_iterator u = resources::units->find(j->second);
if (u == resources::units->end() || u->get_state(z_guardian)) {
if (u == resources::units->end() || u->get_state("guardian")) {
continue;
}

View file

@ -32,7 +32,6 @@
#include <deque>
namespace ai {
namespace testing_ai_default {
@ -292,10 +291,8 @@ std::pair<map_location,map_location> testing_move_to_targets_phase::choose_move(
return std::pair<map_location,map_location>();
}
static const config::t_token & z_guardian( generate_safe_static_const_t_interned(n_token::t_token("guardian")) );
//guardian units stay put
if (u->get_state(z_guardian)) {
if (u->get_state("guardian")) {
LOG_AI << u->type_id() << " is guardian, staying still\n";
return std::make_pair(u->get_location(), u->get_location());
}
@ -389,7 +386,7 @@ std::pair<map_location,map_location> testing_move_to_targets_phase::choose_move(
//now see if any other unit can put a better bid forward
for(++u; u != units_.end(); ++u) {
if (u->side() != get_side() || u->can_recruit() ||
u->movement_left() <= 0 || u->get_state(z_guardian) ||
u->movement_left() <= 0 || u->get_state("guardian") ||
u->incapacitated())
{
continue;

View file

@ -42,7 +42,6 @@
#include <map>
namespace ai {
namespace testing_ai_default {
@ -208,7 +207,7 @@ class fake_team
{
int counter = 0;
foreach(unit &un, *resources::units){
if(un.side() == side() && un.type_id() == config::t_token(name)) // @todo: is type_id good? and upgrade std:string to t_token
if(un.side() == side() && un.type_id() == name) // @todo: is type_id good?
{
counter++;
}
@ -285,14 +284,11 @@ static int average_resistance_against(const unit_type& a, const unit_type& b)
}
//LOG_AI << "average defense of '" << a.id() << "': " << defense << "\n";
static const config::t_token & z_chance_to_hit( generate_safe_static_const_t_interned(n_token::t_token("chance_to_hit")) );
static const config::t_token & z_poison( generate_safe_static_const_t_interned(n_token::t_token("poison")) );
static const config::t_token & z_steadfast( generate_safe_static_const_t_interned(n_token::t_token("steadfast")) );
int sum = 0, weight_sum = 0;
// calculation of the average damage taken
bool steadfast = a.has_ability_by_id(z_steadfast);
bool steadfast = a.has_ability_by_id("steadfast");
bool living = !a.not_living();
const std::vector<attack_type>& attacks = b.attacks();
for (std::vector<attack_type>::const_iterator i = attacks.begin(),
@ -303,10 +299,10 @@ static int average_resistance_against(const unit_type& a, const unit_type& b)
if (steadfast && resistance < 100)
resistance = std::max<int>(resistance * 2 - 100, 50);
// Do not look for filters or values, simply assume 70% if CTH is customized.
int cth = i->get_special_bool(z_chance_to_hit, true) ? 70 : defense;
int cth = i->get_special_bool("chance_to_hit", true) ? 70 : defense;
int weight = i->damage() * i->num_attacks();
// if cth == 0 the division will do 0/0 so don't execute this part
if (living && cth != 0 && i->get_special_bool(z_poison, true)) {
if (living && cth != 0 && i->get_special_bool("poison", true)) {
// Compute the probability of not poisoning the unit.
int prob = 100;
for (int j = 0; j < i->num_attacks(); ++j)

View file

@ -148,8 +148,6 @@ void battle_prediction_pane::get_unit_strings(const battle_context_unit_stats& s
std::stringstream str;
char str_buf[10];
static const config::t_token & z_damage( generate_safe_static_const_t_interned(n_token::t_token("damage")) );
// With a weapon.
if(stats.weapon != NULL) {
@ -158,7 +156,7 @@ void battle_prediction_pane::get_unit_strings(const battle_context_unit_stats& s
weapon->set_specials_context(u_loc, opp_loc, *resources::units, stats.is_attacker, opp_weapon);
// Get damage modifiers.
unit_ability_list dmg_specials = weapon->get_specials(z_damage);
unit_ability_list dmg_specials = weapon->get_specials("damage");
unit_abilities::effect dmg_effect(dmg_specials, weapon->damage(), stats.backstab_pos);
// Get the SET damage modifier, if any.
@ -239,7 +237,7 @@ void battle_prediction_pane::get_unit_strings(const battle_context_unit_stats& s
else str << _("Attacker");
if(resistance_modifier < 100) str << _(" resistance vs ");
else str << _(" vulnerability vs ");
str << string_table["type_" + (*weapon->type() )];
str << string_table["type_" + weapon->type()];
left_strings.push_back(str.str());
str.str("");
str << "* " << (resistance_modifier / 100) << "." << ((resistance_modifier % 100) / 10);

View file

@ -34,7 +34,6 @@ static lg::log_domain log_engine("engine");
terrain_builder::building_ruleset terrain_builder::building_rules_;
const config* terrain_builder::rules_cfg_ = NULL;
terrain_builder::rule_image::rule_image(int layer, int x, int y, bool global_image, int cx, int cy) :
layer(layer),
basex(x),
@ -50,14 +49,11 @@ terrain_builder::tile::tile() :
images(),
images_foreground(),
images_background(),
last_tod(),
last_tod("invalid_tod"),
sorted_images(false)
{
static const n_token::t_token & z_invalid_tod( generate_safe_static_const_t_interned(n_token::t_token("invalid_tod")) );
last_tod = z_invalid_tod;
}
{}
void terrain_builder::tile::rebuild_cache(const n_token::t_token& tod, logs* log)
void terrain_builder::tile::rebuild_cache(const std::string& tod, logs* log)
{
images_background.clear();
images_foreground.clear();
@ -96,13 +92,12 @@ void terrain_builder::tile::rebuild_cache(const n_token::t_token& tod, logs* log
void terrain_builder::tile::clear()
{
static const config::t_token & z_invalid_tod( generate_safe_static_const_t_interned(n_token::t_token("invalid_tod")) );
flags.clear();
images.clear();
sorted_images = false;
images_foreground.clear();
images_background.clear();
last_tod = z_invalid_tod;
last_tod = "invalid_tod";
}
static unsigned int get_noise(const map_location& loc, unsigned int index){
@ -153,13 +148,12 @@ const terrain_builder::tile& terrain_builder::tilemap::operator[] (const map_loc
}
terrain_builder::terrain_builder(const config& level,
const gamemap* m, const n_token::t_token& offmap_image) :
const gamemap* m, const std::string& offmap_image) :
map_(m),
tile_map_(map().w(), map().h()),
terrain_by_type_()
{
static const config::t_token & z_cterrain( generate_safe_static_const_t_interned(n_token::t_token("terrain/")) );
image::precache_file_existence(z_cterrain);
image::precache_file_existence("terrain/");
if(building_rules_.empty() && rules_cfg_){
//off_map first to prevent some default rule seems to block it
@ -211,7 +205,7 @@ void terrain_builder::change_map(const gamemap* m)
}
const terrain_builder::imagelist *terrain_builder::get_terrain_at(const map_location &loc,
const n_token::t_token &tod, const TERRAIN_TYPE terrain_type)
const std::string &tod, const TERRAIN_TYPE terrain_type)
{
if(!tile_map_.on_map(loc))
return NULL;
@ -290,9 +284,9 @@ void terrain_builder::rebuild_all()
build_terrains();
}
static bool image_exists(const n_token::t_token& name)
static bool image_exists(const std::string& name)
{
bool precached = (*name).find("..") == std::string::npos;
bool precached = name.find("..") == std::string::npos;
if(precached && image::precached_file_exists(name)) {
return true;
@ -303,29 +297,28 @@ static bool image_exists(const n_token::t_token& name)
return false;
}
static std::vector<n_token::t_token> get_variations(const n_token::t_token& base, const n_token::t_token& variations)
static std::vector<std::string> get_variations(const std::string& base, const std::string& variations)
{
/** @todo optimize this function */
std::vector<n_token::t_token> res;
std::vector<std::string> res;
if(variations.empty()){
res.push_back(base);
return res;
}
std::string::size_type pos = (*base).find("@V", 0);
std::string::size_type pos = base.find("@V", 0);
if(pos == std::string::npos) {
res.push_back(base);
return res;
}
std::vector<n_token::t_token> vars = utils::split_token(variations, ';', 0);
std::vector<std::string> vars = utils::split(variations, ';', 0);
foreach(const n_token::t_token& v, vars){
foreach(const std::string& v, vars){
res.push_back(base);
std::string::size_type pos = 0;
std::string cbase(*base);
while ((pos = cbase.find("@V", pos)) != std::string::npos) {
cbase.replace(pos, 2, (*v));
pos += (*v).size();
while ((pos = res.back().find("@V", pos)) != std::string::npos) {
res.back().replace(pos, 2, v);
pos += v.size();
}
res.push_back(n_token::t_token(cbase));
}
return res;
}
@ -345,27 +338,27 @@ bool terrain_builder::load_images(building_rule &rule)
foreach(rule_image_variant& variant, ri.variants)
{
std::vector<n_token::t_token> var_strings = get_variations(variant.image_string, variant.variations);
foreach(const n_token::t_token& var, var_strings)
std::vector<std::string> var_strings = get_variations(variant.image_string, variant.variations);
foreach(const std::string& var, var_strings)
{
/** @todo improve this, 99% of terrains are not animated. */
std::vector<n_token::t_token> frames = utils::parenthetical_split_token(var,',');
std::vector<std::string> frames = utils::parenthetical_split(var,',');
animated<image::locator> res;
foreach(const n_token::t_token& frame, frames)
foreach(const std::string& frame, frames)
{
const std::vector<n_token::t_token> items = utils::split_token(frame, ':');
const n_token::t_token& str = items.front();
const std::vector<std::string> items = utils::split(frame, ':');
const std::string& str = items.front();
const size_t tilde = (*str).find('~');
const size_t tilde = str.find('~');
bool has_tilde = tilde != std::string::npos;
const n_token::t_token filename = n_token::t_token("terrain/" + (has_tilde ? (*str).substr(0,tilde) : str));
const std::string filename = "terrain/" + (has_tilde ? str.substr(0,tilde) : str);
if(!image_exists(filename)){
continue; // ignore missing frames
}
const n_token::t_token modif = (has_tilde ? n_token::t_token((*str).substr(tilde+1)) : n_token::t_token::z_empty());
const std::string modif = (has_tilde ? str.substr(tilde+1) : "");
int time = 100;
if(items.size() > 1) {
@ -474,25 +467,23 @@ void terrain_builder::rotate(terrain_constraint &ret, int angle)
}
}
void terrain_builder::replace_rotate_tokens(n_token::t_token &s, int angle,
const std::vector<n_token::t_token> &replacement)
void terrain_builder::replace_rotate_tokens(std::string &s, int angle,
const std::vector<std::string> &replacement)
{
std::string::size_type pos = 0;
std::string scopy(*s);
while ((pos = scopy.find("@R", pos)) != std::string::npos) {
if (pos + 2 >= scopy.size()) { s = n_token::t_token(scopy); return; }
unsigned i = scopy[pos + 2] - '0' + angle;
while ((pos = s.find("@R", pos)) != std::string::npos) {
if (pos + 2 >= s.size()) return;
unsigned i = s[pos + 2] - '0' + angle;
if (i >= 6) i -= 6;
if (i >= 6) { pos += 2; continue; }
const n_token::t_token &r = replacement[i];
scopy.replace(pos, 3, r);
pos += r->size();
const std::string &r = replacement[i];
s.replace(pos, 3, r);
pos += r.size();
}
s = n_token::t_token(scopy);
}
void terrain_builder::replace_rotate_tokens(rule_image &image, int angle,
const std::vector<n_token::t_token> &replacement)
const std::vector<std::string> &replacement)
{
foreach(rule_image_variant& variant, image.variants) {
replace_rotate_tokens(variant, angle, replacement);
@ -500,7 +491,7 @@ void terrain_builder::replace_rotate_tokens(rule_image &image, int angle,
}
void terrain_builder::replace_rotate_tokens(rule_imagelist &list, int angle,
const std::vector<n_token::t_token> &replacement)
const std::vector<std::string> &replacement)
{
foreach (rule_image &img, list) {
replace_rotate_tokens(img, angle, replacement);
@ -508,18 +499,18 @@ void terrain_builder::replace_rotate_tokens(rule_imagelist &list, int angle,
}
void terrain_builder::replace_rotate_tokens(building_rule &rule, int angle,
const std::vector<n_token::t_token> &replacement)
const std::vector<std::string> &replacement)
{
foreach (terrain_constraint &cons, rule.constraints)
{
// Transforms attributes
foreach (n_token::t_token &flag, cons.set_flag) {
foreach (std::string &flag, cons.set_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
foreach (n_token::t_token &flag, cons.no_flag) {
foreach (std::string &flag, cons.no_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
foreach (n_token::t_token &flag, cons.has_flag) {
foreach (std::string &flag, cons.has_flag) {
replace_rotate_tokens(flag, angle, replacement);
}
replace_rotate_tokens(cons.images, angle, replacement);
@ -529,7 +520,7 @@ void terrain_builder::replace_rotate_tokens(building_rule &rule, int angle,
}
void terrain_builder::rotate_rule(building_rule &ret, int angle,
const std::vector<n_token::t_token> &rot)
const std::vector<std::string> &rot)
{
if (rot.size() != 6) {
ERR_NG << "invalid rotations\n";
@ -561,7 +552,7 @@ void terrain_builder::rotate_rule(building_rule &ret, int angle,
replace_rotate_tokens(ret, angle, rot);
}
terrain_builder::rule_image_variant::rule_image_variant(const n_token::t_token &image_string, const n_token::t_token& variations, const n_token::t_token& tod, bool random_start) :
terrain_builder::rule_image_variant::rule_image_variant(const std::string &image_string, const std::string& variations, const std::string& tod, bool random_start) :
image_string(image_string),
variations(variations),
images(),
@ -569,30 +560,20 @@ terrain_builder::rule_image_variant::rule_image_variant(const n_token::t_token &
random_start(random_start)
{
if(!tod.empty()) {
const std::vector<n_token::t_token> tod_list = utils::split_token(tod);
const std::vector<std::string> tod_list = utils::split(tod);
tods.insert(tod_list.begin(), tod_list.end());
}
}
void terrain_builder::add_images_from_config(rule_imagelist& images, const config &cfg, bool global, int dx, int dy)
{
static const config::t_token & z_image( generate_safe_static_const_t_interned(n_token::t_token("image")) );
static const config::t_token & z_layer( generate_safe_static_const_t_interned(n_token::t_token("layer")) );
static const config::t_token & z_base( generate_safe_static_const_t_interned(n_token::t_token("base")) );
static const config::t_token & z_center( generate_safe_static_const_t_interned(n_token::t_token("center")) );
static const config::t_token & z_variant( generate_safe_static_const_t_interned(n_token::t_token("variant")) );
static const config::t_token & z_name( generate_safe_static_const_t_interned(n_token::t_token("name")) );
static const config::t_token & z_variations( generate_safe_static_const_t_interned(n_token::t_token("variations")) );
static const config::t_token & z_tod( generate_safe_static_const_t_interned(n_token::t_token("tod")) );
static const config::t_token & z_random_start( generate_safe_static_const_t_interned(n_token::t_token("random_start")) );
foreach (const config &img, cfg.child_range(z_image))
foreach (const config &img, cfg.child_range("image"))
{
int layer = img[z_layer];
int layer = img["layer"];
int basex = TILEWIDTH / 2 + dx, basey = TILEWIDTH / 2 + dy;
if (const config::attribute_value *base_ = img.get(z_base)) {
std::vector<n_token::t_token> base = utils::split_attr(*base_);
if (const config::attribute_value *base_ = img.get("base")) {
std::vector<std::string> base = utils::split(*base_);
if(base.size() >= 2) {
basex = atoi(base[0].c_str());
basey = atoi(base[1].c_str());
@ -600,8 +581,8 @@ void terrain_builder::add_images_from_config(rule_imagelist& images, const confi
}
int center_x = -1, center_y = -1;
if (const config::attribute_value *center_ = img.get(z_center)) {
std::vector<n_token::t_token> center = utils::split_attr(*center_);
if (const config::attribute_value *center_ = img.get("center")) {
std::vector<std::string> center = utils::split(*center_);
if(center.size() >= 2) {
center_x = atoi(center[0].c_str());
center_y = atoi(center[1].c_str());
@ -611,22 +592,22 @@ void terrain_builder::add_images_from_config(rule_imagelist& images, const confi
images.push_back(rule_image(layer, basex - dx, basey - dy, global, center_x, center_y));
// Adds the other variants of the image
foreach (const config &variant, img.child_range(z_variant))
foreach (const config &variant, img.child_range("variant"))
{
const config::attribute_value &name = variant[z_name];
const config::attribute_value &variations = img[z_variations];
const config::attribute_value &tod = variant[z_tod];
bool random_start = variant[z_random_start].to_bool(true);
const std::string &name = variant["name"];
const std::string &variations = img["variations"];
const std::string &tod = variant["tod"];
bool random_start = variant["random_start"].to_bool(true);
images.back().variants.push_back(rule_image_variant(name.token(), variations.token(), tod.token(), random_start));
images.back().variants.push_back(rule_image_variant(name, variations, tod, random_start));
}
// Adds the main (default) variant of the image at the end,
// (will be used only if previous variants don't match)
const config::attribute_value &name = img[z_name];
const config::attribute_value &variations = img[z_variations];
bool random_start = img[z_random_start].to_bool(true);
images.back().variants.push_back(rule_image_variant(name.token(), variations.token(), random_start));
const std::string &name = img["name"];
const std::string &variations = img["variations"];
bool random_start = img["random_start"].to_bool(true);
images.back().variants.push_back(rule_image_variant(name, variations, random_start));
}
}
@ -664,29 +645,23 @@ void terrain_builder::add_constraints(terrain_builder::constraint_set &constrain
const map_location& loc, const config& cfg, const config& global_images)
{
static const config::t_token & z_type( generate_safe_static_const_t_interned(n_token::t_token("type")) );
static const config::t_token & z_set_flag( generate_safe_static_const_t_interned(n_token::t_token("set_flag")) );
static const config::t_token & z_has_flag( generate_safe_static_const_t_interned(n_token::t_token("has_flag")) );
static const config::t_token & z_no_flag( generate_safe_static_const_t_interned(n_token::t_token("no_flag")) );
static const config::t_token & z_set_no_flag( generate_safe_static_const_t_interned(n_token::t_token("set_no_flag")) );
terrain_constraint& constraint = add_constraints(constraints, loc,
t_translation::t_match(cfg[z_type], t_translation::WILDCARD), global_images);
t_translation::t_match(cfg["type"], t_translation::WILDCARD), global_images);
std::vector<n_token::t_token> item_string = utils::split_attr(cfg[z_set_flag]);
std::vector<std::string> item_string = utils::split(cfg["set_flag"]);
constraint.set_flag.insert(constraint.set_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::split_attr(cfg[z_has_flag]);
item_string = utils::split(cfg["has_flag"]);
constraint.has_flag.insert(constraint.has_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::split_attr(cfg[z_no_flag]);
item_string = utils::split(cfg["no_flag"]);
constraint.no_flag.insert(constraint.no_flag.end(),
item_string.begin(), item_string.end());
item_string = utils::split_attr(cfg[z_set_no_flag]);
item_string = utils::split(cfg["set_no_flag"]);
constraint.set_flag.insert(constraint.set_flag.end(),
item_string.begin(), item_string.end());
constraint.no_flag.insert(constraint.no_flag.end(),
@ -696,7 +671,7 @@ void terrain_builder::add_constraints(terrain_builder::constraint_set &constrain
add_images_from_config(constraint.images, cfg, false);
}
void terrain_builder::parse_mapstring(const n_token::t_token &mapstring,
void terrain_builder::parse_mapstring(const std::string &mapstring,
struct building_rule &br, anchormap& anchors,
const config& global_images)
{
@ -751,14 +726,14 @@ void terrain_builder::add_rule(building_ruleset &rules, building_rule &rule)
}
void terrain_builder::add_rotated_rules(building_ruleset &rules, building_rule &tpl,
const n_token::t_token &rotations)
const std::string &rotations)
{
if(rotations.empty()) {
// Adds the parsed built terrain to the list
add_rule(rules, tpl);
} else {
const std::vector<n_token::t_token>& rot = utils::split_token(rotations, ',');
const std::vector<std::string>& rot = utils::split(rotations, ',');
for(size_t angle = 0; angle < rot.size(); ++angle) {
/* Only 5% of the rules have valid images, so most of
@ -777,24 +752,10 @@ void terrain_builder::add_rotated_rules(building_ruleset &rules, building_rule &
void terrain_builder::parse_config(const config &cfg, bool local)
{
static const config::t_token & z_terrain_graphics( generate_safe_static_const_t_interned(n_token::t_token("terrain_graphics")) );
static const config::t_token & z_x( generate_safe_static_const_t_interned(n_token::t_token("x")) );
static const config::t_token & z_y( generate_safe_static_const_t_interned(n_token::t_token("y")) );
static const config::t_token & z_probability( generate_safe_static_const_t_interned(n_token::t_token("probability")) );
static const config::t_token & z_map( generate_safe_static_const_t_interned(n_token::t_token("map")) );
static const config::t_token & z_tile( generate_safe_static_const_t_interned(n_token::t_token("tile")) );
static const config::t_token & z_loc( generate_safe_static_const_t_interned(n_token::t_token("loc")) );
static const config::t_token & z_pos( generate_safe_static_const_t_interned(n_token::t_token("pos")) );
static const config::t_token & z_set_flag( generate_safe_static_const_t_interned(n_token::t_token("set_flag")) );
static const config::t_token & z_no_flag( generate_safe_static_const_t_interned(n_token::t_token("no_flag")) );
static const config::t_token & z_has_flag( generate_safe_static_const_t_interned(n_token::t_token("has_flag")) );
static const config::t_token & z_set_no_flag( generate_safe_static_const_t_interned(n_token::t_token("set_no_flag")) );
static const config::t_token & z_rotations( generate_safe_static_const_t_interned(n_token::t_token("rotations")) );
static const config::t_token & z_precedence( generate_safe_static_const_t_interned(n_token::t_token("precedence")) );
log_scope("terrain_builder::parse_config");
// Parses the list of building rules (BRs)
foreach (const config &br, cfg.child_range(z_terrain_graphics))
foreach (const config &br, cfg.child_range("terrain_graphics"))
{
building_rule pbr; // Parsed Building rule
pbr.local = local;
@ -802,30 +763,30 @@ void terrain_builder::parse_config(const config &cfg, bool local)
// add_images_from_config(pbr.images, **br);
pbr.location_constraints =
map_location(br[z_x].to_int() - 1, br[z_y].to_int() - 1);
map_location(br["x"].to_int() - 1, br["y"].to_int() - 1);
pbr.probability = br[z_probability].to_int(100);
pbr.probability = br["probability"].to_int(100);
// Mapping anchor indices to anchor locations.
anchormap anchors;
// Parse the map= , if there is one (and fill the anchors list)
parse_mapstring(br[z_map].token(), pbr, anchors, br);
parse_mapstring(br["map"], pbr, anchors, br);
// Parses the terrain constraints (TCs)
foreach (const config &tc, br.child_range(z_tile))
foreach (const config &tc, br.child_range("tile"))
{
// Adds the terrain constraint to the current built terrain's list
// of terrain constraints, if it does not exist.
map_location loc;
if (const config::attribute_value *v = tc.get(z_x)) {
if (const config::attribute_value *v = tc.get("x")) {
loc.x = *v;
}
if (const config::attribute_value *v = tc.get(z_y)) {
if (const config::attribute_value *v = tc.get("y")) {
loc.y = *v;
}
if (const config::attribute_value *v = tc.get(z_loc)) {
std::vector<n_token::t_token> sloc = utils::split_attr(*v);
if (const config::attribute_value *v = tc.get("loc")) {
std::vector<std::string> sloc = utils::split(*v);
if(sloc.size() == 2) {
loc.x = atoi(sloc[0].c_str());
loc.y = atoi(sloc[1].c_str());
@ -834,7 +795,7 @@ void terrain_builder::parse_config(const config &cfg, bool local)
if(loc.valid()) {
add_constraints(pbr.constraints, loc, tc, br);
}
if (const config::attribute_value *v = tc.get(z_pos)) {
if (const config::attribute_value *v = tc.get("pos")) {
int pos = *v;
if(anchors.find(pos) == anchors.end()) {
WRN_NG << "Invalid anchor!\n";
@ -851,10 +812,10 @@ void terrain_builder::parse_config(const config &cfg, bool local)
}
}
const std::vector<n_token::t_token> global_set_flag = utils::split_attr(br[z_set_flag]);
const std::vector<n_token::t_token> global_no_flag = utils::split_attr(br[z_no_flag]);
const std::vector<n_token::t_token> global_has_flag = utils::split_attr(br[z_has_flag]);
const std::vector<n_token::t_token> global_set_no_flag = utils::split_attr(br[z_set_no_flag]);
const std::vector<std::string> global_set_flag = utils::split(br["set_flag"]);
const std::vector<std::string> global_no_flag = utils::split(br["no_flag"]);
const std::vector<std::string> global_has_flag = utils::split(br["has_flag"]);
const std::vector<std::string> global_set_no_flag = utils::split(br["set_no_flag"]);
foreach (terrain_constraint &constraint, pbr.constraints)
{
@ -871,11 +832,11 @@ void terrain_builder::parse_config(const config &cfg, bool local)
}
// Handles rotations
const config::attribute_value &rotations = br[z_rotations];
const std::string &rotations = br["rotations"];
pbr.precedence = br[z_precedence];
pbr.precedence = br["precedence"];
add_rotated_rules(building_rules_, pbr, rotations.token());
add_rotated_rules(building_rules_, pbr, rotations);
loadscreen::increment_progress();
}
@ -896,7 +857,7 @@ void terrain_builder::parse_config(const config &cfg, bool local)
std::cerr << ">>>> New constraint: location = (" << constraint->second.loc
<< "), terrain types = '" << t_translation::write_list(constraint->second.terrain_types_match.terrain) << "'\n";
std::vector<n_token::t_token>::const_iterator flag;
std::vector<std::string>::const_iterator flag;
for(flag = constraint->second.set_flag.begin(); flag != constraint->second.set_flag.end(); ++flag) {
std::cerr << ">>>>>> Set_flag: " << *flag << "\n";
@ -912,37 +873,25 @@ void terrain_builder::parse_config(const config &cfg, bool local)
}
void terrain_builder::add_off_map_rule(const n_token::t_token& image)
void terrain_builder::add_off_map_rule(const std::string& image)
{
static const config::t_token & z_terrain_graphics( generate_safe_static_const_t_interned(n_token::t_token("terrain_graphics")) );
static const config::t_token & z_tile( generate_safe_static_const_t_interned(n_token::t_token("tile")) );
static const config::t_token & z_x( generate_safe_static_const_t_interned(n_token::t_token("x")) );
static const config::t_token & z_y( generate_safe_static_const_t_interned(n_token::t_token("y")) );
static const config::t_token & z_type( generate_safe_static_const_t_interned(n_token::t_token("type")) );
static const config::t_token & z_image( generate_safe_static_const_t_interned(n_token::t_token("image")) );
static const config::t_token & z_layer( generate_safe_static_const_t_interned(n_token::t_token("layer")) );
static const config::t_token & z_name( generate_safe_static_const_t_interned(n_token::t_token("name")) );
static const config::t_token & z_probability( generate_safe_static_const_t_interned(n_token::t_token("probability")) );
static const config::t_token & z_no_flag( generate_safe_static_const_t_interned(n_token::t_token("no_flag")) );
static const config::t_token & z_base( generate_safe_static_const_t_interned(n_token::t_token("base")) );
static const config::t_token & z_set_flag( generate_safe_static_const_t_interned(n_token::t_token("set_flag")) );
// Build a config object
config cfg;
config &item = cfg.add_child(z_terrain_graphics);
config &item = cfg.add_child("terrain_graphics");
config &tile = item.add_child(z_tile);
tile[z_x] = 0;
tile[z_y] = 0;
tile[z_type] = t_translation::write_terrain_code(t_translation::OFF_MAP_USER);
config &tile = item.add_child("tile");
tile["x"] = 0;
tile["y"] = 0;
tile["type"] = t_translation::write_terrain_code(t_translation::OFF_MAP_USER);
config &tile_image = tile.add_child(z_image);
tile_image[z_layer] = -1000;
tile_image[z_name] = image;
config &tile_image = tile.add_child("image");
tile_image["layer"] = -1000;
tile_image["name"] = image;
item[z_probability] = 100;
item[z_no_flag] = z_base;
item[z_set_flag] = z_base;
item["probability"] = 100;
item["no_flag"] = "base";
item["set_flag"] = "base";
// Parse the object
parse_global_config(cfg);
@ -978,16 +927,16 @@ bool terrain_builder::rule_matches(const terrain_builder::building_rule &rule,
return false;
}
const boost::unordered_set<n_token::t_token> &flags = tile_map_[tloc].flags;
const std::set<std::string> &flags = tile_map_[tloc].flags;
foreach (const n_token::t_token &s, cons.no_flag) {
// If a flag listed in z_no_flag is present, the rule does not match
foreach (const std::string &s, cons.no_flag) {
// If a flag listed in "no_flag" is present, the rule does not match
if (flags.find(s) != flags.end()) {
return false;
}
}
foreach (const n_token::t_token &s, cons.has_flag) {
// If a flag listed in z_has_flag is not present, this rule does not match
foreach (const std::string &s, cons.has_flag) {
// If a flag listed in "has_flag" is not present, this rule does not match
if (flags.find(s) == flags.end()) {
return false;
}
@ -1015,7 +964,7 @@ void terrain_builder::apply_rule(const terrain_builder::building_rule &rule, con
}
// Sets flags
foreach (const n_token::t_token &flag, constraint.set_flag) {
foreach (const std::string &flag, constraint.set_flag) {
btile.flags.insert(flag);
}
@ -1025,10 +974,10 @@ void terrain_builder::apply_rule(const terrain_builder::building_rule &rule, con
// copied from text_surface::hash()
// but keep it separated because the needs are different
// and changing it will modify the map random variations
static unsigned int hash_str(const n_token::t_token& str)
static unsigned int hash_str(const std::string& str)
{
unsigned int h = 0;
for(std::string::const_iterator it = str->begin(), it_end = str->end(); it != it_end; ++it)
for(std::string::const_iterator it = str.begin(), it_end = str.end(); it != it_end; ++it)
h = ((h << 9) | (h >> (sizeof(int) * 8 - 9))) ^ (*it);
return h;
}

View file

@ -23,7 +23,6 @@
#include "animated.hpp"
#include "map_location.hpp"
#include "token.hpp"
#include "terrain_translation.hpp"
class config;
@ -88,7 +87,7 @@ public:
* and '.png' suffix
*/
terrain_builder(const config &level, const gamemap* map,
const n_token::t_token& offmap_image);
const std::string& offmap_image);
/** Set the config where we will parse the global terrain rules.
* This also flushes the terrain rules cache.
@ -124,7 +123,7 @@ public:
* to the parameters, or NULL if there is none.
*/
const imagelist *get_terrain_at(const map_location &loc,
const n_token::t_token &tod, TERRAIN_TYPE const terrain_type);
const std::string &tod, TERRAIN_TYPE const terrain_type);
/** Updates the animation at a given tile.
* Returns true if something has changed, and must be redrawn.
@ -157,7 +156,7 @@ public:
*/
struct rule_image_variant {
/** Constructor for the normal defaut case */
rule_image_variant(const n_token::t_token &image_string, const n_token::t_token& variations, bool random_start = true) :
rule_image_variant(const std::string &image_string, const std::string& variations, bool random_start = true) :
image_string(image_string),
variations(variations),
images(),
@ -166,7 +165,7 @@ public:
{};
/** Constructor for true [variant] cases */
rule_image_variant(const n_token::t_token &image_string, const n_token::t_token& variations, const n_token::t_token& tod, bool random_start = true);
rule_image_variant(const std::string &image_string, const std::string& variations, const std::string& tod, bool random_start = true);
/** A string representing either the filename for an image, or
* a list of images, with an optional timing for each image.
@ -185,12 +184,12 @@ public:
* in the animation.
*@endverbatim
*/
n_token::t_token image_string;
std::string image_string;
/** A semi-solon separated list of string used to replace
* @verbatim <code>@V</code> @endverbatim in image_string (if present)
*/
n_token::t_token variations;
std::string variations;
/** An animated image locator built according to the image string.
* This will be the image locator which will actually
@ -199,7 +198,7 @@ public:
std::vector< animated<image::locator> > images;
/** The Time of Day associated to this variant (if any)*/
boost::unordered_set<n_token::t_token> tods;
std::set<std::string> tods;
/** Indicate if the animation uses a random shift */
bool random_start;
@ -270,9 +269,9 @@ public:
map_location loc;
t_translation::t_match terrain_types_match;
std::vector<n_token::t_token> set_flag;
std::vector<n_token::t_token> no_flag;
std::vector<n_token::t_token> has_flag;
std::vector<std::string> set_flag;
std::vector<std::string> no_flag;
std::vector<std::string> has_flag;
rule_imagelist images;
};
@ -296,13 +295,13 @@ public:
*
* @param tod The current time-of-day
*/
void rebuild_cache(const n_token::t_token &tod, logs* log = NULL);
void rebuild_cache(const std::string &tod, logs* log = NULL);
/** Clears all data in this tile, and resets the cache */
void clear();
/** The list of flags present in this tile */
boost::unordered_set<n_token::t_token> flags;
std::set<std::string> flags;
/** Represent a rule_image applied with a random seed.*/
struct rule_image_rand{
@ -335,7 +334,7 @@ public:
/**
* The time-of-day to which the image caches correspond.
*/
n_token::t_token last_tod;
std::string last_tod;
/** Indicates if 'images' is sorted */
bool sorted_images;
@ -512,8 +511,8 @@ private:
* @param angle the angle for substituting the correct replacement.
* @param replacement the replacement strings.
*/
void replace_rotate_tokens(n_token::t_token &s, int angle,
const std::vector<n_token::t_token> &replacement);
void replace_rotate_tokens(std::string &s, int angle,
const std::vector<std::string> &replacement);
/**
* Replaces, in a given rule_image, rotation tokens with their values.
@ -524,7 +523,7 @@ private:
* @param replacement the replacement strings.
*/
void replace_rotate_tokens(rule_image &image, int angle,
const std::vector<n_token::t_token> &replacement);
const std::vector<std::string> &replacement);
/**
* Replaces, in a given rule_variant_image, rotation tokens with their values.
@ -536,7 +535,7 @@ private:
* @param replacement the replacement strings.
*/
void replace_rotate_tokens(rule_image_variant &variant, int angle,
const std::vector<n_token::t_token> &replacement)
const std::vector<std::string> &replacement)
{ replace_rotate_tokens(variant.image_string, angle, replacement); }
/**
@ -549,7 +548,7 @@ private:
* @param replacement the replacement strings.
*/
void replace_rotate_tokens(rule_imagelist &list, int angle,
const std::vector<n_token::t_token> &replacement);
const std::vector<std::string> &replacement);
/**
* Replaces, in a given building_rule, rotation tokens with their values.
@ -563,7 +562,7 @@ private:
* @param replacement the replacement strings.
*/
void replace_rotate_tokens(building_rule &rule, int angle,
const std::vector<n_token::t_token> &replacement);
const std::vector<std::string> &replacement);
/**
* Rotates a template rule to a given angle.
@ -602,7 +601,7 @@ private:
*
*/
void rotate_rule(building_rule &rule, int angle,
const std::vector<n_token::t_token> &angle_name);
const std::vector<std::string> &angle_name);
/**
* Parses a "config" object, which should contains [image] children,
@ -666,7 +665,7 @@ private:
* @param global_images A config object representing the images defined
* as direct children of the [terrain_graphics] rule.
*/
void parse_mapstring(const n_token::t_token &mapstring, struct building_rule &br,
void parse_mapstring(const std::string &mapstring, struct building_rule &br,
anchormap& anchors, const config& global_images);
/**
@ -688,7 +687,7 @@ private:
* template strings @verbatim (@Rn) @endverbatim
*/
void add_rotated_rules(building_ruleset& rules, building_rule& tpl,
const n_token::t_token &rotations);
const std::string &rotations);
/**
* Parses a configuration object containing [terrain_graphics] rules,
@ -707,7 +706,7 @@ private:
*
* @param image The filename of the image
*/
void add_off_map_rule(const n_token::t_token& image);
void add_off_map_rule(const std::string& image);
void flush_local_rules();
@ -781,7 +780,7 @@ private:
/**
* Shorthand typedef for a map associating a list of locations to a terrain type.
*/
typedef boost::unordered_map<t_translation::t_terrain, std::vector<map_location> > terrain_by_type_map;
typedef std::map<t_translation::t_terrain, std::vector<map_location> > terrain_by_type_map;
/**
* A map representing all locations whose terrain is of a given type.

View file

@ -129,21 +129,19 @@ int attack_type_callable::do_compare(const formula_callable* callable) const
return att_.num_attacks() - att_callable->att_.num_attacks();
if ( att_.id() != att_callable->att_.id() )
return (*att_.id()).compare(att_callable->att_.id());
return att_.id().compare(att_callable->att_.id());
if ( att_.type() != att_callable->att_.type() )
return (*att_.type()).compare(att_callable->att_.type());
return att_.type().compare(att_callable->att_.type());
if ( att_.range() != att_callable->att_.range() )
return (*att_.range()).compare(att_callable->att_.range());
return att_.range().compare(att_callable->att_.range());
return (*att_.weapon_specials()).compare(att_callable->att_.weapon_specials());
return att_.weapon_specials().compare(att_callable->att_.weapon_specials());
}
variant unit_callable::get_value(const std::string& key) const
{
static const config::t_token & z_not_living( generate_safe_static_const_t_interned(n_token::t_token("not_living")) );
if(key == "x") {
if (loc_==map_location::null_location) {
return variant();
@ -173,7 +171,7 @@ variant unit_callable::get_value(const std::string& key) const
} else if(key == "leader") {
return variant(u_.can_recruit());
} else if(key == "undead") {
return variant(u_.get_state(z_not_living) ? 1 : 0);
return variant(u_.get_state("not_living") ? 1 : 0);
} else if(key == "attacks") {
const std::vector<attack_type>& att = u_.attacks();
std::vector<variant> res;
@ -182,13 +180,13 @@ variant unit_callable::get_value(const std::string& key) const
res.push_back(variant(new attack_type_callable(*i)));
return variant(&res);
} else if(key == "abilities") {
std::vector<config::t_token> abilities = u_.get_ability_list();
std::vector<std::string> abilities = u_.get_ability_list();
std::vector<variant> res;
if (abilities.empty())
return variant( &res );
for (std::vector<config::t_token>::iterator it = abilities.begin(); it != abilities.end(); ++it)
for (std::vector<std::string>::iterator it = abilities.begin(); it != abilities.end(); ++it)
{
res.push_back( variant(*it) );
}
@ -210,19 +208,19 @@ variant unit_callable::get_value(const std::string& key) const
} else if(key == "attacks_left") {
return variant(u_.attacks_left());
} else if(key == "traits") {
const std::vector<config::t_token> traits = u_.get_traits_list();
const std::vector<std::string> traits = u_.get_traits_list();
std::vector<variant> res;
if(traits.empty())
return variant( &res );
for (std::vector<config::t_token>::const_iterator it = traits.begin(); it != traits.end(); ++it)
for (std::vector<std::string>::const_iterator it = traits.begin(); it != traits.end(); ++it)
{
res.push_back( variant(*it) );
}
return variant( &res );
} else if(key == "states") {
const std::map<config::t_token, config::t_token>& states_map = u_.get_states();
const std::map<std::string, std::string>& states_map = u_.get_states();
return convert_map( states_map );
} else if(key == "side") {
@ -288,13 +286,13 @@ variant unit_type_callable::get_value(const std::string& key) const
} else if(key == "alignment") {
return variant(u_.alignment_id(u_.alignment()));
} else if(key == "abilities") {
std::vector<config::t_token> abilities = u_.get_ability_list();
std::vector<std::string> abilities = u_.get_ability_list();
std::vector<variant> res;
if (abilities.empty())
return variant( &res );
for (std::vector<config::t_token>::iterator it = abilities.begin(); it != abilities.end(); ++it)
for (std::vector<std::string>::iterator it = abilities.begin(); it != abilities.end(); ++it)
{
res.push_back( variant(*it) );
}
@ -349,7 +347,7 @@ int unit_type_callable::do_compare(const formula_callable* callable) const
return formula_callable::do_compare(callable);
}
return (*u_.id()).compare(u_callable->u_.id());
return u_.id().compare(u_callable->u_.id());
}
variant terrain_callable::get_value(const std::string& key) const

View file

@ -154,8 +154,8 @@ void cave_map_generator::generate_chambers()
continue;
}
const std::string xpos = ch["x"];
const std::string ypos = ch["y"];
const std::string &xpos = ch["x"];
const std::string &ypos = ch["y"];
size_t min_xpos = 0, min_ypos = 0, max_xpos = width_, max_ypos = height_;
@ -188,7 +188,7 @@ void cave_map_generator::generate_chambers()
const config &items = ch.child("items");
new_chamber.items = items ? &items : NULL;
const std::string id = ch["id"];
const std::string &id = ch["id"];
if (!id.empty()) {
chamber_ids_[id] = chambers_.size();
}
@ -197,7 +197,7 @@ void cave_map_generator::generate_chambers()
foreach (const config &p, ch.child_range("passage"))
{
const std::string dst = p["destination"];
const std::string &dst = p["destination"];
// Find the destination of this passage
const std::map<std::string,size_t>::const_iterator itor = chamber_ids_.find(dst);

View file

@ -161,7 +161,7 @@ std::string rgb2highlight(Uint32 rgb)
int color_range::index() const
{
for(int i = 1; i <= gamemap::MAX_PLAYERS; ++i) {
if(*this==(game_config::color_info(n_token::t_token(lexical_cast<std::string>(i))))) {
if(*this==(game_config::color_info(lexical_cast<std::string>(i)))) {
return i;
}
}

File diff suppressed because it is too large Load diff

View file

@ -34,15 +34,12 @@
#include <map>
#include <iosfwd>
#include <vector>
#include <utility> //for relops
#include <boost/unordered_map.hpp>
#include <boost/variant/variant.hpp>
#include "game_errors.hpp"
#include "tstring.hpp"
#include "wesconfig.h"
//debug
#include <iostream>
class config;
class vconfig;
struct lua_State;
@ -56,28 +53,17 @@ class config
{
friend bool operator==(const config& a, const config& b);
static config * invalid;
static bool initialize_invalid();
/**
* Raises a most cryptic exception if @a this is not valid.
*/
//Place the call to the exception in the object file.
void throw_missing_child_exception() const ;
static config invalid;
/**
* Raises an exception if @a this is not valid.
*/
void check_valid() const {
if (!*this){
throw_missing_child_exception(); }}
void check_valid() const;
/**
* Raises an exception if @a this or @a cfg is not valid.
*/
void check_valid(const config &cfg) const {
check_valid();
cfg.check_valid();}
void check_valid(const config &cfg) const;
#ifndef HAVE_CXX0X
struct safe_bool_impl { void nonnull() {} };
@ -100,33 +86,25 @@ public:
config(config &&);
config &operator=(config &&);
#endif
/// Define a token that compares faster than a string once created.
/// It is preferable to use t_token as indices over strings
typedef n_token::t_token t_token;
/**
* Creates a config object with an empty child of name @a child.
*/
explicit config(const std::string &child);
explicit config(const t_token &child);
~config();
#ifdef HAVE_CXX0X
explicit operator bool() const
{ return this != invalid; }
{ return this != &invalid; }
#else
operator safe_bool() const
{ return this != invalid ? &safe_bool_impl::nonnull : 0; }
{ return this != &invalid ? &safe_bool_impl::nonnull : 0; }
#endif
typedef std::vector<config*> child_list;
//typedef std::map<t_token,child_list> child_map;
typedef boost::unordered_map<t_token,child_list> child_map;
typedef boost::unordered_map<config::t_token, config *> t_child_range_index;
typedef boost::unordered_map<config::t_token, config const *> t_const_child_range_index;
typedef std::map<std::string,child_list> child_map;
struct const_child_iterator;
@ -189,23 +167,13 @@ public:
* Variant for storing WML attributes.
* The most efficient type is used when assigning a value. For instance,
* strings "yes", "no", "true", "false" will be detected and stored as boolean.
* References are returned as results. Once a value is constructed it is stored so that
* future (likely) references will be fast.
* Try not to stuff int into double or elimnate the ghost copies as that prevent excess copying elsewhere.
* @note The blank variant is only used when querying missing attributes.
* It is not stored in config objects.
*/
class attribute_value
{
public:
enum attribute_type {EMPTY, BOOL, INT, DOUBLE, TSTRING, TOKEN};
private:
mutable int int_value_;
mutable double double_value_;
mutable t_string t_string_value_;
mutable t_token token_value_;
attribute_type type_;
mutable bool bool_value_ : 1;
mutable bool is_bool_ : 1, is_int_ : 1, is_double_ : 1, is_t_string_ : 1, is_token_ : 1;
typedef boost::variant<boost::blank, bool, double, std::string, t_string> value_type;
value_type value;
public:
/** Default implementation, but defined out-of-line for efficiency reasons. */
@ -221,66 +189,35 @@ public:
attribute_value &operator=(int v);
attribute_value &operator=(double v);
attribute_value &operator=(const char *v) { return operator=(std::string(v)); }
attribute_value &operator=(const char *v)
{ return operator=(std::string(v)); }
attribute_value &operator=(const std::string &v);
attribute_value &operator=(const t_string &v);
attribute_value &operator=(const t_token &v);
bool to_bool(bool def = false) const;
int to_int(int def = 0) const;
double to_double(double def = 0.) const;
bool blank() const;
bool empty() const;
bool blank() const {return empty();}; ///todo remove and use the standard empty()
std::string const & str() const;
t_string const & t_str() const;
t_token const & token() const;
std::string str() const;
t_string t_str() const;
operator int() const { return to_int(); }
operator std::string const () const { return str(); } ///This is probably ill advised, due to spurious constructions
//operator t_string const &() const { return t_str(); }
//operator t_token const &() const {return token();}
operator std::string() const { return str(); }
operator t_string() const { return t_str(); }
bool operator==(const attribute_value &other) const;
bool operator!=(const attribute_value &other) const { return !operator==(other); }
friend bool operator==(const attribute_value &a, t_token const & b) ;
friend bool operator==(t_token const & b, const attribute_value &a) { return a == b;}
friend bool operator!=(const attribute_value &a, t_token const & b) { return !(a == b);}
friend bool operator!=(t_token const & b, const attribute_value &a) { return a != b;}
friend bool operator==(const attribute_value &a, t_string const & b) ;
friend bool operator==(t_string const & b, const attribute_value &a) { return a == b;}
friend bool operator!=(const attribute_value &a, t_string const & b) { return !(a== b);}
friend bool operator!=(t_string const & b, const attribute_value &a) { return a != b;}
friend bool operator==(const attribute_value &a, std::string const & b) {return a == t_token(b);}
friend bool operator==(std::string const & b, const attribute_value &a) { return a == b;}
friend bool operator!=(const attribute_value &a, std::string const & b) { return !(a == b);}
friend bool operator!=(std::string const & b, const attribute_value &a) { return a != b;}
friend bool operator==(const attribute_value &a, char const * b) {return a == std::string(b);}
friend bool operator==(char const * b, const attribute_value &a) { return a == b;}
friend bool operator!=(const attribute_value &a, char const * b) { return !(a == b);}
friend bool operator!=(char const * b, const attribute_value &a) { return a != b;}
bool operator!=(const attribute_value &other) const
{ return !operator==(other); }
friend std::ostream& operator<<(std::ostream &os, const attribute_value &v);
struct default_visitor{
void operator()() {}
void operator()(bool const) {}
void operator()(int const) {}
void operator()(double const) {}
void operator()(config::t_token const & ) {}
void operator()(const t_string & ) {}
};
template <typename X> void apply_visitor(X & visitor) const;
friend void luaW_pushscalar(lua_State *, const attribute_value &);
friend void write_key_val(std::ostream &, const std::string &, const attribute_value &, unsigned, std::string &);
friend class vconfig;
};
//Note:: the unordered_map is smaller and the same speed
//typedef std::map<t_token, attribute_value> attribute_map;
typedef boost::unordered_map<t_token, attribute_value> attribute_map;
typedef std::map<std::string, attribute_value> attribute_map;
typedef attribute_map::value_type attribute;
struct const_attribute_iterator
@ -307,22 +244,6 @@ public:
};
typedef std::pair<const_attribute_iterator,const_attribute_iterator> const_attr_itors;
child_itors child_range(const t_token& key);
const_child_itors child_range(const t_token& key) const;
/** Creates an index into the child range to allow for quick searches.
key is the key for the child range and name is the column to index.
i.e. if the list of save games is stored in a child called save with titles
then to create a container indexed by titles do
child_range_index(z_save, z_title);
@Note the index is not stored in the config and is intended for
repeated searches of large child ranges.
*/
t_child_range_index child_range_index(const t_token& key, config::t_token const & name);
t_const_child_range_index const_child_range_index(const t_token& key, config::t_token const & name) const;
unsigned child_count(const t_token &key) const;
child_itors child_range(const std::string& key);
const_child_itors child_range(const std::string& key) const;
@ -331,7 +252,6 @@ public:
/**
* Copies the first child with the given @a key, or an empty config if there is none.
*/
config child_or_empty(const t_token &key) const;
config child_or_empty(const std::string &key) const;
/**
@ -340,7 +260,6 @@ public:
* @note A negative @a n accesses from the end of the object.
* For instance, -1 is the index of the last child.
*/
config &child(const t_token& key, int n = 0);
config &child(const std::string& key, int n = 0);
/**
@ -349,12 +268,9 @@ public:
* @note A negative @a n accesses from the end of the object.
* For instance, -1 is the index of the last child.
*/
const config &child(const t_token& key, int n = 0) const { return const_cast<config *>(this)->child(key, n); }
const config &child(const std::string& key, int n = 0) const { return const_cast<config *>(this)->child(key, n); }
const config &child(const std::string& key, int n = 0) const
{ return const_cast<config *>(this)->child(key, n); }
config& add_child(const t_token& key);
config& add_child(const t_token& key, const config& val);
config& add_child_at(const t_token &key, const config &val, unsigned index);
config& add_child(const std::string& key);
config& add_child(const std::string& key, const config& val);
config& add_child_at(const std::string &key, const config &val, unsigned index);
@ -365,25 +281,20 @@ public:
/**
* Returns a reference to the attribute with the given @a key.
* Creates it if it does not exist. The variant using t_token is faster.
* Creates it if it does not exist.
*/
attribute_value &operator[](const t_token &key);
attribute_value &operator[](const attribute_value &key);
attribute_value &operator[](const std::string &key);
/**
* Returns a reference to the attribute with the given @a key
* or to a dummy empty attribute if it does not exist.
*/
const attribute_value &operator[](const t_token &key) const;
const attribute_value &operator[](const attribute_value &key) const;
const attribute_value &operator[](const std::string &key) const;
/**
* Returns a pointer to the attribute with the given @a key
* or NULL if it does not exist.
*/
const attribute_value *get(const t_token &key) const;
const attribute_value *get(const std::string &key) const;
/**
@ -391,26 +302,21 @@ public:
* Get the value of key and if missing try old_key
* and log msg as a WML error (if not empty)
*/
const attribute_value &get_old_attribute(const t_token &key, const t_token &old_key, const std::string& msg = "") const;
const attribute_value &get_old_attribute(const std::string &key, const std::string &old_key, const std::string& msg = "") const;
/**
* Returns a reference to the first child with the given @a key.
* Creates the child if it does not yet exist.
*/
config &child_or_add(const t_token &key);
config &child_or_add(const std::string &key);
bool has_attribute(const t_token &key) const;
bool has_attribute(const std::string &key) const;
/**
* Function to handle backward compatibility
* Check if has key or old_key
* and log msg as a WML error (if not empty)
*/
bool has_old_attribute(const t_token &key, const t_token &old_key, const std::string& msg = "") const;
bool has_old_attribute(const std::string &key, const std::string &old_key, const std::string& msg = "") const;
void remove_attribute(const t_token &key);
void remove_attribute(const std::string &key);
void merge_attributes(const config &);
@ -420,25 +326,20 @@ public:
* Returns the first child of tag @a key with a @a name attribute
* containing @a value.
*/
config &find_child(const t_token &key, const t_token &name, const t_token &value);
config &find_child(const std::string &key, const std::string &name, const std::string &value);
config &find_child(const std::string &key, const std::string &name,
const std::string &value);
const config &find_child(const t_token &key, const t_token &name, const t_token &value) const
{ return const_cast<config *>(this)->find_child(key, name, value); }
const config &find_child(const std::string &key, const std::string &name, const std::string &value) const
const config &find_child(const std::string &key, const std::string &name,
const std::string &value) const
{ return const_cast<config *>(this)->find_child(key, name, value); }
void clear_children(const t_token& key);
void clear_children(const std::string& key);
/**
* Moves all the children with tag @a key from @a src to this.
*/
void splice_children(config &src, const t_token &key);
void splice_children(config &src, const std::string &key);
void remove_child(const t_token &key, unsigned index);
void recursive_clear_value(const t_token& key);
void remove_child(const std::string &key, unsigned index);
void recursive_clear_value(const std::string& key);
@ -568,7 +469,6 @@ public:
* All children with the given key will be merged
* into the first element with that key.
*/
void merge_children(const t_token& key);
void merge_children(const std::string& key);
/**
@ -576,7 +476,6 @@ public:
* of the specified attribute will be merged into the
* element with that key and that value of the attribute
*/
void merge_children_by_attribute(const t_token& key, const t_token& attribute);
void merge_children_by_attribute(const std::string& key, const std::string& attribute);
//this is a cheap O(1) operation
@ -601,19 +500,7 @@ class variable_set
{
public:
virtual ~variable_set() {}
virtual config::attribute_value get_variable_const(const config::t_token &id) const = 0;
virtual config::attribute_value get_variable_const(const std::string &id) const = 0;
};
template <typename X> void config::attribute_value::apply_visitor(X & visitor) const {
switch(type_){
case (EMPTY) : return visitor();
case(BOOL) : return visitor(bool_value_);
case(INT) : return visitor(int_value_);
case(DOUBLE) : return visitor(double_value_);
case(TOKEN) : return visitor(token_value_);
case(TSTRING) : return visitor(t_string_value_);
default : assert(false);
}
}
#endif

View file

@ -68,31 +68,28 @@ static lg::log_domain log_display("display");
static lg::log_domain log_config("config");
#define ERR_CF LOG_STREAM(err, log_config)
namespace dialogs
{
int advance_unit_dialog(const map_location &loc)
{
static const n_token::t_token & z_advance( generate_safe_static_const_t_interned(n_token::t_token("advance")) );
unit_map::iterator u = resources::units->find(loc);
const std::vector<config::t_token>& options = u->advances_to();
const std::vector<std::string>& options = u->advances_to();
std::vector<std::string> lang_options;
std::vector<unit> sample_units;
for(std::vector<config::t_token>::const_iterator op = options.begin(); op != options.end(); ++op) {
for(std::vector<std::string>::const_iterator op = options.begin(); op != options.end(); ++op) {
sample_units.push_back(::get_advanced_unit(*u, *op));
const unit& type = sample_units.back();
#ifdef LOW_MEM
lang_options.push_back(IMAGE_PREFIX
+ (*type.absolute_image())
+ static_cast<std::string const &>(type.absolute_image())
+ COLUMN_SEPARATOR + type.type_name());
#else
lang_options.push_back(IMAGE_PREFIX + (*type.absolute_image()) + u->image_mods() + COLUMN_SEPARATOR + type.type_name());
lang_options.push_back(IMAGE_PREFIX + type.absolute_image() + u->image_mods() + COLUMN_SEPARATOR + type.type_name());
#endif
preferences::encountered_units().insert(*op);
}
@ -102,17 +99,17 @@ int advance_unit_dialog(const map_location &loc)
{
if (mod["always_display"].to_bool()) always_display = true;
sample_units.push_back(::get_advanced_unit(*u, u->type_id()));
sample_units.back().add_modification(z_advance, mod);
sample_units.back().add_modification("advance", mod);
const unit& type = sample_units.back();
if (!mod["image"].empty()) {
lang_options.push_back(IMAGE_PREFIX + mod["image"].str() + COLUMN_SEPARATOR + mod["description"].str());
} else {
#ifdef LOW_MEM
lang_options.push_back(IMAGE_PREFIX
+ (*type.absolute_image())
+ static_cast<std::string const &>(type.absolute_image())
+ COLUMN_SEPARATOR + mod["description"].str());
#else
lang_options.push_back(IMAGE_PREFIX + (*type.absolute_image()) + u->image_mods() + COLUMN_SEPARATOR + mod["description"].str());
lang_options.push_back(IMAGE_PREFIX + type.absolute_image() + u->image_mods() + COLUMN_SEPARATOR + mod["description"].str());
#endif
}
}
@ -197,7 +194,7 @@ bool animate_unit_advancement(const map_location &loc, size_t choice, const bool
return false;
}
const std::vector<config::t_token>& options = u->advances_to();
const std::vector<std::string>& options = u->advances_to();
std::vector<config> mod_options = u->get_modification_advances();
if(choice >= options.size() + mod_options.size()) {
@ -211,14 +208,11 @@ bool animate_unit_advancement(const map_location &loc, size_t choice, const bool
if (!resources::screen->video().update_locked()) {
unit_animator animator;
bool with_bars = true;
static const config::t_token & z_levelout( generate_safe_static_const_t_interned(n_token::t_token("levelout")) );
animator.add_animation(&*u, z_levelout, u->get_location(), map_location(), 0, with_bars);
animator.add_animation(&*u,"levelout", u->get_location(), map_location(), 0, with_bars);
animator.start_animations();
animator.wait_for_end();
}
static const n_token::t_token & z_advance( generate_safe_static_const_t_interned(n_token::t_token("advance")) );
static const n_token::t_token & z_post_advance( generate_safe_static_const_t_interned(n_token::t_token("post_advance")) );
if(choice < options.size()) {
// chosen_unit is not a reference, since the unit may disappear at any moment.
std::string chosen_unit = options[choice];
@ -230,17 +224,17 @@ bool animate_unit_advancement(const map_location &loc, size_t choice, const bool
if(fire_event)
{
LOG_NG << "firing advance event (AMLA)\n";
game_events::fire(z_advance ,loc);
game_events::fire("advance",loc);
}
amla_unit.set_experience(amla_unit.experience() - amla_unit.max_experience());
amla_unit.add_modification(z_advance,mod_option);
amla_unit.add_modification("advance",mod_option);
resources::units->replace(loc, amla_unit);
if(fire_event)
{
LOG_NG << "firing post_advance event (AMLA)\n";
game_events::fire(z_post_advance, loc);
game_events::fire("post_advance",loc);
}
}
@ -250,8 +244,7 @@ bool animate_unit_advancement(const map_location &loc, size_t choice, const bool
if (u != resources::units->end() && !resources::screen->video().update_locked()) {
unit_animator animator;
static const config::t_token & z_levelin( generate_safe_static_const_t_interned(n_token::t_token("levelin")) );
animator.add_animation(&*u, z_levelin, u->get_location(), map_location(), 0, true);
animator.add_animation(&*u, "levelin", u->get_location(), map_location(), 0, true);
animator.start_animations();
animator.wait_for_end();
animator.set_all_standing();
@ -275,26 +268,17 @@ void show_objectives(const config &level, const std::string &objectives)
namespace {
struct save_with_summary{
save_with_summary(savegame::save_info const & sv, config * cfg):save_(&sv), summary_(cfg){}
savegame::save_info const * save_;
config * summary_;
};
typedef std::vector<save_with_summary> t_saves_with_summaries;
/** Class to handle deleting a saved game. */
class delete_save : public gui::dialog_button_action
{
public:
delete_save(display& disp, gui::filter_textbox& filter, t_saves_with_summaries * saves)
: disp_(disp), saves_(*saves), filter_(filter) {}
delete_save(display& disp, gui::filter_textbox& filter, std::vector<savegame::save_info>& saves, std::vector<config*>& save_summaries) : disp_(disp), saves_(saves), summaries_(save_summaries), filter_(filter) {}
private:
gui::dialog_button_action::RESULT button_pressed(int menu_selection);
display& disp_;
t_saves_with_summaries saves_;
std::vector<savegame::save_info>& saves_;
std::vector<config*>& summaries_;
gui::filter_textbox& filter_;
};
@ -314,11 +298,15 @@ gui::dialog_button_action::RESULT delete_save::button_pressed(int menu_selection
filter_.delete_item(menu_selection);
// Delete the file
savegame::manager::delete_game(saves_[index].save_->name);
savegame::manager::delete_game(saves_[index].name);
// Remove it from the list of saves
saves_.erase(saves_.begin() + index);
if(index < summaries_.size()) {
summaries_.erase(summaries_.begin() + index);
}
return gui::DELETE_ITEM;
} else {
return gui::CONTINUE_DIALOG;
@ -330,12 +318,14 @@ static const int save_preview_border = 10;
class save_preview_pane : public gui::preview_pane
{
public:
save_preview_pane(CVideo &video, const config& game_config, gamemap* map
, t_saves_with_summaries * saves
, const gui::filter_textbox& textbox) :
save_preview_pane(CVideo &video, const config& game_config, gamemap* map,
const std::vector<savegame::save_info>& info,
const std::vector<config*>& summaries,
const gui::filter_textbox& textbox) :
gui::preview_pane(video),
game_config_(&game_config),
map_(map), saves_(*saves),
map_(map), info_(&info),
summaries_(summaries),
index_(0),
map_cache_(),
textbox_(textbox)
@ -355,7 +345,8 @@ public:
private:
const config* game_config_;
gamemap* map_;
t_saves_with_summaries saves_;
const std::vector<savegame::save_info>* info_;
const std::vector<config*>& summaries_;
int index_;
std::map<std::string,surface> map_cache_;
const gui::filter_textbox& textbox_;
@ -363,19 +354,18 @@ private:
void save_preview_pane::draw_contents()
{
static const n_token::t_token & z_leader( generate_safe_static_const_t_interned(n_token::t_token("leader")) );
if (size_t(index_) >= saves_.size() ){
return; }
if (size_t(index_) >= summaries_.size() || info_->size() != summaries_.size()) {
return;
}
std::string dummy;
const config &summary = *saves_[index_].summary_;
const config &summary = *summaries_[index_];
if (summary["label"].empty())
{
try {
savegame::manager::load_summary(saves_[index_].save_->name, *saves_[index_].summary_, &dummy);
savegame::manager::load_summary((*info_)[index_].name, *summaries_[index_], &dummy);
} catch(game::load_game_failed&) {
(*saves_[index_].summary_)["corrupt"] = true;
(*summaries_[index_])["corrupt"] = true;
}
}
@ -391,14 +381,13 @@ void save_preview_pane::draw_contents()
int ypos = area.y;
const unit_type *leader = unit_types.find(summary[z_leader].token());
const unit_type *leader = unit_types.find(summary["leader"]);
if (leader)
{
#ifdef LOW_MEM
const surface image(image::get_image(leader->image()));
#else
const surface image(image::get_image((*leader->image())
+ "~RC(" + (*leader->flag_rgb()) + ">1)"));
const surface image(image::get_image(leader->image() + "~RC(" + leader->flag_rgb() + ">1)"));
#endif
if(image != NULL) {
@ -458,7 +447,7 @@ void save_preview_pane::draw_contents()
}
char time_buf[256] = {0};
const savegame::save_info& save = *saves_[index_].save_;
const savegame::save_info& save = (*info_)[index_];
tm* tm_l = localtime(&save.time_modified);
if (tm_l) {
const size_t res = strftime(time_buf,sizeof(time_buf),
@ -474,7 +463,7 @@ void save_preview_pane::draw_contents()
std::stringstream str;
str << font::BOLD_TEXT << font::NULL_MARKUP
<< saves_[index_].save_->name << '\n' << time_buf;
<< (*info_)[index_].name << '\n' << time_buf;
const std::string& campaign_type = summary["campaign_type"];
if (summary["corrupt"].to_bool()) {
@ -491,7 +480,7 @@ void save_preview_pane::draw_contents()
}
utils::string_map symbols;
if (campaign != NULL) {
symbols["campaign_name"] = (*campaign)["name"].token();
symbols["campaign_name"] = (*campaign)["name"];
} else {
// Fallback to nontranslatable campaign id.
symbols["campaign_name"] = "(" + campaign_id + ")";
@ -586,7 +575,6 @@ std::string format_time_summary(time_t t)
} // end anon namespace
std::string load_game_dialog(display& disp, const config& game_config, bool* show_replay, bool* cancel_orders)
{
std::vector<savegame::save_info> games;
@ -597,23 +585,19 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
if(games.empty()) {
gui2::show_transient_message(disp.video(),
_("No Saved Games"),
_("There are no saved games to load.\n\n(Games are saved automatically when you complete a scenario)"));
_("No Saved Games"),
_("There are no saved games to load.\n\n(Games are saved automatically when you complete a scenario)"));
return "";
}
config::t_child_range_index index = savegame::save_index::indexed_summaries();
t_saves_with_summaries saves_and_summaries;
std::vector<config*> summaries;
std::vector<savegame::save_info>::const_iterator i;
//FIXME: parent_to_child is not used yet
std::map<std::string,std::string> parent_to_child;
std::vector<savegame::save_info>::const_iterator i;
for(i = games.begin(); i != games.end(); ++i) {
n_token::t_token tname(i->name);
config * cfg = &savegame::save_index::find_or_create_summary(index, tname);
n_token::t_token gname = savegame::save_index::gz_corrected_filename(tname);
parent_to_child[(*cfg)["parent"]] = gname;
saves_and_summaries.push_back(save_with_summary(*i, cfg));
config& cfg = savegame::save_index::save_summary(i->name);
parent_to_child[cfg["parent"]] = i->name;
summaries.push_back(&cfg);
}
const events::event_context context;
@ -623,13 +607,12 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
heading << HEADING_PREFIX << _("Name") << COLUMN_SEPARATOR << _("Date");
items.push_back(heading.str());
t_saves_with_summaries::const_iterator j = saves_and_summaries.begin();
for(; j != saves_and_summaries.end(); ++j) {
std::string name = j->save_->name;
for(i = games.begin(); i != games.end(); ++i) {
std::string name = i->name;
utils::truncate_as_wstring(name, std::min<size_t>(name.size(), 40));
std::ostringstream str;
str << name << COLUMN_SEPARATOR << format_time_summary(j->save_->time_modified);
str << name << COLUMN_SEPARATOR << format_time_summary(i->time_modified);
items.push_back(str.str());
}
@ -649,8 +632,7 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
gui::filter_textbox* filter = new gui::filter_textbox(disp.video(), _("Filter: "), items, items, 1, lmenu);
lmenu.set_textbox(filter);
save_preview_pane save_preview(disp.video(),game_config,&map_obj, &saves_and_summaries,*filter);
save_preview_pane save_preview(disp.video(),game_config,&map_obj,games,summaries,*filter);
lmenu.add_pane(&save_preview);
// create an option for whether the replay should be shown or not
if(show_replay != NULL) {
@ -668,9 +650,7 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
lmenu.add_button(new gui::standard_dialog_button(disp.video(),_("OK"),0,false), gui::dialog::BUTTON_STANDARD);
lmenu.add_button(new gui::standard_dialog_button(disp.video(),_("Cancel"),1,true), gui::dialog::BUTTON_STANDARD);
delete_save save_deleter(disp,*filter, &saves_and_summaries);
delete_save save_deleter(disp,*filter,games,summaries);
gui::dialog_button_info delete_button(&save_deleter,_("Delete Save"));
lmenu.add_button(delete_button,
@ -682,14 +662,15 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
savegame::save_index::write_save_index();
res = filter->get_index(res);
if(res == -1){ return ""; }
if(res == -1)
return "";
res = filter->get_index(res);
int option_index = 0;
if(show_replay != NULL) {
*show_replay = lmenu.option_checked(option_index++);
const config& summary = *saves_and_summaries[res].summary_;
const config& summary = *summaries[res];
if (summary["replay"].to_bool() && !summary["snapshot"].to_bool(true)) {
*show_replay = true;
}
@ -698,7 +679,7 @@ std::string load_game_dialog(display& disp, const config& game_config, bool* sho
*cancel_orders = lmenu.option_checked(option_index++);
}
return saves_and_summaries[res].save_->name;
return games[res].name;
}
namespace {
@ -876,9 +857,9 @@ void unit_preview_pane::draw_contents()
<< at_it->num_attacks()
<< " " << at_it->name() << "\n";
text << font::weapon_details
<< " " << string_table["range_" + (*at_it->range())]
<< " " << string_table["range_" + at_it->range()]
<< font::weapon_details_sep
<< string_table["type_" + (*at_it->type() )] << "\n";
<< string_table["type_" + at_it->type()] << "\n";
std::string accuracy_parry = at_it->accuracy_parry_description();
if(accuracy_parry.empty() == false) {
@ -961,8 +942,8 @@ const unit_preview_pane::details units_list_preview_pane::get_details() const
det.traits = utils::join(u.trait_names(), ", ");
//we filter to remove the tooltips (increment by 2)
const std::vector<t_string> &abilities = u.ability_tooltips(true);
for(std::vector<t_string>::const_iterator a = abilities.begin();
const std::vector<std::string> &abilities = u.ability_tooltips(true);
for(std::vector<std::string>::const_iterator a = abilities.begin();
a != abilities.end(); a+=2) {
det.abilities.push_back(*a);
}
@ -1012,8 +993,8 @@ const unit_types_preview_pane::details unit_types_preview_pane::get_details() co
//FIXME: There should be a better way to deal with this
unit_types.find(t->id(), unit_type::WITHOUT_ANIMATIONS);
std::string mod = "~RC(" + (*t->flag_rgb()) + ">" + team::get_side_color_index(side_) + ")";
det.image = image::get_image((*t->image()) + mod);
std::string mod = "~RC(" + t->flag_rgb() + ">" + team::get_side_color_index(side_) + ")";
det.image = image::get_image(t->image()+mod);
det.name = "";
det.type_name = t->type_name();
@ -1030,7 +1011,7 @@ const unit_types_preview_pane::details unit_types_preview_pane::get_details() co
{
if (tr["availability"] != "musthave") continue;
std::string gender_string = (!t->genders().empty() && t->genders().front()== unit_race::FEMALE) ? "female_name" : "male_name";
config::attribute_value name = tr[gender_string];
t_string name = tr[gender_string];
if (name.empty()) {
name = tr["name"];
}
@ -1038,7 +1019,7 @@ const unit_types_preview_pane::details unit_types_preview_pane::get_details() co
if (!det.traits.empty()) {
det.traits += ", ";
}
det.traits += name.str();
det.traits += name;
}
}

View file

@ -642,7 +642,7 @@ std::vector<surface> display::get_fog_shroud_images(const map_location& loc, ima
}
std::vector<surface> display::get_terrain_images(const map_location &loc,
const n_token::t_token& timeid,
const std::string& timeid,
image::TYPE image_type,
TERRAIN_TYPE terrain_type)
{
@ -737,7 +737,7 @@ std::vector<surface> display::get_terrain_images(const map_location &loc,
surface surf;
if(!use_local_light) {
const bool off_map = (image.get_filename() == n_token::t_token(off_map_name));
const bool off_map = (image.get_filename() == off_map_name);
surf = image::get_image(image, off_map ? image::SCALED_TO_HEX : image_type);
} else if(color_mod.empty()) {
surf = image::get_image(image, image::SCALED_TO_HEX);
@ -2212,7 +2212,6 @@ void display::refresh_report(std::string const &report_name, const config &_repo
SDL_Rect &rect = reportRects_[report_name];
const SDL_Rect &new_rect = item->location(screen_area());
surface &surf = reportSurfaces_[report_name];
/// @todo check to see if reports_ is ever updated
config &report = reports_[report_name];
// Report and its location is unchanged since last time. Do nothing.
@ -2376,10 +2375,10 @@ void display::refresh_report(std::string const &report_name, const config &_repo
}
skip_element:
t = (*elements.first)["tooltip"].t_str().base_str();
t = (*elements.first)["tooltip"].str();
if (!t.empty()) {
if (!used_ellipsis) {
tooltips::add_tooltip(area, t, (*elements.first)["help"].t_str().base_str());
tooltips::add_tooltip(area, t, (*elements.first)["help"]);
} else {
// Collect all tooltips for the ellipsis.
// TODO: need a better separator

View file

@ -538,7 +538,7 @@ protected:
enum TERRAIN_TYPE { BACKGROUND, FOREGROUND};
std::vector<surface> get_terrain_images(const map_location &loc,
const n_token::t_token& timeid,
const std::string& timeid,
image::TYPE type,
TERRAIN_TYPE terrain_type);

View file

@ -1,49 +0,0 @@
/* $Id$ */
/*
Copyright (C) 2010 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
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
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 "exceptions.hpp"
#include "gettext.hpp"
#include <sstream>
namespace game {
wml_syntax_error::wml_syntax_error(std::string const & reason)
: output_( _("WML Syntax error:: Variable in WML string cannot be evaluated because, ") + reason) {}
/**Tries to parse the error message so that an arror <-- points to the location of the error */
wml_syntax_error::wml_syntax_error(std::string const & str, size_t const & pos, std::string const & reason)
: output_() {
std::stringstream ss;
ss << _("WML Syntax error:: Variable in WML string cannot be evaluated because, ") << reason<< _(" in \n\"");
ss << str << "\" at \n\"";
ss << str.substr(0, pos);
if(pos != str.size()){
ss << "\" <--";
if((pos+1) != str.size()){
ss << "-->\"";
ss << str.substr(pos) << "\"";
}
}
else { ss << "\"<--"; }
output_ = ss.str();
}
const char * wml_syntax_error::what() const throw() {
return output_.c_str();
}
}

View file

@ -17,9 +17,6 @@
#include <exception>
#include <string>
#include "gettext.hpp"
#include <sstream>
#include "token.hpp"
namespace game {
@ -42,63 +39,6 @@ struct error : std::exception
}
};
/**
///WML syntax error exception
When parsing wml from a vector of tokens when the location of the error is known an exact
error message can be thrown.
*/
class wml_syntax_error : public std::exception {
typedef n_token::t_token t_token;
typedef std::vector<t_token> t_tokens;
std::string output_; ///the parsed what string
public:
~wml_syntax_error() throw() {}
/** Construct a wml syntax error with the vectors of parsed tokens, the position of the error and a reason for the error. */
template <typename T_castable_to_token>
wml_syntax_error(std::vector<T_castable_to_token> const & tokens, size_t const & pos, std::string const & reason = "unknown reason");
/** Construct a wml syntax error with the unparsed string the position of the error and a reason for the error. */
wml_syntax_error(std::string const & tokens, size_t const & pos, std::string const & reason = "unknown reason");
wml_syntax_error(std::string const & reason = "unknown reason");
/** Tries to parse the error message so that an arror <-- points to the location of the error */
virtual const char * what() const throw() ;
};
template <typename T_castable_to_token>
wml_syntax_error::wml_syntax_error(std::vector<T_castable_to_token> const & itokens, size_t const & p, std::string const & reason)
: output_() {
t_tokens tokens;
typedef std::vector<T_castable_to_token> t_input_tokens;
typename t_input_tokens::const_iterator it(itokens.begin()), itend(itokens.end());
for(; it != itend; ++it) {
tokens.push_back(static_cast<t_token const &>(*it)); }
std::stringstream ss;
ss << _("WML Syntax error:: Variable in WML string cannot be evaluated because, ") << reason<< _(" in \n\"");
t_tokens::const_iterator i = tokens.begin(), pos(tokens.begin() + p);
for(; i!=tokens.end(); ++i){
ss << *i; }
ss << "\" at \n\"";
for(i = tokens.begin(); (i!= tokens.end() && i != pos) ; ++i){
ss << *i; }
if(i != tokens.end()){
ss << "\" -->\"" << *i << "\"<-- ";
if((++i) != tokens.end()){
ss << "\"";
for(; i != tokens.end(); ++i){
ss << *i; }
ss << "\"";
}
}
else { ss << "\"<--"; }
output_ = ss.str();
}
}
#endif

View file

@ -678,11 +678,11 @@ const std::string &get_cache_dir()
cache_dir += "/.cache";
} else cache_dir = xdg_cache;
cache_dir += "/wesnoth";
create_directory_if_missing_recursive(cache_dir);
#else
cache_dir = get_dir(get_user_data_dir() + "/cache");
#endif
}
create_directory_if_missing_recursive(cache_dir);
return cache_dir;
}

View file

@ -1265,7 +1265,7 @@ bool load_font_config()
known_fonts.insert(font["name"]);
}
family_order = fonts_config["family_order"].t_str();
family_order = fonts_config["family_order"];
const std::vector<std::string> font_order = utils::split(fonts_config["order"]);
std::vector<font::subset_descriptor> fontlist;
std::vector<std::string>::const_iterator font;

View file

@ -17,10 +17,14 @@
#include "formula_string_utils.hpp"
#include "config.hpp"
#include "log.hpp"
#include "formula.hpp"
#include "gettext.hpp"
#include "formula_string_utils_backend.hpp"
static lg::log_domain log_engine("engine");
#define ERR_NG LOG_STREAM(err, log_engine)
static bool two_dots(char a, char b) { return a == '.' && b == '.'; }
namespace utils {
@ -29,47 +33,182 @@ class string_map_variable_set : public variable_set
public:
string_map_variable_set(const string_map& map) : map_(map) {};
virtual config::attribute_value get_variable_const(const n_token::t_token &key) const {
virtual config::attribute_value get_variable_const(const std::string &key) const
{
config::attribute_value val;
const string_map::const_iterator itor = map_.find(key);
if (itor != map_.end())
val = itor->second;
return val;
}
virtual config::attribute_value get_variable_const(const std::string &key) const{
return get_variable_const(n_token::t_token(key));}
private:
const string_map& map_;
};
}
static std::string do_interpolation(const std::string &str, const variable_set& set)
{
std::string res = str;
// This needs to be able to store negative numbers to check for the while's condition
// (which is only false when the previous '$' was at index 0)
int rfind_dollars_sign_from = res.size();
while(rfind_dollars_sign_from >= 0) {
// Going in a backwards order allows nested variable-retrieval, e.g. in arrays.
// For example, "I am $creatures[$i].user_description!"
const std::string::size_type var_begin_loc = res.rfind('$', rfind_dollars_sign_from);
// If there are no '$' left then we're done.
if(var_begin_loc == std::string::npos) {
break;
}
// 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;
const std::string::iterator var_begin = res.begin() + var_begin_loc;
// The '$' is not part of the variable name.
const std::string::iterator var_name_begin = var_begin + 1;
std::string::iterator var_end = var_name_begin;
if(var_name_begin == res.end()) {
// Any '$' at the end of a string is just a '$'
continue;
} else if(*var_name_begin == '(') {
// The $( ... ) syntax invokes a formula
int paren_nesting_level = 0;
bool in_string = false,
in_comment = false;
do {
switch(*var_end) {
case '(':
if(!in_string && !in_comment) {
++paren_nesting_level;
}
break;
case ')':
if(!in_string && !in_comment) {
--paren_nesting_level;
}
break;
case '#':
if(!in_string) {
in_comment = !in_comment;
}
break;
case '\'':
if(!in_comment) {
in_string = !in_string;
}
break;
// TODO: support escape sequences when/if they are allowed in FormulaAI strings
}
} while(++var_end != res.end() && paren_nesting_level > 0);
if(paren_nesting_level > 0) {
ERR_NG << "Formula in WML string cannot be evaluated due to "
<< "missing closing paren:\n\t--> \""
<< std::string(var_begin, var_end) << "\"\n";
res.replace(var_begin, var_end, "");
continue;
}
try {
const game_logic::formula form(std::string(var_begin+2, var_end-1));
res.replace(var_begin, var_end, form.evaluate().string_cast());
} catch(game_logic::formula_error& e) {
ERR_NG << "Formula in WML string cannot be evaluated due to "
<< e.type << "\n\t--> \""
<< e.formula << "\"\n";
res.replace(var_begin, var_end, "");
}
continue;
}
// Find the maximum extent of the variable name (it may be shortened later).
for(int bracket_nesting_level = 0; var_end != res.end(); ++var_end) {
const char c = *var_end;
if(c == '[') {
++bracket_nesting_level;
}
else if(c == ']') {
if(--bracket_nesting_level < 0) {
break;
}
}
// isascii() breaks on mingw with -std=c++0x
else if (!(((c) & ~0x7f) == 0)/*isascii(c)*/ || (!isalnum(c) && c != '.' && c != '_')) {
break;
}
}
// Two dots in a row cannot be part of a valid variable name.
// That matters for random=, e.g. $x..$y
var_end = std::adjacent_find(var_name_begin, var_end, two_dots);
// If the last character is '.', then it can't be a sub-variable.
// It's probably meant to be a period instead. Don't include it.
// Would need to do it repetitively if there are multiple '.'s at the end,
// but don't actually need to do so because the previous check for adjacent '.'s would catch that.
// For example, "My score is $score." or "My score is $score..."
if(*(var_end-1) == '.'
// However, "$array[$i]" by itself does not name a variable,
// so if "$array[$i]." is encountered, then best to include the '.',
// so that it more closely follows the syntax of a variable (if only to get rid of all of it).
// (If it's the script writer's error, they'll have to fix it in either case.)
// For example in "$array[$i].$field_name", if field_name does not exist as a variable,
// then the result of the expansion should be "", not "." (which it would be if this exception did not exist).
&& *(var_end-2) != ']') {
--var_end;
}
const std::string var_name(var_name_begin, var_end);
if(var_end != res.end() && *var_end == '|') {
// It's been used to end this variable name; now it has no more effect.
// This can allow use of things like "$$composite_var_name|.x"
// (Yes, that's a WML 'pointer' of sorts. They are sometimes useful.)
// If there should still be a '|' there afterwards to affect other variable names (unlikely),
// just put another '|' there, one matching each '$', e.g. "$$var_containing_var_name||blah"
++var_end;
}
if (var_name == "") {
// Allow for a way to have $s in a string.
// $| will be replaced by $.
res.replace(var_begin, var_end, "$");
}
else {
// The variable is replaced with its value.
res.replace(var_begin, var_end,
set.get_variable_const(var_name));
}
}
return res;
}
namespace utils {
std::string interpolate_variables_into_string(const std::string &str, const string_map * const symbols) {
std::string interpolate_variables_into_string(const std::string &str, const string_map * const symbols)
{
string_map_variable_set set(*symbols);
return interpolate_variables_into_string(str, set);
return do_interpolation(str, set);
}
std::string interpolate_variables_into_string(const std::string &str, const variable_set& variables) {
n_token::t_token token(str);
wml_interpolation::t_parse_and_interpolator interpolator(token);
token = interpolator.parse_and_interpolate(variables);
return (*token);
std::string interpolate_variables_into_string(const std::string &str, const variable_set& variables)
{
return do_interpolation(str, variables);
}
void interpolate_variables_into_token(n_token::t_token &token, const variable_set& variables) {
wml_interpolation::t_parse_and_interpolator interpolator(token);
token = interpolator.parse_and_interpolate(variables);
}
t_string interpolate_variables_into_tstring(const t_string &tstr, const variable_set& variables) {
t_string interpolate_variables_into_tstring(const t_string &tstr, const variable_set& variables)
{
if(!tstr.str().empty()) {
n_token::t_token token(tstr);
wml_interpolation::t_parse_and_interpolator interpolator(token);
token = interpolator.parse_and_interpolate(variables);
if(tstr.str() != token) {
return t_string( (*token) );
std::string interp = utils::interpolate_variables_into_string(tstr.str(), variables);
if(tstr.str() != interp) {
return t_string(interp);
}
}
return tstr;

View file

@ -17,7 +17,6 @@
#ifndef FORMULA_STRING_UTILS_HPP_INCLUDED
#define FORMULA_STRING_UTILS_HPP_INCLUDED
#include "token.hpp"
#include "serialization/string_utils.hpp"
class variable_set;
@ -31,7 +30,6 @@ namespace utils {
*/
std::string interpolate_variables_into_string(const std::string &str, const string_map * const symbols);
std::string interpolate_variables_into_string(const std::string &str, const variable_set& variables);
void interpolate_variables_into_token(n_token::t_token &str, const variable_set& variables);
/**
* Function that does the same as the above, for t_stringS.

View file

@ -1,517 +0,0 @@
/* $Id$ */
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
Copyright (C) 2005 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
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
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 "formula_string_utils_backend.hpp"
#include "game_display.hpp" //for add_chat_message for the error message
namespace wml_interpolation {
typedef n_token::t_token t_token;
typedef std::vector<t_token> t_tokens;
static const t_token & z_dollar( generate_safe_static_const_t_interned(n_token::t_token("$")) );
static const t_token & z_bar( generate_safe_static_const_t_interned(n_token::t_token("|")) );
static const t_token & z_dot( generate_safe_static_const_t_interned(n_token::t_token(".")) );
static const t_token & z_lbracket( generate_safe_static_const_t_interned(n_token::t_token("[")) );
static const t_token & z_rbracket( generate_safe_static_const_t_interned(n_token::t_token("]")) );
static const t_token & z_lparen( generate_safe_static_const_t_interned(n_token::t_token("(")) );
static const t_token & z_rparen( generate_safe_static_const_t_interned(n_token::t_token(")")) );
static const t_token & z_single_quote( generate_safe_static_const_t_interned(n_token::t_token("'")) );
static const t_token & z_sharp( generate_safe_static_const_t_interned(n_token::t_token("#")) );
template <typename T>
t_tokenizer::t_tokenizer(T const & in)
: tokens_(), is_done_(false), is_valid_varname_(false), input_string_((*in))
, curr_pos_(0), end_(input_string_.size())
, varname_start_(input_string_.npos){}
template <typename T>
t_tokens const & t_tokenizer::tokenize(T const & in) {
input_string_ = ((*in));
is_done_=false;
return tokenize(); }
t_tokens const & t_tokenizer::tokenize() {
static const t_token & z_empty( generate_safe_static_const_t_interned(n_token::t_token("")) );
if(!is_done_){
tokens_.clear();
curr_pos_=0;
end_=input_string_.size();
if(end_ == 0) {
tokens_.push_back(z_empty);
is_done_ = true; }
else {
varname_start_=input_string_.npos;
int guard(0);
while (!is_done_ && (++guard < 1e6)){
process_char(); } }
assert(is_done_);
}
if(! lg::debug.dont_log(log_interpolate)){
std::stringstream ss;
ss << "tokenized [";
foreach(t_token const &tok, tokens_){ ss << " \""<<tok<<"\"";}
DEBUG_INTERP << ss.str() << "]\n";
}
return tokens_;
}
void t_tokenizer::grab_name(){
if(varname_start_ != input_string_.npos){
t_token next_token(input_string_.substr(varname_start_, curr_pos_- varname_start_));
tokens_.push_back(next_token);
varname_start_=input_string_.npos;
}
}
void t_tokenizer::process_char(){
if(curr_pos_ == end_){ grab_name(); is_done_=true; return; }
//if the char at curr_pos is a control character then it is its own token
//otherwise it is the start of a multicharacter token
char curr_char = input_string_[curr_pos_];
switch(curr_char){
case '$' : grab_name(); tokens_.push_back(z_dollar); ++curr_pos_; return ;
case '|' : grab_name(); tokens_.push_back(z_bar); ++curr_pos_; return ;
case '[' : grab_name(); tokens_.push_back(z_lbracket); ++curr_pos_; return;
case ']': grab_name(); tokens_.push_back(z_rbracket); ++curr_pos_; return;
case '(': grab_name(); tokens_.push_back(z_lparen); ++curr_pos_; return;
case ')': grab_name(); tokens_.push_back(z_rparen); ++curr_pos_; return;
case '.': grab_name(); tokens_.push_back(z_dot); ++curr_pos_; return;
case '#': grab_name(); tokens_.push_back(z_sharp); ++curr_pos_; return;
case '\'': grab_name(); tokens_.push_back(z_single_quote); ++curr_pos_; return;
default:
//Multi-character tokens are either all valid variable name characters or all not valid variable name characters
bool is_good_char = is_alnum_or_underscore(curr_char);
if(is_good_char != is_valid_varname_){
grab_name();
}
if(varname_start_ == input_string_.npos){
varname_start_ = curr_pos_;
is_valid_varname_ = is_good_char ;
}
++curr_pos_;
}
}
/**
t_operation is a functor that does 2 things
1. When provided with a token stack and a variable set it performs an operation like interpolation.
2. When given a token stack an t_operation stack it performs its operation if it can do so without the
variable set, otherwise it puts an operation on the instruction stack. This function can be called when the expression
is parsed in order to reduce the operations to their smallest set.
*/
//static member
t_operation_ptr const t_operation::void_op_;
std::string const t_operation_noop::string() const {return "[noop] "; }
std::string const t_operation_push::string() const {std::stringstream ss; ss << "[push \"" <<x_<<"\"] "; return ss.str(); }
std::string const t_operation_append::string() const {std::stringstream ss; ss << "[append \"" <<x_<<"\"] "; return ss.str(); }
std::string const t_operation_append::string(std::string const & res) const {
std::stringstream ss; ss << "[append \"" <<x_<<"\"->\""<< res <<"\"] "; return ss.str(); }
std::string const t_operation_interp::string() const {return "[interpolate] "; }
std::string const t_operation_interp::string(std::string const & var, std::string const & res) const {
std::stringstream ss; ss << "[interpolate \"" << var <<"\"->\""<< res <<"\"] "; return ss.str(); }
std::string const t_operation_formula::string() const {return "[formula] "; }
std::string const t_operation_formula::string(std::string const & var, std::string const & res) const {
std::stringstream ss; ss << "[formula \"" << var <<"\"->\""<< res <<"\"] "; return ss.str(); }
//Static Member
t_operation_append::t_append_cache t_operation_append::cache_(t_operation_append::t_make_append_result(), CACHE_SIZE);
void t_operation_formula::operator()(t_tokens & stack, variable_set const & variable_set) const {
t_token var_name(stack.back());
stack.pop_back();
try {
const game_logic::formula form(*var_name);
t_token rhs(form.evaluate().string_cast());
t_operation_append append(rhs);
append(stack, variable_set);
DEBUG_INTERP << string(var_name, (*rhs) ) << "\n";
} catch(game_logic::formula_error& e) {
ERR_INTERP << _("Formula in WML string cannot be evaluated because, ")
<< e.type << "\n\t--> \""
<< e.formula << "\"\n";
t_operation_append append(var_name);
append(stack, variable_set);
}
}
void t_instructions::optimize(t_token const & unparsed) {
t_operations optimized;
DEBUG_INTERP << "Optimizing these instructions : \n" << *this <<"\n";
if(ops_.size() > 1){
bool last_instruction_optimized(false);
t_operations::iterator i_not (ops_.begin() + 1);
while(i_not!=ops_.end()){
//reduce either the last 2 instructions or the last instruction and the last optimized instruction
t_operation_ptr const & first_op = (last_instruction_optimized == true) ? optimized.back() : *(i_not-1);
t_operation::t_reduce_result reduced =first_op->reduce(*i_not);
if(reduced.second){
DEBUG_INTERP <<"Reducing "<< *first_op << " + " << (**i_not) << " to "<< *reduced.first<<"\n";
if(last_instruction_optimized){ optimized.pop_back(); }
last_instruction_optimized = true;
optimized.push_back(reduced.first); }
else{
DEBUG_INTERP <<"Not reducing "<< *first_op << " + " << (**i_not) << " \n";
if(last_instruction_optimized){ }
else { optimized.push_back(first_op); }
last_instruction_optimized = false; }
++i_not;
}
if(! last_instruction_optimized){ optimized.push_back( ops_.back() ); }
ops_.swap(optimized);
}
//Check to see if the optimized result is to just push the original token and clears the ops_.
if(ops_.size() == 1){
t_operation_push op_push_unparsed(unparsed);
if(op_push_unparsed == ops_[0]){ ops_.clear(); }
}
DEBUG_INTERP << "Optimized instructions : \n" << *this <<"\n";
}
///runs the instructions and places the results in @param[out] x
void t_instructions::run_core(t_token & x, variable_set const & set) const {
t_tokens stack;
assert(!ops_.empty());
//DEBUG_INTERP << "Running these instructions : \n" << *this <<"\n";
t_operations::const_iterator i (ops_.begin());
for(; i!= ops_.end(); ++i){
(**i)(stack, set); }
assert(stack.size() == 1);
x = stack.back();
}
std::ostream & operator<<(std::ostream &out, t_instructions const & a){
t_operations::const_iterator i (a.ops_.begin());
for(; i!= a.ops_.end(); ++i){
out <<(**i) <<"\n";
}
return out; }
std::ostream & operator<<(std::ostream &out, t_parse const & a){
out<<"TOKENS ";
foreach(t_token const &tok, a.tokens_){out <<" \""<<tok<<"\"";}
out<<" /TOKENS \n OPS ";
t_operations const & ops( a.complete_parse_.ops() );
t_operations::const_iterator i(ops.begin());
for(; i != ops.end(); ++i){ out << *i ;}
return out<<" /OPS \n";
}
t_parse::t_parse(n_token::t_token const & unparsed)
: token_(unparsed)
, tokens_()
, complete_parse_() {}
t_parse::t_parse(t_parse const & a )
: token_(a.token_)
, tokens_(a.tokens_)
, complete_parse_(a.complete_parse_)
{
}
t_parse & t_parse::operator=(t_parse const & a) {
token_ = (a.token_);
complete_parse_ = a.complete_parse_;
return *this; }
///Calculate a parse
t_instructions & t_parse::parse(){
t_tokenizer tokenizer(token_);
tokens_ = tokenizer.tokenize();
complete_parse_.ops().clear();
do_parse_plain(tokens_.begin());
return complete_parse_;
}
t_token const & t_parse::peek_next(t_tokens::iterator const & curr_pos ){
static const t_token & z_empty( generate_safe_static_const_t_interned(n_token::t_token("")) );
t_tokens::iterator next(curr_pos + 1);
return (next != tokens_.end() ) ? (*next) : z_empty; }
//Keep concatenating components until you see a $ which indicates some kind of interpolation
t_tokens::iterator t_parse::do_parse_plain(t_tokens::iterator const & start_pos ){
t_tokens::iterator curr_pos = start_pos;
while(curr_pos != tokens_.end()) {
if(*curr_pos == z_dollar) {
//$| inserts just a $
if( peek_next(curr_pos) == z_bar){
static const t_operation_ptr op(new t_operation_append(z_dollar));
complete_parse_.ops().push_back(op);
curr_pos+=2; }
//A interpolation / formula
else {
size_t good_size = complete_parse_.ops().size();
try {
curr_pos = do_parse_interp(++curr_pos); }
catch (game::wml_syntax_error & e) {
ERR_INTERP << e.what()<<"\n";
static const config::t_token & z_caption( generate_safe_static_const_t_interned(n_token::t_token(_("Invalid WML found"))) );
if(resources::screen) {
resources::screen->add_chat_message(time(NULL), z_caption, 0, e.what(),
events::chat_handler::MESSAGE_PUBLIC, false); }
if(complete_parse_.ops().size() > good_size){
complete_parse_.ops().resize(good_size); } } } }
//text variable name component
else {
t_operation_ptr op(new t_operation_append(*curr_pos));
complete_parse_.ops().push_back(op);
++curr_pos; }
}
return curr_pos;
}
t_tokens::iterator t_parse::do_parse_interp(t_tokens::iterator const & start_pos ){
bool found_part_of_name(false);
t_tokens::iterator curr_pos = start_pos + 1;
//A $ at the end of the line is just a $
if(start_pos == tokens_.end()){
static const t_operation_ptr op(new t_operation_append(z_dollar));
complete_parse_.ops().push_back(op);
return start_pos; }
//Start of the variable name
if (is_good_for_varname(*start_pos)){
found_part_of_name = true;
t_operation_ptr op(new t_operation_push(*start_pos));
complete_parse_.ops().push_back(op); }
else if(*start_pos == z_dollar){
// $| Creates a $ to allow for $ in the string
if( peek_next(start_pos) == z_bar){
throw game::wml_syntax_error(tokens_, start_pos - tokens_.begin(), _(" $$| creates an illegal variable name")); }
//A Nested interpolation / formula
else {
curr_pos = do_parse_interp(start_pos + 1);
//todo this is a small lie if the interpolated result contains a control character
found_part_of_name = true; } }
// $( ... ) Creates a WML formula
else if (*start_pos == z_lparen){
return do_parse_formula(start_pos); }
// Everything else is an error
else { throw game::wml_syntax_error(tokens_, start_pos - tokens_.begin(), _("missing variable name immediately after $")); }
// Grab and append tokens until we reach the end of the variable name
int bracket_nesting_level = 0;
while(curr_pos != tokens_.end()){
//text variable name component
if (is_good_for_varname(*curr_pos)){
found_part_of_name = true;
t_operation_ptr op(new t_operation_append(*curr_pos));
complete_parse_.ops().push_back(op);
++curr_pos; }
else if(*curr_pos == z_dollar){
// $| Creates a $ to allow for $ in the string
if( peek_next(curr_pos) == z_bar){
break; }
//A Nested interpolation / formula
else{
found_part_of_name = true;
curr_pos = do_parse_interp(++curr_pos); } }
//[] Nesting brackets
else if(*curr_pos == z_lbracket){
static const t_operation_ptr op(new t_operation_append(z_lbracket));
complete_parse_.ops().push_back(op);
++bracket_nesting_level;
++curr_pos; }
else if(*curr_pos == z_rbracket){
if((--bracket_nesting_level) < 0) { break; }
static const t_operation_ptr op(new t_operation_append(z_rbracket));
complete_parse_.ops().push_back(op);
++curr_pos; }
//Dots
//two dots terminates variable expansion
// That matters for random=, e.g. $x..$y
else if(*curr_pos == z_dot){
if(peek_next(curr_pos) == z_dot){ break; }
static const t_operation_ptr op(new t_operation_append(z_dot));
complete_parse_.ops().push_back(op);
++curr_pos; }
//A | terminates the variable name
// It's been used to end this variable name; now it has no more effect.
// This can allow use of things like "$$composite_var_name|.x"
// (Yes, that's a WML 'pointer' of sorts. They are sometimes useful.)
else if(*curr_pos == z_bar) {
++curr_pos;
break; }
//Invalid variable name component
else if (!is_good_for_varname(*curr_pos)){
break; }
//Never happen
else { assert(false); }
}
// If the last character is '.', then it can't be a sub-variable.
// It's probably meant to be a period instead. Don't include it.
// Would need to do it repetitively if there are multiple '.'s at the end,
// but don't actually need to do so because the previous check for adjacent '.'s would catch that.
// For example, "My score is $score." or "My score is $score..."
if(*(curr_pos - 1) == z_dot && (curr_pos-1) != start_pos ){
// However, "$array[$i]" by itself does not name a variable,
// so if "$array[$i]." is encountered, then best to include the '.',
// so that it more closely follows the syntax of a variable (if only to get rid of all of it).
// (If it's the script writer's error, they'll have to fix it in either case.)
// For example in "$array[$i].$field_name", if field_name does not exist as a variable,
// then the result of the expansion should be "", not "." (which it would be if this exception did not exist).
if( *(curr_pos-2) != z_rbracket) {
complete_parse_.ops().pop_back();
--curr_pos; }
else {
throw game::wml_syntax_error(tokens_, curr_pos - tokens_.begin()
, _("missing field name after ]. (correct usage: $array[$i].fieldname)")); } }
if(! found_part_of_name) {
throw game::wml_syntax_error(tokens_, start_pos - tokens_.begin()
, _("missing variable name after $ (valid characters are a-zA-Z0-9_)")); }
//FInally an interpolation
t_operation_ptr op(new t_operation_interp());
complete_parse_.ops().push_back(op);
return curr_pos;
}
/** do_parse forumal parses a formula invoked by $ (...) syntax
*/
t_tokens::iterator t_parse::do_parse_formula(t_tokens::iterator const & start_pos ){
//Deal with the first token in the iterpolated variable
if(start_pos == tokens_.end()){
throw game::wml_syntax_error(tokens_, start_pos - tokens_.begin(), _("formula is incomplete at the end of the line")); }
if(*start_pos != z_lparen){
throw game::wml_syntax_error(tokens_, start_pos - tokens_.begin(), _("of missing paren in the formula should be $( ...)")); }
// Grab and append tokens until we reach the end of the variable name
t_tokens::iterator curr_pos = start_pos + 1; // +1 is skipping the left paren
int paren_nesting_level = 1;
bool in_string = false, in_comment = false;
static const t_token & z_empty( generate_safe_static_const_t_interned(n_token::t_token("")) );
static const t_operation_ptr op_empty(new t_operation_push(z_empty));
complete_parse_.ops().push_back(op_empty);
for(;curr_pos != tokens_.end(); ++curr_pos){
//() Nesting
if(*curr_pos == z_lparen){
static const t_operation_ptr op(new t_operation_append(z_lparen));
complete_parse_.ops().push_back(op);
if(!in_string && !in_comment) {
++paren_nesting_level; } }
else if(*curr_pos == z_rparen){
if(!in_string && !in_comment) {
--paren_nesting_level; }
if( paren_nesting_level <= 0) { break; }
static const t_operation_ptr op(new t_operation_append(z_rparen));
complete_parse_.ops().push_back(op); }
else if(*curr_pos == z_sharp){
static const t_operation_ptr op(new t_operation_append(z_sharp));
complete_parse_.ops().push_back(op);
if(!in_string ) {
in_comment = !in_comment; }}
else if(*curr_pos == z_single_quote){
static const t_operation_ptr op(new t_operation_append(z_single_quote));
complete_parse_.ops().push_back(op);
if(!in_comment ) {
in_string = !in_string; }}
else if(*curr_pos == z_dollar){
// $| Creates a $ to allow for $ in the string
if( peek_next(curr_pos) == z_bar){
static const t_operation_ptr op(new t_operation_append(z_dollar));
complete_parse_.ops().push_back(op); }
//A Nested interpolation / formula
else{
curr_pos = do_parse_interp(++curr_pos) - 1; } }
else {
t_operation_ptr op(new t_operation_append(*curr_pos));
complete_parse_.ops().push_back(op); }
}
if(paren_nesting_level > 0) {
throw game::wml_syntax_error(tokens_, curr_pos - tokens_.begin(), _(" of missing closing paren")); }
t_operation_ptr op(new t_operation_formula());
complete_parse_.ops().push_back(op);
return ++curr_pos; //skip the closing right paren
}
t_parse_and_interpolator::t_parse_and_interpolator (t_parse_and_interpolator const & a)
: maybe_parsed_(a.maybe_parsed_), complete_parse_(a.complete_parse_), is_done_(a.is_done_){}
t_parse_and_interpolator & t_parse_and_interpolator::operator=(t_parse_and_interpolator const & a) {
maybe_parsed_ = (a.maybe_parsed_); complete_parse_ = a.complete_parse_; is_done_ = a.is_done_; return *this;}
std::ostream & operator<<(std::ostream &out, t_parse_and_interpolator const & a){
out << ((a.is_done_) ? "parsed=" : "unparsed=") << a.maybe_parsed_;
return out; }
//static member
t_parse_and_interpolator::t_all_parsed t_parse_and_interpolator::all_parsed_(t_parse_and_interpolator::t_parser(), CACHE_SIZE);
}

View file

@ -1,452 +0,0 @@
/* $Id$ */
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
Copyright (C) 2005 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
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
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.
*/
#ifndef FORMULA_STRING_UTILS_BACKEND_HPP_INCLUDED
#define FORMULA_STRING_UTILS_BACKEND_HPP_INCLUDED
#include "exceptions.hpp"
#include "formula_string_utils.hpp"
#include "config.hpp"
#include "log.hpp"
#include "formula.hpp"
#include "gettext.hpp"
#include "util.hpp" // for str_cast
#include "foreach.hpp"
#include <time.h>
///todo remove next 1 line
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include "utils/lru_cache.hpp"
static lg::log_domain log_interpolate("interpolate");
#define ERR_INTERP LOG_STREAM(err, log_interpolate)
#define WARN_INTERP LOG_STREAM(warn, log_interpolate)
#define DEBUG_INTERP LOG_STREAM(debug, log_interpolate)
/** @file contains a parser, a code generator and an interpolator to interpolate variables into WMLstrings.
t_tokenizer tokenizes strings into possible variable name components and control characters
t_instructions runs the mini-language that interpolates wml_variables into strings.
t_operations constitutes the mini-language: push, append, interpolate and formula.
t_parse takes a vector of tokens and parses it into a script to do the interpolation
At each step results are cached so that at run-time a given string is only tokenized and parsed into instructions once.
At each interpolation the variable is retrieved and interpolated as necessary.
*/
namespace wml_interpolation {
typedef n_token::t_token t_token;
typedef std::vector<t_token> t_tokens;
static const unsigned int CACHE_SIZE = 10000;
inline bool is_alnum_or_underscore (char c){
return ( (((c) & ~0x7f) == 0)/*isascii(c)*/ && (isalnum(c) || (c == '_'))); }
///Checks if this token could be a part of a variable name
///@pre a has a least 1 character
///assumes that the whole token is characterized by the first character, which is true of
///parsed tokens but might not be true of returned by interpolation tokens
inline bool is_good_for_varname (t_token const & a){
return is_alnum_or_underscore((*a)[0] ) ;}
///Break string/token into relevant tokens
/** @class t_tokenizer breaks strings/tokens into vectors of tokens.
Tokens are either a part of a variable name (alnum or _),
a valid control character $|.[]()'#
or everything else.
*/
class t_tokenizer {
t_tokens tokens_; /// tokens for output
bool is_done_, is_valid_varname_;
std::string input_string_; ///inputs string
size_t curr_pos_, end_, varname_start_;
public:
/** Initialize the tokenizer with a std::string or a t_token
@param[in] in a string/token static_castible to a string
*/
template <typename T> t_tokenizer(T const & in);
/**Binds to a new string and tokenizes the string
@param[in] in a string/token static_castible to a string
*/
template <typename T> t_tokens const & tokenize(T const & in);
///Tokenizes the string
t_tokens const & tokenize();
private:
///Grabs a variable name from the start pos to the current position
void grab_name();
///Process the next character
void process_char();
};
/**@class
Each t_operation is a functor that does 2 things
1. When provided with a token stack and a variable set it performs an operation :
push, append, interpolate (variable) or formula (interpolation).
2. When provided with 2 operations, it returns a single operation that in the same as
the two operations it possible.
*/
struct t_operation;
typedef boost::shared_ptr<t_operation> t_operation_ptr;
typedef std::vector<t_operation_ptr> t_operations;
struct t_operation_noop;
struct t_operation_push;
struct t_operation_append;
struct t_operation_interp;
struct t_operation_formula;
struct t_operation {
virtual ~t_operation() {}
virtual void operator()(t_tokens & /*stack*/, variable_set const & /*variable_set*/) const = 0;
virtual std::string const string() const = 0;
friend std::ostream & operator<<(std::ostream &out, t_operation const & a){
return out << a.string(); }
///t_reduce_result returns either (new_operation,true) on success or (void_op, false)
typedef std::pair<t_operation_ptr, bool> t_reduce_result;
///Takes 2 operations and possibly reduces them to 1
virtual t_reduce_result reduce(t_operation_ptr const & second_op) const = 0;
///Takes 2 operations and possibly reduces them to 1
virtual t_reduce_result reduce_flipped(t_operation_noop const & /*first_op*/) const {
return std::make_pair(void_op_,false); }
virtual t_reduce_result reduce_flipped(t_operation_push const & /*first_op*/) const {
return std::make_pair(void_op_,false); }
virtual t_reduce_result reduce_flipped(t_operation_append const & /*first_op*/) const {
return std::make_pair(void_op_,false); }
virtual t_reduce_result reduce_flipped(t_operation_interp const & /*first_op*/) const {
return std::make_pair(void_op_,false); }
virtual t_reduce_result reduce_flipped(t_operation_formula const & /*first_op*/) const {
return std::make_pair(void_op_,false); }
virtual bool operator==(t_operation_ptr const & second_op) const = 0;
virtual bool operator!=(t_operation_ptr const & second_op) const {
return !(this->operator==(second_op)); }
virtual bool operator==(t_operation_noop const & /*first_op*/) const { return false; }
virtual bool operator==(t_operation_push const & /*first_op*/) const { return false; }
virtual bool operator==(t_operation_append const & /*first_op*/) const { return false; }
virtual bool operator==(t_operation_interp const & /*first_op*/) const { return false; }
virtual bool operator==(t_operation_formula const & /*first_op*/) const { return false; }
private:
static const t_operation_ptr void_op_; ///Operation ptr returned on failure, deferencing will cause a crash
};
///No op
struct t_operation_noop : public t_operation {
virtual void operator()(t_tokens & /*stack*/, variable_set const & /*variable_set*/) const { }
std::string const string() const ;
virtual std::pair<t_operation_ptr, bool> reduce(t_operation_ptr const & second_op) const {
return std::make_pair(second_op, true); }
virtual bool operator==(t_operation_ptr const & second_op) const {
return second_op->operator==(*this); }
virtual bool operator==(t_operation_noop const & /*first_op*/) const { return true; }
};
///@class t_operation_push pushes a token on the stack
class t_operation_push : public t_operation {
t_token x_;
public:
t_operation_push(t_token const & a) : x_(a){}
virtual void operator()(t_tokens & stack, variable_set const & /*variable_set*/) const {
stack.push_back(x_);
DEBUG_INTERP << string() << "\n"; }
t_token const &x() const {return x_;}
std::string const string() const;
virtual t_reduce_result reduce(t_operation_ptr const & second_op) const {
return second_op->reduce_flipped(*this); }
virtual bool operator==(t_operation_ptr const & second_op) const {
return second_op->operator==(*this); }
virtual bool operator==(t_operation_push const & first_op) const { return first_op.x_ == x_; }
};
///@class t_operation_appends appends a token with the top item on the stack. It caches results.
class t_operation_append : public t_operation {
t_token x_;
///@class this functor generates the result to cache in the event of a cache miss
struct t_make_append_result {
t_token operator()(std::pair<t_token, t_token> const & x) const {
return t_token((*x.first) + (*x.second)); }
};
///LRU cache of append operations
typedef n_lru_cache::t_lru_cache<std::pair<t_token, t_token>, t_token, t_make_append_result> t_append_cache;
static t_append_cache cache_;
public:
t_operation_append(t_token const & a) : x_(a){}
///Checks the cache for the append result and replaces the top token on the stack with the result
virtual void operator()(t_tokens & stack, variable_set const & /*variable_set*/) const {
if(!stack.empty()){
t_token const &res = cache_.check(std::make_pair(stack.back(), x_));
if(res != stack.back()){
DEBUG_INTERP << string(res) << "\n";
stack.pop_back();
stack.push_back(res); } }
else {
stack.push_back(x_); }
}
t_token const &x() const {return x_;}
virtual t_reduce_result reduce(t_operation_ptr const & second_op) const {
return second_op->reduce_flipped(*this); }
/// push->append is reduces to a push operation
virtual t_reduce_result reduce_flipped(t_operation_push const & first_op) const {
t_operation_ptr op(new t_operation_push(t_token((*first_op.x())
+ (*x()))));
return std::make_pair(op, true); }
/// append->append is reduces to an append operation
virtual t_reduce_result reduce_flipped(t_operation_append const & first_op) const {
t_operation_ptr op(new t_operation_append(t_token((*first_op.x())
+ (*x()))));
return std::make_pair(op, true); }
virtual bool operator==(t_operation_ptr const & second_op) const {
return second_op->operator==(*this); }
virtual bool operator==(t_operation_append const & first_op) const { return first_op.x_ == x_; }
std::string const string() const ;
private:
std::string const string(std::string const & res) const;
};
/**@class t_operation_interp looksup the top token on the stack in the variable_set
@param[in] variable_set
*/
class t_operation_interp : public t_operation {
public :
///Grab the top item on the stack, look it up in the variable set and append it to the second item on the stack
virtual void operator()(t_tokens & stack, variable_set const & variable_set) const {
t_token var_name(stack.back());
config::attribute_value stuffing(variable_set.get_variable_const(var_name ));
DEBUG_INTERP << string(var_name, stuffing) << "\n";
stack.pop_back();
t_operation_append append(stuffing.token());
append(stack, variable_set);
}
virtual t_reduce_result reduce(t_operation_ptr const & second_op) const {
return second_op->reduce_flipped(*this); }
virtual bool operator==(t_operation_ptr const & second_op) const {
return second_op->operator==(*this); }
virtual bool operator==(t_operation_interp const & /*first_op*/) const { return true; }
std::string const string() const ;
private:
std::string const string(std::string const & var, std::string const & res) const ;
};
struct t_operation_formula : public t_operation {
virtual void operator()(t_tokens & stack, variable_set const & variable_set) const ;
virtual t_reduce_result reduce(t_operation_ptr const & second_op) const {
return second_op->reduce_flipped(*this); }
std::string const string() const ;
virtual bool operator==(t_operation_ptr const & second_op) const {
return second_op->operator==(*this); }
virtual bool operator==(t_operation_formula const & /*first_op*/) const { return true; }
private:
std::string const string(std::string const & var, std::string const & res) const ;
};
/** @class A vector of operations that can be run.
*/
class t_instructions {
t_operations ops_; /// the operations
public:
t_instructions()
: ops_()
{
}
///Optimize the instructions by trying to pairwise reduce the instruction set.
void optimize(t_token const & unparsed) ;
///runs the instructions and places the results in @param[out] x
void run(t_token & x, variable_set const & set) const {
if ( ops_.empty() ) {
//DEBUG_INTERP << "Nothing to interpolate in "<<x<<"\n";
return; }
run_core(x, set);
}
void run_core(t_token & x, variable_set const & set) const ;
t_operations & ops() { return ops_; }
t_operations const & ops() const { return ops_; }
friend std::ostream & operator<<(std::ostream &out, t_instructions const & a);
};
/** @class t_parse parses tokens into instructions to perform the interpolation
*/
struct t_parse {
n_token::t_token token_; ///The input token
t_tokens tokens_; ///Its tokens
t_instructions complete_parse_;
friend std::ostream & operator<<(std::ostream &out, t_parse const & a);
t_parse(n_token::t_token const & unparsed) ;
t_parse(t_parse const & a );
t_parse & operator=(t_parse const & a) ;
///Calculate a parse
t_instructions & parse();
///Peeks at the next token
t_token const & peek_next(t_tokens::iterator const & curr_pos );
///Keep concatenating components until you see a $ which indicates some kind of interpolation
t_tokens::iterator do_parse_plain(t_tokens::iterator const & start_pos );
///Parse the instructions to generate the variable name for interpolation
t_tokens::iterator do_parse_interp(t_tokens::iterator const & start_pos ) ;
/** do_parse formul a parses a formula invoked by $ (...) syntax
*/
t_tokens::iterator do_parse_formula(t_tokens::iterator const & start_pos );
};
/** @class Parses and possibly stores variables for subsequent interpolation */
class t_parse_and_interpolator {
/// @class Generate a parse for an uncached token
struct t_parser {
t_instructions operator()(n_token::t_token const & unparsed){
t_parse aparse(unparsed);
t_instructions instructions(aparse.parse());
instructions.optimize(unparsed);
return instructions;
}
};
/// A Least Recently Used (LRU) cache of previous parse results
///These are independent of the interpolated data
typedef n_lru_cache::t_lru_cache<n_token::t_token, t_instructions, t_parser> t_all_parsed;
static t_all_parsed all_parsed_;
n_token::t_token maybe_parsed_; ///input token and result
t_instructions const * complete_parse_; ///instructions to interpolate this token
bool is_done_;
public:
t_parse_and_interpolator (n_token::t_token const & unparsed)
: maybe_parsed_(unparsed), complete_parse_(NULL), is_done_(false){}
t_parse_and_interpolator (t_parse_and_interpolator const & a);
t_parse_and_interpolator & operator=(t_parse_and_interpolator const & a);
friend std::ostream & operator<<(std::ostream &out, t_parse_and_interpolator const & a);
// {
// out << ((a.is_done_) ? "parsed=" : "unparsed=") << a.maybe_parsed_;
// return out; }
bool valid() const { return complete_parse_ != NULL; }
bool is_done() const { return valid() && is_done_; }
/// The core loop. Parse and Interpolate
/// The parse may be fetched from the cache and the same also with the interpolated result (after variable lookup)
n_token::t_token const & parse_and_interpolate(const variable_set& set) {
parse();
return interpolate(set); }
///Fetch the parsed instructions from the cache
t_parse_and_interpolator & parse(){
complete_parse_ = & all_parsed_.check(maybe_parsed_);
is_done_ = false;
return *this; }
///Run the parsed instructions to do the interpolation.
t_token const & interpolate(const variable_set& set){
assert(complete_parse_);
if(!is_done_){
complete_parse_->run(maybe_parsed_, set); }
return maybe_parsed_; }
};
}
#endif

View file

@ -64,7 +64,7 @@ namespace game_config
default_defeat_music;
namespace images {
n_token::t_token game_title,
std::string game_title,
// orbs and hp/xp bar
moved_orb,
unmoved_orb,
@ -89,9 +89,9 @@ namespace game_config
tod_bright,
tod_dark,
///@todo de-hardcode this
checked_menu = n_token::t_token( "buttons/checkbox-pressed.png"),
unchecked_menu = n_token::t_token( "buttons/checkbox.png"),
wml_menu = n_token::t_token( "buttons/WML-custom.png"),
checked_menu = "buttons/checkbox-pressed.png",
unchecked_menu = "buttons/checkbox.png",
wml_menu = "buttons/WML-custom.png",
level,
ellipsis,
missing;
@ -116,7 +116,7 @@ namespace game_config
std::string foot_teleport_enter;
std::string foot_teleport_exit;
t_team_rgb_range team_rgb_range;
std::map<std::string, color_range > team_rgb_range;
std::map<std::string, t_string > team_rgb_name;
std::map<std::string, std::vector<Uint32> > team_rgb_colors;
@ -182,33 +182,33 @@ namespace game_config
if(const config &i = v.child("images")){
using namespace game_config::images;
game_title = i["game_title"].token();
game_title = i["game_title"].str();
moved_orb = i["moved_orb"].token();
unmoved_orb = i["unmoved_orb"].token();
partmoved_orb = i["partmoved_orb"].token();
enemy_orb = i["enemy_orb"].token();
ally_orb = i["ally_orb"].token();
energy = i["energy"].token();
moved_orb = i["moved_orb"].str();
unmoved_orb = i["unmoved_orb"].str();
partmoved_orb = i["partmoved_orb"].str();
enemy_orb = i["enemy_orb"].str();
ally_orb = i["ally_orb"].str();
energy = i["energy"].str();
flag = i["flag"].token();
flag_icon = i["flag_icon"].token();
flag = i["flag"].str();
flag_icon = i["flag_icon"].str();
terrain_mask = i["terrain_mask"].token();
grid_top = i["grid_top"].token();
grid_bottom = i["grid_bottom"].token();
mouseover = i["mouseover"].token();
selected = i["selected"].token();
editor_brush = i["editor_brush"].token();
unreachable = i["unreachable"].token();
linger = i["linger"].token();
terrain_mask = i["terrain_mask"].str();
grid_top = i["grid_top"].str();
grid_bottom = i["grid_bottom"].str();
mouseover = i["mouseover"].str();
selected = i["selected"].str();
editor_brush = i["editor_brush"].str();
unreachable = i["unreachable"].str();
linger = i["linger"].str();
observer = i["observer"].token();
tod_bright = i["tod_bright"].token();
tod_dark = i["tod_dark"].token();
level = i["level"].token();
ellipsis = i["ellipsis"].token();
missing = i["missing"].token();
observer = i["observer"].str();
tod_bright = i["tod_bright"].str();
tod_dark = i["tod_dark"].str();
level = i["level"].str();
ellipsis = i["ellipsis"].str();
missing = i["missing"].str();
} // images
hp_bar_scaling = v["hp_bar_scaling"].to_double(0.666);
@ -258,17 +258,17 @@ namespace game_config
void add_color_info(const config &v)
{
foreach (const config &teamC, v.child_range("color_range")) {
foreach (const config &teamC, v.child_range("color_range"))
{
const config::attribute_value *a1 = teamC.get("id"),
*a2 = teamC.get("rgb");
if (!a1 || !a2) continue;
std::string const & id = *a1;
config::attribute_value const & idt = *a1;
std::string id = *a1;
std::vector<Uint32> temp = string2rgb(*a2);
team_rgb_range.insert(std::make_pair(n_token::t_token(id), color_range(temp)));
team_rgb_name[id] = teamC["name"].token();
team_rgb_range.insert(std::make_pair(id,color_range(temp)));
team_rgb_name[id] = teamC["name"];
//generate palette of same name;
std::vector<Uint32> tp = palette(team_rgb_range[idt.token()]);
std::vector<Uint32> tp = palette(team_rgb_range[id]);
if (tp.empty()) continue;
team_rgb_colors.insert(std::make_pair(id,tp));
//if this is being used, output log of palette for artists use.
@ -301,9 +301,9 @@ namespace game_config
}
}
const color_range& color_info(const n_token::t_token& name)
const color_range& color_info(const std::string& name)
{
t_team_rgb_range::const_iterator i = team_rgb_range.find(name);
std::map<std::string, color_range>::const_iterator i = team_rgb_range.find(name);
if(i == team_rgb_range.end()) {
try {
team_rgb_range.insert(std::make_pair(name,color_range(string2rgb(name))));

View file

@ -70,7 +70,7 @@ namespace game_config
default_defeat_music;
namespace images {
extern n_token::t_token game_title,
extern std::string game_title,
// orbs and hp/xp bar
moved_orb,
unmoved_orb,
@ -116,8 +116,7 @@ namespace game_config
extern std::vector<std::string> foot_speed_prefix;
extern std::string foot_teleport_enter, foot_teleport_exit;
typedef boost::unordered_map<n_token::t_token, color_range> t_team_rgb_range;
extern t_team_rgb_range team_rgb_range;
extern std::map<std::string, color_range> team_rgb_range;
extern std::map<std::string, t_string> team_rgb_name;
extern std::map<std::string, std::vector<Uint32> > team_rgb_colors;
@ -143,7 +142,7 @@ namespace game_config
void add_color_info(const config& v);
const std::vector<Uint32>& tc_info(const std::string& name);
const color_range& color_info(const n_token::t_token& name);
const color_range& color_info(const std::string& name);
/**
* Return a color corresponding to the value val

View file

@ -510,7 +510,7 @@ bool game_controller::play_multiplayer_mode()
foreach (const config &faction, era_cfg.child_range("multiplayer_side"))
{
if (faction["random_faction"].to_bool()) continue;
const std::string faction_id = faction["id"];
const std::string &faction_id = faction["id"];
if (!faction_choices.empty() &&
std::find(faction_choices.begin(), faction_choices.end(), faction_id) == faction_choices.end())
continue;

View file

@ -90,11 +90,11 @@ game_display::game_display(unit_map& units, CVideo& video, const gamemap& map,
// Inits the flag list and the team colors used by ~TC
flags_.reserve(teams_.size());
std::vector<config::t_token> side_colors;
std::vector<std::string> side_colors;
side_colors.reserve(teams_.size());
for(size_t i = 0; i != teams_.size(); ++i) {
config::t_token side_color = team::get_side_color_index(i+1);
std::string side_color = team::get_side_color_index(i+1);
side_colors.push_back(side_color);
std::string flag = teams_[i].flag();
std::string old_rgb = game_config::flag_rgb;

File diff suppressed because it is too large Load diff

View file

@ -71,12 +71,12 @@ namespace game_events
struct queued_event {
queued_event(const config::t_token& name, const game_events::entity_location& loc1,
queued_event(const std::string& name, const game_events::entity_location& loc1,
const game_events::entity_location& loc2,
const config& data)
: name(name), loc1(loc1), loc2(loc2),data(data) {}
config::t_token name;
std::string name;
game_events::entity_location loc1;
game_events::entity_location loc2;
config data;
@ -87,7 +87,7 @@ namespace game_events
public:
event_handler(const config &cfg, bool is_menu_item = false);
bool matches_name(const config::t_token& name) const;
bool matches_name(const std::string& name) const;
bool disabled() const { return disabled_; }
bool is_menu_item() const { return is_menu_item_; }
@ -110,11 +110,11 @@ namespace game_events
/**
* Runs the action handler associated to @a cmd with parameters @a cfg.
*/
void handle_event_command(const config::t_token &cmd,
void handle_event_command(const std::string &cmd,
const queued_event &event_info, const vconfig &cfg);
void write_events(config& cfg);
void add_events(const config::const_child_itors &cfgs,const config::t_token& id);
void add_events(const config::const_child_itors &cfgs,const std::string& id);
bool unit_matches_filter(const unit &, const vconfig& filter);
@ -136,12 +136,12 @@ namespace game_events
*
* Events may have up to two arguments, both of which must be locations.
*/
bool fire(const config::t_token& event,
bool fire(const std::string& event,
const entity_location& loc1=map_location::null_location,
const entity_location& loc2=map_location::null_location,
const config& data=config());
void raise(const config::t_token& event,
void raise(const std::string& event,
const entity_location& loc1=map_location::null_location,
const entity_location& loc2=map_location::null_location,
const config& data=config());

File diff suppressed because it is too large Load diff

View file

@ -29,7 +29,6 @@
class scoped_wml_variable;
class team;
typedef std::vector<team> t_teams;
class gamemap;
namespace t_translation {
struct t_match;
@ -69,7 +68,7 @@ public:
struct wml_menu_item
{
wml_menu_item(const std::string& id, const config* cfg=NULL);
config::t_token name;
std::string name;
std::string image;
t_string description;
bool needs_select;
@ -102,27 +101,6 @@ public:
void write_config(config_writer& out, bool write_variables=true) const;
// Variable access
//Prefer using token or attribute value interface as it is faster
config::attribute_value &get_variable(const config::t_token &varname);
virtual config::attribute_value get_variable_const(const config::t_token& varname) const;
config& get_variable_cfg(const config::t_token& varname);
void set_variable(const config::t_token& varname, const t_string& value);
config& add_variable_cfg(const config::t_token& varname, const config& value=config());
void clear_variable(const config::t_token& varname);
void clear_variable_cfg(const config::t_token& varname); // Clears only the config children
config::attribute_value &get_variable(const config::attribute_value &varname);
virtual config::attribute_value get_variable_const(const config::attribute_value& varname) const;
config& get_variable_cfg(const config::attribute_value& varname);
void set_variable(const config::attribute_value& varname, const t_string& value);
config& add_variable_cfg(const config::attribute_value& varname, const config& value=config());
void clear_variable(const config::attribute_value& varname);
void clear_variable_cfg(const config::attribute_value& varname); // Clears only the config children
config::attribute_value &get_variable(const std::string &varname);
virtual config::attribute_value get_variable_const(const std::string& varname) const;
@ -149,7 +127,7 @@ public:
//create an object responsible for creating and populating a team from a config
team_builder_ptr create_team_builder(const config& side_cfg, std::string save_id
, t_teams& teams, const config& level, gamemap& map
, std::vector<team>& teams, const config& level, gamemap& map
, unit_map& units, bool snapshot);
//do first stage of team initialization (everything except unit placement)

View file

@ -40,9 +40,9 @@ std::vector<ttip> load(const config& cfg)
std::vector<ttip> result;
foreach(const config &tip, cfg.child_range("tip")) {
result.push_back(ttip(tip["text"].t_str()
, tip["source"].t_str()
, tip["encountered_units"].t_str()));
result.push_back(ttip(tip["text"]
, tip["source"]
, tip["encountered_units"]));
}
return result;

View file

@ -229,7 +229,7 @@ const std::string& twindow_builder::read(const config& cfg)
*/
id_ = cfg["id"].str();
description_ = cfg["description"].t_str();
description_ = cfg["description"].str();
VALIDATE(!id_.empty(), missing_mandatory_wml_key("window", "id"));
VALIDATE(!description_.empty(), missing_mandatory_wml_key("window", "description"));

View file

@ -58,11 +58,8 @@ tbuilder_horizontal_listbox::tbuilder_horizontal_listbox(const config& cfg)
foreach(const config &c, row.child_range("column")) {
list_data.push_back(string_map());
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, c.attribute_range()) {
sorted.insert( ipresorted ); }
foreach (const config::attribute &i, sorted ) {
list_data.back()[i.first] = i.second.t_str();
foreach (const config::attribute &i, c.attribute_range()) {
list_data.back()[i.first] = i.second;
}
++col;
}

View file

@ -71,11 +71,8 @@ tbuilder_listbox::tbuilder_listbox(const config& cfg)
foreach(const config& c, row.child_range("column")) {
list_data.push_back(string_map());
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, c.attribute_range()) {
sorted.insert( ipresorted ); }
foreach(const config::attribute& i, sorted) {
list_data.back()[i.first] = i.second.token();
foreach(const config::attribute& i, c.attribute_range()) {
list_data.back()[i.first] = i.second;
}
++col;
}

View file

@ -51,11 +51,8 @@ tbuilder_multi_page::tbuilder_multi_page(const config& cfg)
foreach(const config &column, row.child_range("column")) {
data.push_back(string_map());
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, column.attribute_range()) {
sorted.insert( ipresorted ); }
foreach(const config::attribute &i, sorted) {
data.back()[i.first] = i.second.token();
foreach(const config::attribute &i, column.attribute_range()) {
data.back()[i.first] = i.second;
}
++col;
}

View file

@ -45,7 +45,7 @@ tbuilder_slider::tbuilder_slider(const config& cfg)
}
foreach(const config& label, labels.child_range("value")) {
value_labels_.push_back(label["label"].t_str());
value_labels_.push_back(label["label"]);
}
}

View file

@ -74,7 +74,7 @@ void taddon_list::pre_show(CVideo& /*video*/, twindow& window)
std::map<std::string, string_map> data;
string_map item;
item["label"] = c["icon"].token();
item["label"] = c["icon"];
data.insert(std::make_pair("icon", item));
std::string tmp = c["name"];
@ -92,10 +92,10 @@ void taddon_list::pre_show(CVideo& /*video*/, twindow& window)
item["label"] = tmp;
data.insert(std::make_pair("author", item));
item["label"] = c["downloads"].token();
item["label"] = c["downloads"];
data.insert(std::make_pair("downloads", item));
item["label"] = c["size"].token();
item["label"] = c["size"];
data.insert(std::make_pair("size", item));
list.add_row(data);

View file

@ -143,10 +143,10 @@ void tcampaign_selection::pre_show(CVideo& /*video*/, twindow& window)
foreach(const config &campaign, campaigns_) {
/*** Add tree item ***/
tree_group_field["label"] = campaign["icon"].token();
tree_group_field["label"] = campaign["icon"];
tree_group_item["icon"] = tree_group_field;
tree_group_field["label"] = campaign["name"].token();
tree_group_field["label"] = campaign["name"];
tree_group_item["name"] = tree_group_field;
if (campaign["completed"].to_bool()) {
@ -161,11 +161,11 @@ void tcampaign_selection::pre_show(CVideo& /*video*/, twindow& window)
string_map detail_item;
std::map<std::string, string_map> detail_page;
detail_item["label"] = campaign["description"].token();
detail_item["label"] = campaign["description"];
detail_item["use_markup"] = "true";
detail_page.insert(std::make_pair("description", detail_item));
detail_item["label"] = campaign["image"].token();
detail_item["label"] = campaign["image"];
detail_page.insert(std::make_pair("image", detail_item));
multi_page.add_page(detail_page);
@ -212,10 +212,10 @@ void tcampaign_selection::pre_show(CVideo& /*video*/, twindow& window)
string_map list_item;
std::map<std::string, string_map> list_item_item;
list_item["label"] = c["icon"].token();
list_item["label"] = c["icon"];
list_item_item.insert(std::make_pair("icon", list_item));
list_item["label"] = c["name"].token();
list_item["label"] = c["name"];
list_item_item.insert(std::make_pair("name", list_item));
list.add_row(list_item_item);
@ -232,11 +232,11 @@ void tcampaign_selection::pre_show(CVideo& /*video*/, twindow& window)
string_map detail_item;
std::map<std::string, string_map> detail_page;
detail_item["label"] = c["description"].token();
detail_item["label"] = c["description"];
detail_item["use_markup"] = "true";
detail_page.insert(std::make_pair("description", detail_item));
detail_item["label"] = c["image"].token();
detail_item["label"] = c["image"];
detail_page.insert(std::make_pair("image", detail_item));
multi_page.add_page(detail_page);

View file

@ -248,7 +248,7 @@ void tgame_load::display_savegame(twindow& window)
}
find_widget<timage>(&window, "imgLeader", false).
set_label(cfg_summary["leader_image"].t_str());
set_label(cfg_summary["leader_image"]);
find_widget<tminimap>(&window, "minimap", false).
set_map_data(cfg_summary["map_data"]);
@ -286,7 +286,7 @@ void tgame_load::evaluate_summary_string(std::stringstream& str
}
utils::string_map symbols;
if (campaign != NULL) {
symbols["campaign_name"] = (*campaign)["name"].token();
symbols["campaign_name"] = (*campaign)["name"];
} else {
// Fallback to nontranslatable campaign id.
symbols["campaign_name"] = "(" + campaign_id + ")";

View file

@ -189,15 +189,12 @@ public:
? resources::state_of_game->get_variables()
: config();
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &i, vars.attribute_range()) {
sorted.insert( i ); }
foreach( const config::attribute &a, sorted) {
foreach( const config::attribute &a, vars.attribute_range()) {
model_.add_row_to_stuff_list(a.first,a.first);
}
foreach( const config::any_child &c, vars.all_children_range()) {
model_.add_row_to_stuff_list("[" + (*c.key)+"]","["+ (*c.key)+"]");
model_.add_row_to_stuff_list("["+c.key+"]","["+c.key+"]");
}
model_.set_inspect_window_text("");
@ -217,10 +214,7 @@ public:
? resources::state_of_game->get_variables()
: config();
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &i, vars.attribute_range()) {
sorted.insert( i ); }
foreach( const config::attribute &a, sorted) {
foreach( const config::attribute &a, vars.attribute_range()) {
if (selected==i) {
model_.set_inspect_window_text(a.second);
return;

View file

@ -193,7 +193,7 @@ game_info::game_info(const config& game, const config& game_config)
{
const config &era_cfg = game_config.find_child("era", "id", game["mp_era"]);
utils::string_map symbols;
symbols["era_id"] = game["mp_era"].token();
symbols["era_id"] = game["mp_era"];
if (era_cfg) {
era = era_cfg["name"].str();
era_short = era_cfg["short_name"].str();
@ -254,10 +254,7 @@ game_info::game_info(const config& game, const config& game_config)
if (const config& hashes = game_config.child("multiplayer_hashes")) {
std::string hash = game["hash"];
bool hash_found = false;
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, hashes.attribute_range()) {
sorted.insert( ipresorted ); }
foreach (const config::attribute &i, sorted) {
foreach (const config::attribute &i, hashes.attribute_range()) {
if (i.first == game["mp_scenario"] && i.second == hash) {
hash_found = true;
break;
@ -273,7 +270,7 @@ game_info::game_info(const config& game, const config& game_config)
}
} else {
utils::string_map symbols;
symbols["scenario_id"] = game["mp_scenario"].token();
symbols["scenario_id"] = game["mp_scenario"];
scenario = vgettext("Unknown scenario: $scenario_id", symbols);
map_info += scenario;
verified = false;
@ -301,7 +298,7 @@ game_info::game_info(const config& game, const config& game_config)
started = false;
if (vacant_slots > 0) {
status = std::string(_n("Vacant Slot:", "Vacant Slots:",
vacant_slots)) + " " + game["slots"].str();
vacant_slots)) + " " + game["slots"];
}
}

View file

@ -86,10 +86,9 @@ std::string dump_games_map(const lobby_info::game_info_map& games)
std::string dump_games_config(const config& gamelist)
{
static const config::t_token & z_diff_track_attribute_( generate_safe_static_const_t_interned(n_token::t_token("diff_track_attribute_")) );
std::stringstream ss;
foreach (const config& c, gamelist.child_range("game")) {
ss << "g" << c["id"] << "(" << c["name"] << ") " << c[z_diff_track_attribute_] << " ";
ss << "g" << c["id"] << "(" << c["name"] << ") " << c[config::diff_track_attribute] << " ";
}
ss << "\n";
return ss.str();
@ -116,7 +115,6 @@ void lobby_info::process_gamelist(const config &data)
bool lobby_info::process_gamelist_diff(const config &data)
{
static const config::t_token & z_diff_track_attribute_( generate_safe_static_const_t_interned(n_token::t_token("diff_track_attribute_")) );
SCOPE_LB;
if (!gamelist_initialized_) return false;
DBG_LB << "prediff " << dump_games_config(gamelist_.child("gamelist"));
@ -133,7 +131,7 @@ bool lobby_info::process_gamelist_diff(const config &data)
config::child_itors range = gamelist_.child("gamelist").child_range("game");
for (config::child_iterator i = range.first; i != range.second; ++i) {
config& c = *i;
DBG_LB << "data process: " << c["id"] << " (" << c[z_diff_track_attribute_] << ")\n";
DBG_LB << "data process: " << c["id"] << " (" << c[config::diff_track_attribute] << ")\n";
int game_id = c["id"];
if (game_id == 0) {
ERR_LB << "game with id 0 in gamelist config\n";
@ -141,7 +139,7 @@ bool lobby_info::process_gamelist_diff(const config &data)
return false;
}
game_info_map::iterator current_i = games_by_id_.find(game_id);
const std::string& diff_result = c[z_diff_track_attribute_];
const std::string& diff_result = c[config::diff_track_attribute];
if (diff_result == "new" || diff_result == "modified") {
if (current_i == games_by_id_.end()) {
games_by_id_.insert(std::make_pair(game_id, new game_info(c, game_config_)));

View file

@ -267,7 +267,7 @@ const std::string& tgui_definition::read(const config& cfg)
* @end{parent}{name="/"}
*/
id = cfg["id"].str();
description = cfg["description"].t_str();
description = cfg["description"];
VALIDATE(!id.empty(), missing_mandatory_wml_key("gui", "id"));
VALIDATE(!description.empty(), missing_mandatory_wml_key("gui", "description"));
@ -394,7 +394,7 @@ const std::string& tgui_definition::read(const config& cfg)
sound_toggle_panel_click_ = settings["sound_toggle_panel_click"].str();
sound_slider_adjust_ = settings["sound_slider_adjust"].str();
has_helptip_message_ = settings["has_helptip_message"].t_str();
has_helptip_message_ = settings["has_helptip_message"];
VALIDATE(!has_helptip_message_.empty(),
missing_mandatory_wml_key("[settings]", "has_helptip_message"));

View file

@ -1132,7 +1132,7 @@ std::vector<topic> generate_weapon_special_topics(const bool sort_generated)
if (!type.hide_help()) {
//add a link in the list of units having this special
std::string type_name = type.type_name();
std::string ref_id = unit_prefix + (* type.id() );
std::string ref_id = unit_prefix + type.id();
//we put the translated name at the beginning of the hyperlink,
//so the automatic alphabetic sorting of std::set can use it
std::string link = "<ref>text='" + escape(type_name) + "' dst='" + escape(ref_id) + "'</ref>";
@ -1180,13 +1180,13 @@ std::vector<topic> generate_ability_topics(const bool sort_generated)
abil_vecs[0] = &type.abilities();
abil_vecs[1] = &type.adv_abilities();
std::vector<t_string> const* desc_vecs[2];
std::vector<std::string> const* desc_vecs[2];
desc_vecs[0] = &type.ability_tooltips();
desc_vecs[1] = &type.adv_ability_tooltips();
for(int i=0; i<2; ++i) {
std::vector<t_string> const& abil_vec = *abil_vecs[i];
std::vector<t_string> const& desc_vec = *desc_vecs[i];
std::vector<std::string> const& desc_vec = *desc_vecs[i];
for(size_t j=0; j < abil_vec.size(); ++j) {
t_string const& abil_name = abil_vec[j];
if (ability_description.find(abil_name) == ability_description.end()) {
@ -1208,7 +1208,7 @@ std::vector<topic> generate_ability_topics(const bool sort_generated)
if (!type.hide_help()) {
//add a link in the list of units having this ability
std::string type_name = type.type_name();
std::string ref_id = unit_prefix + (* type.id() );
std::string ref_id = unit_prefix + type.id();
//we put the translated name at the beginning of the hyperlink,
//so the automatic alphabetic sorting of std::set can use it
std::string link = "<ref>text='" + escape(type_name) + "' dst='" + escape(ref_id) + "'</ref>";
@ -1251,9 +1251,9 @@ std::vector<topic> generate_faction_topics(const bool sort_generated)
std::stringstream text;
const config::attribute_value& description = f["description"];
const std::string& description = f["description"];
if (!description.empty()) {
text << description.t_str() << "\n";
text << description << "\n";
text << "\n";
}
@ -1282,9 +1282,9 @@ std::vector<topic> generate_faction_topics(const bool sort_generated)
std::stringstream text;
text << "<header>text='" << _("Era:") << " " << era["name"] << "'</header>" << "\n";
text << "\n";
const config::attribute_value& description = era["description"];
const std::string& description = era["description"];
if (!description.empty()) {
text << description.t_str() << "\n";
text << description << "\n";
text << "\n";
}
@ -1362,11 +1362,11 @@ public:
const bool first_reverse_value = true;
bool reverse = first_reverse_value;
do {
std::vector<config::t_token> adv_units =
std::vector<std::string> adv_units =
reverse ? type_.advances_from() : type_.advances_to();
bool first = true;
foreach (const config::t_token &adv, adv_units)
foreach (const std::string &adv, adv_units)
{
const unit_type *type = unit_types.find(adv);
if (!type || type->hide_help()) continue;
@ -1383,7 +1383,7 @@ public:
std::string lang_unit = type->type_name();
std::string ref_id;
if (description_type(*type) == FULL_DESCRIPTION) {
ref_id = unit_prefix + (* type->id() );
ref_id = unit_prefix + type->id();
} else {
ref_id = unknown_unit_topic;
lang_unit += " (?)";
@ -1397,7 +1397,7 @@ public:
// Print the race of the unit, cross-reference it to the
// respective topic.
const config::t_token race_id = type_.race();
const std::string race_id = type_.race();
std::string race_name;
if (const unit_race *r = unit_types.find_race(race_id)) {
race_name = r->plural_name();
@ -1405,7 +1405,7 @@ public:
race_name = _ ("race^Miscellaneous");
}
ss << _("Race: ");
ss << "<ref>dst='" << escape("..race_" + (*race_id )) << "' text='" << escape(race_name) << "'</ref>";
ss << "<ref>dst='" << escape("..race_"+race_id) << "' text='" << escape(race_name) << "'</ref>";
ss << "\n";
// Print the abilities the units has, cross-reference them
@ -1480,7 +1480,7 @@ public:
attack_end = attacks.end();
attack_it != attack_end; ++attack_it) {
std::string lang_weapon = attack_it->name();
std::string lang_type = string_table["type_" + (* attack_it->type() )];
std::string lang_type = string_table["type_" + attack_it->type()];
std::vector<item> row;
std::stringstream attack_ss;
attack_ss << "<img>src='" << (*attack_it).icon() << "'</img>";
@ -1492,7 +1492,7 @@ public:
attack_ss << attack_it->damage() << utils::unicode_en_dash << attack_it->num_attacks() << " " << attack_it->accuracy_parry_description();
push_tab_pair(row, attack_ss.str());
attack_ss.str(clear_stringstream);
push_tab_pair(row, string_table["range_" + (* (*attack_it).range() )]);
push_tab_pair(row, string_table["range_" + (*attack_it).range()]);
// Show this attack's special, if it has any. Cross
// reference it to the section describing the
// special.
@ -1662,7 +1662,7 @@ std::string make_unit_link(const std::string& type_id)
std::string name = type->type_name();
std::string ref_id;
if (description_type(*type) == FULL_DESCRIPTION) {
ref_id = unit_prefix + (* type->id() );
ref_id = unit_prefix + type->id();
} else {
ref_id = unknown_unit_topic;
name += " (?)";
@ -1715,7 +1715,7 @@ void generate_races_sections(const config *help_cfg, section &sec, int level)
section_cfg["id"] = hidden_symbol(hidden) + race_prefix + *it;
std::string title;
if (const unit_race *r = unit_types.find_race(config::t_token(*it))) {
if (const unit_race *r = unit_types.find_race(*it)) {
title = r->plural_name();
} else {
title = _ ("race^Miscellaneous");
@ -1740,14 +1740,14 @@ std::vector<topic> generate_unit_topics(const bool sort_generated, const std::st
{
const unit_type &type = i.second;
if (type.race() != config::t_token(race))
if (type.race() != race)
continue;
UNIT_DESCRIPTION_TYPE desc_type = description_type(type);
if (desc_type != FULL_DESCRIPTION)
continue;
const std::string type_name = type.type_name();
const std::string ref_id = hidden_symbol(type.hide_help()) + unit_prefix + (* type.id() );
const std::string ref_id = hidden_symbol(type.hide_help()) + unit_prefix + type.id();
topic unit_topic(type_name, ref_id, "");
unit_topic.text = new unit_topic_generator(type);
topics.push_back(unit_topic);
@ -1764,7 +1764,7 @@ std::vector<topic> generate_unit_topics(const bool sort_generated, const std::st
std::string race_id = "..race_"+race;
std::string race_name;
std::string race_description;
if (const unit_race *r = unit_types.find_race(config::t_token(race))) {
if (const unit_race *r = unit_types.find_race(race)) {
race_name = r->plural_name();
race_description = r->description();
// if (description.empty()) description = _("No description Available");

View file

@ -44,7 +44,6 @@ static lg::log_domain log_display("display");
#define ERR_DP LOG_STREAM(err, log_display)
#define LOG_DP LOG_STREAM(info, log_display)
template<typename T>
struct cache_item
{
@ -119,17 +118,17 @@ image::bool_cache in_hex_info_;
// const int cache_version_ = 0;
boost::unordered_map<n_token::t_token,bool> image_existence_map;
std::map<std::string,bool> image_existence_map;
// directories where we already cached file existence
boost::unordered_set<n_token::t_token> precached_dirs;
std::set<std::string> precached_dirs;
boost::unordered_map<surface, surface> reversed_images_;
std::map<surface, surface> reversed_images_;
int red_adjust = 0, green_adjust = 0, blue_adjust = 0;
/** List of colors used by the TC image modification */
std::vector<n_token::t_token> team_colors;
std::vector<std::string> team_colors;
int zoom = image::tile_size;
int cached_zoom = 0;
@ -173,8 +172,8 @@ void flush_cache()
void locator::init_index()
{
boost::unordered_map<value, int>& finder = locator_finder[hash_value(val_)];
boost::unordered_map<value, int>::iterator i = finder.find(val_);
std::map<value, int>& finder = locator_finder[hash_value(val_)];
std::map<value, int>::iterator i = finder.find(val_);
if(i == finder.end()) {
index_ = last_index_++;
@ -186,7 +185,7 @@ void locator::init_index()
void locator::parse_arguments()
{
std::string const & fn = (*val_.filename_);
std::string& fn = val_.filename_;
if(fn.empty()) {
return;
}
@ -194,24 +193,30 @@ void locator::parse_arguments()
if(markup_field != std::string::npos) {
val_.type_ = SUB_FILE;
val_.modifications_ = n_token::t_token(fn.substr(markup_field, fn.size() - markup_field));
val_.filename_ = n_token::t_token( fn.substr(0,markup_field) );
val_.modifications_ = fn.substr(markup_field, fn.size() - markup_field);
fn = fn.substr(0,markup_field);
}
}
locator::locator() : index_(-1), val_() {}
locator::locator() :
index_(-1),
val_()
{
}
locator::locator(const locator &a, const n_token::t_token& mods):
index_(-1), val_(a.val_) {
locator::locator(const locator &a, const std::string& mods):
index_(-1),
val_(a.val_)
{
if(!mods.empty()){
val_.modifications_ = config::t_token( val_.modifications_ + mods );
val_.type_=SUB_FILE;
init_index();
val_.modifications_ += mods;
val_.type_=SUB_FILE;
init_index();
}
else index_ = a.index_;
else index_=a.index_;
}
locator::locator(const n_token::t_token &filename) :
locator::locator(const char *filename) :
index_(-1),
val_(filename)
{
@ -219,50 +224,31 @@ locator::locator(const n_token::t_token &filename) :
init_index();
}
locator::locator(const n_token::t_token &filename, const n_token::t_token& modifications) :
index_(-1), val_(filename, modifications) {
init_index();
}
locator::locator(const n_token::t_token &filename, const map_location &loc,
int center_x, int center_y, const n_token::t_token& modifications) :
index_(-1), val_(filename, modifications, loc, center_x, center_y) {
init_index();
}
locator::locator(const char *filename) :
index_(-1), val_(n_token::t_token( filename )) {
parse_arguments();
init_index();
}
locator::locator(const std::string & filename) :
index_(-1), val_(n_token::t_token( filename )) {
locator::locator(const std::string &filename) :
index_(-1),
val_(filename)
{
parse_arguments();
init_index();
}
locator::locator(const std::string &filename, const std::string& modifications) :
index_(-1), val_(n_token::t_token( filename), n_token::t_token( modifications)) {
index_(-1),
val_(filename, modifications)
{
init_index();
}
locator::locator(const std::string &filename, const map_location &loc,
int center_x, int center_y, const std::string& modifications) :
index_(-1), val_(n_token::t_token( filename), n_token::t_token( modifications), loc, center_x, center_y) {
int center_x, int center_y, const std::string& modifications) :
index_(-1),
val_(filename, loc, center_x, center_y, modifications)
{
init_index();
}
// locator::locator(const config::t_token &filename, const config::t_token& modifications, const map_location &loc,
// int center_x, int center_y) :
// index_(-1), val_(filename, modifications, loc, center_x, center_y) {
// init_index();
// }
locator& locator::operator=(const locator &a) {
locator& locator::operator=(const locator &a)
{
index_ = a.index_;
val_ = a.val_;
@ -270,29 +256,43 @@ locator& locator::operator=(const locator &a) {
}
locator::value::value(const locator::value& a) :
type_(a.type_), filename_(a.filename_), loc_(a.loc_), modifications_(a.modifications_)
, center_x_(a.center_x_), center_y_(a.center_y_) { }
type_(a.type_), filename_(a.filename_), loc_(a.loc_),
modifications_(a.modifications_),
center_x_(a.center_x_), center_y_(a.center_y_)
{
}
locator::value::value() :
type_(NONE), filename_(), loc_(), modifications_(), center_x_(0), center_y_(0) { }
type_(NONE), filename_(), loc_(), modifications_(),
center_x_(0), center_y_(0)
locator::value::value(const n_token::t_token& filename) :
type_(FILE), filename_(filename), loc_(), modifications_(), center_x_(0), center_y_(0) { }
{}
// locator::value::value(const n_token::t_token& filename, const n_token::t_token& modifications) :
// type_(SUB_FILE), filename_(filename), loc_(), modifications_(modifications),
// center_x_(0), center_y_(0)
locator::value::value(const char *filename) :
type_(FILE), filename_(filename), loc_(), modifications_(),
center_x_(0), center_y_(0)
// {
// }
{
}
// locator::value::value(const n_token::t_token& filename, const map_location& loc, int center_x, int center_y, const n_token::t_token& modifications) :
// type_(SUB_FILE), filename_(filename), loc_(loc), modifications_(modifications), center_x_(center_x), center_y_(center_y)
// {
// }
locator::value::value(const std::string& filename) :
type_(FILE), filename_(filename), loc_(), modifications_(),
center_x_(0), center_y_(0)
locator::value::value(const config::t_token& filename, const config::t_token& modifications, const map_location& loc, int center_x, int center_y) :
type_(SUB_FILE), filename_(filename), loc_(loc), modifications_(modifications), center_x_(center_x), center_y_(center_y) { }
{
}
locator::value::value(const std::string& filename, const std::string& modifications) :
type_(SUB_FILE), filename_(filename), loc_(), modifications_(modifications),
center_x_(0), center_y_(0)
{
}
locator::value::value(const std::string& filename, const map_location& loc, int center_x, int center_y, const std::string& modifications) :
type_(SUB_FILE), filename_(filename), loc_(loc), modifications_(modifications), center_x_(center_x), center_y_(center_y)
{
}
bool locator::value::operator==(const value& a) const
{
@ -349,11 +349,6 @@ size_t hash_value(const locator::value& val) {
return hash;
}
size_t hash_value(const locator& a) {
size_t hash = hash_value(a.val_);
boost::hash_combine(hash, a.index_);
return hash;
}
// Check if localized file is uptodate according to l10n track index.
// Make sure only that the image is not explicitly recorded as fuzzy,
// in order to be able to use non-tracked images (e.g. from UMC).
@ -465,7 +460,7 @@ surface locator::load_image_file() const
if (res.null() && !val_.filename_.empty()) {
ERR_DP << "could not open image '" << val_.filename_ << "'\n";
if (game_config::debug && val_.filename_ != game_config::images::missing)
return get_image(locator(game_config::images::missing), UNSCALED);
return get_image(game_config::images::missing, UNSCALED);
}
return res;
@ -473,7 +468,7 @@ surface locator::load_image_file() const
surface locator::load_image_sub_file() const
{
surface surf = get_image(locator( val_.filename_ ) , UNSCALED);
surface surf = get_image(val_.filename_, UNSCALED);
if(surf == NULL)
return NULL;
@ -578,7 +573,7 @@ void color_adjustment_resetter::reset()
set_color_adjustment(r_, g_, b_);
}
void set_team_colors(const std::vector<n_token::t_token>* colors)
void set_team_colors(const std::vector<std::string>* colors)
{
if (colors == NULL)
team_colors.clear();
@ -587,7 +582,7 @@ void set_team_colors(const std::vector<n_token::t_token>* colors)
}
}
const std::vector<n_token::t_token>& get_team_colors()
const std::vector<std::string>& get_team_colors()
{
return team_colors;
}
@ -827,7 +822,7 @@ surface reverse_image(const surface& surf)
return surface(NULL);
}
const boost::unordered_map<surface,surface>::iterator itor = reversed_images_.find(surf);
const std::map<surface,surface>::iterator itor = reversed_images_.find(surf);
if(itor != reversed_images_.end()) {
// sdl_add_ref(itor->second);
return itor->second;
@ -851,7 +846,7 @@ bool exists(const image::locator& i_locator)
return false;
// The insertion will fail if there is already an element in the cache
std::pair< boost::unordered_map< n_token::t_token, bool >::iterator, bool >
std::pair< std::map< std::string, bool >::iterator, bool >
it = image_existence_map.insert(std::make_pair(i_locator.get_filename(), false));
bool &cache = it.first->second;
if (it.second)
@ -859,9 +854,9 @@ bool exists(const image::locator& i_locator)
return cache;
}
static void precache_file_existence_internal(const n_token::t_token& dir, const n_token::t_token& subdir)
static void precache_file_existence_internal(const std::string& dir, const std::string& subdir)
{
const n_token::t_token checked_dir = n_token::t_token((*dir) + "/" + (*subdir));
const std::string checked_dir = dir + "/" + subdir;
if (precached_dirs.find(checked_dir) != precached_dirs.end())
return;
precached_dirs.insert(checked_dir);
@ -873,16 +868,16 @@ static void precache_file_existence_internal(const n_token::t_token& dir, const
for(std::vector<std::string>::const_iterator f = files_found.begin();
f != files_found.end(); ++f) {
image_existence_map[n_token::t_token(subdir + *f)] = true;
image_existence_map[subdir + *f] = true;
}
for(std::vector<std::string>::const_iterator d = dirs_found.begin();
d != dirs_found.end(); ++d) {
precache_file_existence_internal(dir, n_token::t_token( subdir + *d + "/" ));
precache_file_existence_internal(dir, subdir + *d + "/");
}
}
void precache_file_existence(const n_token::t_token& subdir)
void precache_file_existence(const std::string& subdir)
{
const std::vector<std::string>& paths = get_binary_paths("images");
@ -890,13 +885,13 @@ void precache_file_existence(const n_token::t_token& subdir)
p != paths.end(); ++p) {
const std::string dir = *p + "/" + subdir;
precache_file_existence_internal(n_token::t_token( *p ), subdir);
precache_file_existence_internal(*p, subdir);
}
}
bool precached_file_exists(const n_token::t_token& file)
bool precached_file_exists(const std::string& file)
{
boost::unordered_map<n_token::t_token, bool>::const_iterator b = image_existence_map.find(file);
std::map<std::string, bool>::const_iterator b = image_existence_map.find(file);
if (b != image_existence_map.end())
return b->second;
else

View file

@ -16,12 +16,10 @@
#ifndef IMAGE_HPP_INCLUDED
#define IMAGE_HPP_INCLUDED
#include "token.hpp"
#include "map_location.hpp"
#include "sdl_utils.hpp"
#include "terrain_translation.hpp"
///this module manages the cache of images. With an image name, you can get
///the surface corresponding to that image.
//
@ -44,45 +42,40 @@ namespace image {
struct value {
value();
value(const value &a);
explicit value(const n_token::t_token& filename);
// value(const n_token::t_token& filename, const n_token::t_token& modifications);
// value(const n_token::t_token& filename, const map_location& loc, int center_x, int center_y, const n_token::t_token& modifications);
value(const n_token::t_token& filename, const n_token::t_token& modifications
, const map_location& loc = map_location::null_location, int center_x=0, int center_y=0);
value(const char *filename);
value(const std::string& filename);
value(const std::string& filename, const std::string& modifications);
value(const std::string& filename, const map_location& loc, int center_x, int center_y, const std::string& modifications);
bool operator==(const value& a) const;
bool operator<(const value& a) const;
type type_;
n_token::t_token filename_;
std::string filename_;
map_location loc_;
n_token::t_token modifications_;
std::string modifications_;
int center_x_;
int center_y_;
};
friend size_t hash_value(const value&);
friend size_t hash_value(const locator&);
public:
typedef boost::unordered_map<size_t, boost::unordered_map<value, int> > locator_finder_t;
/**
* @todo replace this with std::unordered_map<value, int> or boost::unordered_map<value, int>
* boost::unordered_map can almost just be dropped in as boost::hash<T>(T val) will return hash_value(val), but it
* requires boost 1.35 (preferably 1.36 or later)
*
**/
typedef std::map<size_t, std::map<value, int> > locator_finder_t;
// Constructing locators is somewhat slow, accessing image
// through locators is fast. The idea is that calling functions
// should store locators, and not strings to construct locators
// (the second will work, of course, but will be slower)
locator();
locator(const locator &a, const n_token::t_token &mods = n_token::t_token::z_empty());
// locator(const locator &a, const std::string &mods ="");
locator(const n_token::t_token& filename);
locator(const n_token::t_token& filename, const n_token::t_token& modifications);
locator(const n_token::t_token& filename, const map_location& loc, int center_x, int center_y
, const n_token::t_token& modifications=n_token::t_token::z_empty());
locator();
locator(const locator &a, const std::string &mods ="");
locator(const char *filename);
locator(const std::string& filename);
locator(const std::string& filename, const std::string& modifications);
@ -93,11 +86,11 @@ namespace image {
bool operator!=(const locator &a) const { return index_ != a.index_; }
bool operator<(const locator &a) const { return index_ < a.index_; }
const n_token::t_token &get_filename() const { return val_.filename_; }
const std::string &get_filename() const { return val_.filename_; }
const map_location& get_loc() const { return val_.loc_ ; }
int get_center_x() const { return val_.center_x_; }
int get_center_y() const { return val_.center_y_; }
const n_token::t_token& get_modifications() const {return val_.modifications_;}
const std::string& get_modifications() const {return val_.modifications_;}
type get_type() const { return val_.type_; };
// const int get_index() const { return index_; };
@ -137,12 +130,11 @@ namespace image {
};
size_t hash_value(const locator::value&);
size_t hash_value(const locator& );
typedef cache_type<surface> image_cache;
typedef cache_type<bool> bool_cache;
typedef boost::unordered_map<t_translation::t_terrain, surface> mini_terrain_cache_map;
typedef std::map<t_translation::t_terrain, surface> mini_terrain_cache_map;
extern mini_terrain_cache_map mini_terrain_cache;
extern mini_terrain_cache_map mini_fogged_terrain_cache;
@ -174,9 +166,9 @@ namespace image {
///set the team colors used by the TC image modification
///use a vector with one string for each team
///using NULL will reset to default TC
void set_team_colors(const std::vector<n_token::t_token>* colors = NULL);
void set_team_colors(const std::vector<std::string>* colors = NULL);
const std::vector<n_token::t_token>& get_team_colors();
const std::vector<std::string>& get_team_colors();
///sets the pixel format used by the images. Is called every time the
///video mode changes. Invalidates all images.
@ -216,8 +208,8 @@ namespace image {
bool exists(const locator& i_locator);
/// precache the existence of files in the subdir (ex: "terrain/")
void precache_file_existence(const n_token::t_token& subdir = n_token::t_token::z_empty());
bool precached_file_exists(const n_token::t_token& file);
void precache_file_existence(const std::string& subdir = "");
bool precached_file_exists(const std::string& file);
}
#endif

View file

@ -401,7 +401,7 @@ REGISTER_MOD_PARSER(TC, args)
std::map<Uint32, Uint32> rc_map;
try {
color_range const& new_color =
game_config::color_info(n_token::t_token(team_color));
game_config::color_info(team_color);
std::vector<Uint32> const& old_color =
game_config::tc_info(params[1]);
@ -422,7 +422,7 @@ REGISTER_MOD_PARSER(TC, args)
// Team-color-based color range selection and recoloring
REGISTER_MOD_PARSER(RC, args)
{
const std::vector<config::t_token> recolor_params = utils::split_token(n_token::t_token(args), '>');
const std::vector<std::string> recolor_params = utils::split(args,'>');
if(recolor_params.size()>1){
//

View file

@ -104,8 +104,8 @@ bool load_language_list()
foreach (const config &lang, cfg.child_range("locale"))
{
known_languages.push_back(
language_def(lang["locale"].str(), lang["name"].t_str(), lang["dir"].str(),
lang["alternates"].str(), lang["sort_name"].str()));
language_def(lang["locale"], lang["name"], lang["dir"],
lang["alternates"], lang["sort_name"]));
}
return true;
@ -228,12 +228,9 @@ bool load_strings(bool complain)
}
foreach (const config &lang, languages_) {
DBG_G << "[language]\n";
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, lang.attribute_range()) {
sorted.insert( ipresorted ); }
foreach (const config::attribute &j, sorted) {
foreach (const config::attribute &j, lang.attribute_range()) {
DBG_G << j.first << "=\"" << j.second << "\"\n";
strings_[j.first] = j.second.token();
strings_[j.first] = j.second;
}
DBG_G << "[/language]\n";
}
@ -288,8 +285,8 @@ void init_textdomains(const config& cfg)
{
foreach (const config &t, cfg.child_range("textdomain"))
{
const std::string name = t["name"];
const std::string path = t["path"];
const std::string &name = t["name"];
const std::string &path = t["path"];
if(path.empty()) {
t_string::add_textdomain(name, get_intl_dir());

View file

@ -144,11 +144,11 @@ void leader_list_manager::update_gender_list(const std::string& leader)
// Make the internationalized titles for each gender, along with the WML ids
if (*i == unit_race::FEMALE) {
gender_ids_.push_back("female");
genders_.push_back(IMAGE_PREFIX + (* utg.image() ) + get_RC_suffix(utg.flag_rgb()) +
genders_.push_back(IMAGE_PREFIX + utg.image() + get_RC_suffix(utg.flag_rgb()) +
COLUMN_SEPARATOR + _("Female ♀"));
} else {
gender_ids_.push_back("male");
genders_.push_back(IMAGE_PREFIX + (* utg.image() ) + get_RC_suffix(utg.flag_rgb()) +
genders_.push_back(IMAGE_PREFIX + utg.image() + get_RC_suffix(utg.flag_rgb()) +
COLUMN_SEPARATOR + _("Male ♂"));
}
}
@ -180,8 +180,8 @@ void leader_list_manager::populate_leader_combo(int selected_index) {
if (gender_combo_ != NULL && !genders_.empty() && size_t(gender_combo_->selected()) < genders_.size()) {
gender = gender_ids_[gender_combo_->selected()];
}
const unit_type& ut = utp->get_gender_unit_type(config::t_token(gender));
leader_strings.push_back(IMAGE_PREFIX + (*ut.image()) + get_RC_suffix(ut.flag_rgb()) + COLUMN_SEPARATOR + ut.type_name());
const unit_type& ut = utp->get_gender_unit_type(gender);
leader_strings.push_back(IMAGE_PREFIX + ut.image() + get_RC_suffix(ut.flag_rgb()) + COLUMN_SEPARATOR + ut.type_name());
} else {
if(*itor == "random") {

View file

@ -310,7 +310,7 @@ void terrain_label::read(const config &cfg)
std::string tmp_color = cfg["color"];
text_ = cfg["text"].token();
text_ = cfg["text"];
team_name_ = cfg["team_name"].str();
visible_in_fog_ = cfg["visible_in_fog"].to_bool(true);
visible_in_shroud_ = cfg["visible_in_shroud"].to_bool();

View file

@ -402,7 +402,7 @@ std::vector<map_location> parse_location_range(const std::string &x, const std::
return res;
}
void write_location_range(const map_location::t_maploc_set& locs, config& cfg)
void write_location_range(const std::set<map_location>& locs, config& cfg)
{
if(locs.empty()){
cfg["x"] = "";
@ -414,7 +414,7 @@ void write_location_range(const map_location::t_maploc_set& locs, config& cfg)
assert(map_location(0,1) < map_location(1,0));
std::stringstream x, y;
map_location::t_maploc_set::const_iterator
std::set<map_location>::const_iterator
i = locs.begin(),
first = i,
last = i;

View file

@ -24,7 +24,6 @@ class variable_set;
#include <string>
#include <vector>
#include <set>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#define MAX_MAP_AREA 65536
@ -51,7 +50,6 @@ struct map_location {
static std::vector<DIRECTION> parse_directions(const std::string& str);
static std::string write_direction(DIRECTION dir);
typedef boost::unordered_set<map_location> t_maploc_set;
map_location() : x(-1000), y(-1000) {}
map_location(int x, int y) : x(x), y(y) {}
map_location(const config& cfg, const variable_set *variables);
@ -129,7 +127,7 @@ std::vector<map_location> parse_location_range(const std::string& xvals,
* Write a set of locations into a config using ranges,
* adding keys x=x1,..,xn and y=y1a-y1b,..,yna-ynb
*/
void write_location_range(const map_location::t_maploc_set& locs, config& cfg);
void write_location_range(const std::set<map_location>& locs, config& cfg);
/** Parse x,y keys of a config into a vector of locations */
void read_locations(const config& cfg, std::vector<map_location>& locs);

View file

@ -535,11 +535,11 @@ static map_location place_village(const t_translation::t_map& map,
tcode_list_cache &adj_liked_cache)
{
const map_location loc(x,y);
map_location::t_maploc_set locs;
std::set<map_location> locs;
get_tiles_radius(loc,radius,locs);
map_location best_loc;
int best_rating = 0;
for(map_location::t_maploc_set::const_iterator i = locs.begin();
for(std::set<map_location>::const_iterator i = locs.begin();
i != locs.end(); ++i) {
if(i->x < 0 || i->y < 0 || i->x >= static_cast<long>(map.size()) ||
@ -593,7 +593,7 @@ static std::string generate_name(const unit_race& name_generator, const std::str
if(options.empty() == false) {
const size_t choice = rand()%options.size();
LOG_NG << "calling name generator...\n";
const std::string name = name_generator.generate_name(unit_race::MALE);
const std::string& name = name_generator.generate_name(unit_race::MALE);
LOG_NG << "name generator returned '" << name << "'\n";
if(base_name != NULL) {
*base_name = name;
@ -829,7 +829,7 @@ std::string default_generate_map(size_t width, size_t height, size_t island_size
if(river.empty() == false && labels != NULL) {
std::string base_name;
LOG_NG << "generating name for river...\n";
const std::string name = generate_name(name_generator,"river_name",&base_name);
const std::string& name = generate_name(name_generator,"river_name",&base_name);
LOG_NG << "named river '" << name << "'\n";
size_t name_frequency = 20;
for(std::vector<location>::const_iterator r = river.begin(); r != river.end(); ++r) {
@ -1101,7 +1101,7 @@ std::string default_generate_map(size_t width, size_t height, size_t island_size
// '\' will be used if the road is going south east-north west
// The terrain will be left unchanged otherwise
// (if there is no clear direction).
const std::string convert_to_bridge = child["convert_to_bridge"];
const std::string &convert_to_bridge = child["convert_to_bridge"];
if(convert_to_bridge.empty() == false) {
if(step == rt.steps.begin() || step+1 == rt.steps.end())
continue;
@ -1152,7 +1152,7 @@ std::string default_generate_map(size_t width, size_t height, size_t island_size
}
// Just a plain terrain substitution for a road
const std::string convert_to = child["convert_to"];
const std::string &convert_to = child["convert_to"];
if(convert_to.empty() == false) {
const t_translation::t_terrain letter =
t_translation::read_terrain_code(convert_to);
@ -1305,7 +1305,7 @@ std::string default_generate_map(size_t width, size_t height, size_t island_size
t_translation::write_terrain_code(terrain[res.x][res.y]);
if (const config &child = cfg.find_child("village", "terrain", str))
{
const std::string convert_to = child["convert_to"];
const std::string &convert_to = child["convert_to"];
if(convert_to != "") {
terrain[res.x][res.y] =
t_translation::read_terrain_code(convert_to);

View file

@ -182,13 +182,10 @@ std::string menu_handler::get_title_suffix(int side_num)
void menu_handler::objectives(int side_num)
{
static const config::t_token & z__from_interface( generate_safe_static_const_t_interned(n_token::t_token("_from_interface")) );
static const config::t_token & z_show_objectives( generate_safe_static_const_t_interned(n_token::t_token("show_objectives")) );
config cfg;
cfg["side"] = str_cast(side_num);
game_events::handle_event_command(z_show_objectives,
game_events::queued_event(z__from_interface, map_location(),
game_events::handle_event_command("show_objectives",
game_events::queued_event("_from_interface", map_location(),
map_location(), config()), vconfig(cfg));
team &current_team = teams_[side_num - 1];
dialogs::show_objectives(level_, current_team.objectives());
@ -2628,10 +2625,7 @@ class console_handler : public map_command_handler<console_handler>, private cha
if (const config &alias_list = preferences::get_alias())
{
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, alias_list.attribute_range()) {
sorted.insert( ipresorted ); }
foreach (const config::attribute &a, sorted) {
foreach (const config::attribute &a, alias_list.attribute_range()) {
register_alias(a.second, a.first);
}
}
@ -3229,7 +3223,7 @@ void console_handler::do_layers() {
terrain_builder& builder = disp.get_builder();
terrain_builder::tile* tile = builder.get_tile(loc);
const n_token::t_token& tod_id = disp.get_time_of_day(loc).id;
const std::string& tod_id = disp.get_time_of_day(loc).id;
terrain_builder::tile::logs tile_logs;
tile->rebuild_cache(tod_id, &tile_logs);
@ -3321,7 +3315,7 @@ void console_handler::do_choose_level() {
int next = 0, nb = 0;
foreach (const config &sc, menu_handler_.game_config_.child_range("scenario"))
{
const std::string id = sc["id"];
const std::string &id = sc["id"];
options.push_back(id);
if (id == menu_handler_.gamestate_.classification().next_scenario)
next = nb;
@ -3334,7 +3328,7 @@ void console_handler::do_choose_level() {
{
if (mp["id"] == scenario)
{
const std::string id = mp["id"];
const std::string &id = mp["id"];
options.push_back(id);
if (id == menu_handler_.gamestate_.classification().next_scenario)
next = nb;
@ -3608,7 +3602,7 @@ void console_handler::do_gold() {
menu_handler_.gui_->redraw_everything();
}
void console_handler::do_event() {
game_events::fire(config::t_token(get_data()));
game_events::fire(get_data());
menu_handler_.gui_->redraw_everything();
}
void console_handler::do_toggle_draw_coordinates() {

View file

@ -611,11 +611,13 @@ void mouse_handler::select_hex(const map_location& hex, const bool browse) {
gui().set_route(NULL);
// selection have impact only if we are not observing and it's our unit
if (!browse && !commands_disabled && u->side() == gui().viewing_side()) {
sound::play_UI_sound("select-unit.wav");
u->set_selecting();
static const config::t_token & z_select( generate_safe_static_const_t_interned(n_token::t_token("select")) );
game_events::fire(z_select, hex);
if ((!commands_disabled || resources::whiteboard->is_active()) && u->side() == gui().viewing_side()) {
if (!(browse || resources::whiteboard->unit_has_actions(&*u)))
{
sound::play_UI_sound("select-unit.wav");
u->set_selecting();
game_events::fire("select", hex);
}
}
} else {

View file

@ -168,7 +168,7 @@ connect::side::side(connect& parent, const config& cfg, int index) :
team_ = itor - parent_->team_names_.begin();
}
if (cfg.has_attribute("color")) {
color_ = game_config::color_info(cfg["color"].token()).index() - 1;
color_ = game_config::color_info(cfg["color"]).index() - 1;
}
llm_.set_color(color_);
@ -205,7 +205,7 @@ connect::side::side(connect& parent, const config& cfg, int index) :
if (!leader_name) {
leader_name_pseudolist.push_back("-");
} else {
leader_name_pseudolist.push_back(leader_name->get_gender_unit_type(config::t_token(gender_)).type_name());
leader_name_pseudolist.push_back(leader_name->get_gender_unit_type(gender_).type_name());
}
}
combo_leader_.set_items(leader_name_pseudolist);
@ -641,7 +641,7 @@ config connect::side::get_config() const
if (allow_player_) {
const config &ai_cfg = ai::configuration::get_ai_config_for(ai_algorithm_);
res.add_child("ai",ai_cfg);
symbols["playername"] = ai_cfg["description"].token();
symbols["playername"] = ai_cfg["description"];
} else { // do not import default ai cfg here - all is set by scenario config
symbols["playername"] = _("Computer Player");
}
@ -668,9 +668,9 @@ config connect::side::get_config() const
}
res["user_description"] = t_string(description, "wesnoth");
} else {
res["player_id"] = player_id_ + res["side"].str();
res["player_id"] = player_id_ + res["side"];
if (enabled_ && !cfg_.has_attribute("save_id")) {
res["save_id"] = player_id_ + res["side"].str();
res["save_id"] = player_id_ + res["side"];
}
res["user_description"] = player_id_;
@ -963,7 +963,7 @@ void connect::side::resolve_random()
leader_ = types[lchoice];
} else {
utils::string_map i18n_symbols;
i18n_symbols["faction"] = fact["name"].token();
i18n_symbols["faction"] = fact["name"];
throw config::error(vgettext("Unable to find a leader type for faction $faction", i18n_symbols));
}
}
@ -1373,7 +1373,7 @@ void connect::process_network_data(const config& data, const network::connection
if (const config &c = data.child("observer"))
{
const config::attribute_value &observer_name = c["name"];
const t_string &observer_name = c["name"];
if(!observer_name.empty()) {
connected_user_list::iterator player = find_player(observer_name);
if(player == users_.end()) {
@ -1386,7 +1386,7 @@ void connect::process_network_data(const config& data, const network::connection
}
if (const config &c = data.child("observer_quit"))
{
const config::attribute_value &observer_name = c["name"];
const t_string &observer_name = c["name"];
if(!observer_name.empty()) {
connected_user_list::iterator player = find_player(observer_name);
if(player != users_.end() && find_player_side(observer_name) == -1) {
@ -1641,7 +1641,7 @@ void connect::load_game()
if (params_.random_start_time)
{
if (!tod_manager::is_start_ToD(level_["random_start_time"].token()))
if (!tod_manager::is_start_ToD(level_["random_start_time"]))
{
level_["random_start_time"] = true;
}

View file

@ -435,7 +435,7 @@ void gamebrowser::set_game_items(const config& cfg, const config& game_config)
{
const config &era_cfg = game_config.find_child("era", "id", game["mp_era"]);
utils::string_map symbols;
symbols["era_id"] = game["mp_era"].token();
symbols["era_id"] = game["mp_era"];
if (era_cfg) {
games_.back().map_info = era_cfg["name"].str();
} else {
@ -502,10 +502,7 @@ void gamebrowser::set_game_items(const config& cfg, const config& game_config)
if (map_hashes_ && !games_.back().reloaded) {
std::string hash = game["hash"];
bool hash_found = false;
std::map<config::t_token, config::attribute_value> sorted;
foreach (const config::attribute &ipresorted, map_hashes_.attribute_range()) {
sorted.insert( ipresorted ); }
foreach (const config::attribute &i, sorted) {
foreach (const config::attribute &i, map_hashes_.attribute_range()) {
if (i.first == game["mp_scenario"] && i.second == hash) {
hash_found = true;
break;
@ -519,7 +516,7 @@ void gamebrowser::set_game_items(const config& cfg, const config& game_config)
}
} else {
utils::string_map symbols;
symbols["scenario_id"] = game["mp_scenario"].token();
symbols["scenario_id"] = game["mp_scenario"];
games_.back().map_info += vgettext("Unknown scenario: $scenario_id", symbols);
verified = false;
}

View file

@ -99,7 +99,7 @@ void wait::leader_preview_pane::draw_contents()
const unit_type *ut = unit_types.find(leader);
if (ut) {
const unit_type &utg = ut->get_gender_unit_type(config::t_token(gender));
const unit_type &utg = ut->get_gender_unit_type(gender);
image = utg.image() + leaders_.get_RC_suffix(utg.flag_rgb());
}
@ -270,9 +270,9 @@ void wait::join_game(bool observe)
}
int color = side_num;
const config::attribute_value color_str = (*side_choice)["color"];
const std::string color_str = (*side_choice)["color"];
if (!color_str.empty())
color = game_config::color_info(color_str.token()).index() - 1;
color = game_config::color_info(color_str).index() - 1;
std::vector<const config *> leader_sides;
foreach (const config &side, possible_sides) {
@ -290,8 +290,8 @@ void wait::join_game(bool observe)
foreach (const config *s, leader_sides)
{
const config &side = *s;
const std::string name = side["name"];
const std::string icon = side["image"];
const std::string &name = side["name"];
const std::string &icon = side["image"];
if (!icon.empty()) {
std::string rgb = side["flag_rgb"];
@ -451,7 +451,7 @@ void wait::generate_menu()
std::string description = sd["user_description"];
const std::string faction_id = sd["player_id"];
config::attribute_value side_name = sd["faction_name"];
t_string side_name = sd["faction_name"];
std::string leader_type = sd["type"];
std::string gender_id = sd["gender"];
@ -475,7 +475,7 @@ void wait::generate_menu()
const unit_type *ut = unit_types.find(leader_type);
if (ut) {
const unit_type &utg = ut->get_gender_unit_type(config::t_token(gender_id));
const unit_type &utg = ut->get_gender_unit_type(gender_id);
leader_name = utg.type_name();
#ifdef LOW_MEM
@ -485,7 +485,7 @@ void wait::generate_menu()
if (RCcolor.empty())
RCcolor = sd["side"].str();
leader_image = (*utg.image()) + "~RC(" + (*utg.flag_rgb()) + ">" + RCcolor + ")";
leader_image = utg.image() + std::string("~RC(") + std::string(utg.flag_rgb() + ">" + RCcolor + ")");
#endif
} else {
leader_image = leader_list_manager::random_enemy_picture;
@ -496,7 +496,7 @@ void wait::generate_menu()
if(side_name.str()[0] == font::IMAGE) {
std::string::size_type p =
side_name.str().find_first_of(COLUMN_SEPARATOR);
if(p != std::string::npos && p < side_name.str().size()) {
if(p != std::string::npos && p < side_name.size()) {
side_name = IMAGE_PREFIX + leader_image + COLUMN_SEPARATOR + side_name.str().substr(p+1);
}
} else {
@ -530,7 +530,7 @@ void wait::generate_menu()
int disp_color = sd["color"];
if(!sd["color"].empty()) {
try {
disp_color = game_config::color_info(sd["color"].token()).index();
disp_color = game_config::color_info(sd["color"]).index();
} catch(config::error&) {
//ignore
}

View file

@ -86,10 +86,10 @@ struct node {
if (teleports && !teleports->empty()) {
double new_srch = 1.0;
map_location::t_maploc_set sources;
std::set<map_location> sources;
teleports->get_sources(sources);
map_location::t_maploc_set::const_iterator it = sources.begin();
std::set<map_location>::const_iterator it = sources.begin();
for(; it != sources.end(); ++it) {
const double tmp_srch = heuristic(c, *it);
if (tmp_srch < new_srch) { new_srch = tmp_srch; }
@ -97,7 +97,7 @@ struct node {
double new_dsth = 1.0;
map_location::t_maploc_set targets;
std::set<map_location> targets;
teleports->get_targets(targets);
for(it = targets.begin(); it != targets.end(); ++it) {
@ -192,7 +192,7 @@ pathfind::plain_route pathfind::a_star_search(const map_location& src, const map
int i;
if (teleports && !teleports->empty()) {
map_location::t_maploc_set allowed_teleports;
std::set<map_location> allowed_teleports;
teleports->get_adjacents(allowed_teleports, n.curr);
i = allowed_teleports.size() +6;

View file

@ -206,7 +206,7 @@ static void find_routes(const gamemap& map, const unit_map& /*units*/,
pq.pop_back();
n.in = search_counter;
map_location::t_maploc_set allowed_teleports;
std::set<map_location> allowed_teleports;
teleports.get_adjacents(allowed_teleports, n.curr);
std::vector<map_location> locs(6 + allowed_teleports.size());
std::copy(allowed_teleports.begin(), allowed_teleports.end(), locs.begin() + 6);

View file

@ -125,7 +125,7 @@ pathfind::teleport_map::teleport_map(
}
std::string teleport_id = group.get_teleport_id();
map_location::t_maploc_set::iterator source_it = locations.first.begin();
std::set<map_location>::iterator source_it = locations.first.begin();
for (; source_it != locations.first.end(); ++source_it ) {
if(teleport_map_.count(*source_it) == 0) {
std::set<std::string> id_set;
@ -140,7 +140,7 @@ pathfind::teleport_map::teleport_map(
}
}
void pathfind::teleport_map::get_adjacents(map_location::t_maploc_set& adjacents, map_location loc) const {
void pathfind::teleport_map::get_adjacents(std::set<map_location>& adjacents, map_location loc) const {
if (teleport_map_.count(loc) == 0) {
return;
@ -148,23 +148,23 @@ void pathfind::teleport_map::get_adjacents(map_location::t_maploc_set& adjacents
const std::set<std::string>& keyset = (teleport_map_.find(loc)->second);
for(std::set<std::string>::const_iterator it = keyset.begin(); it != keyset.end(); ++it) {
const map_location::t_maploc_set& target = targets_.find(*it)->second;
const std::set<map_location>& target = targets_.find(*it)->second;
adjacents.insert(target.begin(), target.end());
}
}
}
void pathfind::teleport_map::get_sources(map_location::t_maploc_set& sources) const {
void pathfind::teleport_map::get_sources(std::set<map_location>& sources) const {
std::map<std::string, map_location::t_maploc_set >::const_iterator it;
std::map<std::string, std::set<map_location> >::const_iterator it;
for(it = sources_.begin(); it != sources_.end(); ++it) {
sources.insert(it->second.begin(), it->second.end());
}
}
void pathfind::teleport_map::get_targets(map_location::t_maploc_set& targets) const {
void pathfind::teleport_map::get_targets(std::set<map_location>& targets) const {
std::map<std::string, map_location::t_maploc_set >::const_iterator it;
std::map<std::string, std::set<map_location> >::const_iterator it;
for(it = targets_.begin(); it != targets_.end(); ++it) {
targets.insert(it->second.begin(), it->second.end());
}

View file

@ -26,7 +26,7 @@
namespace pathfind {
typedef std::pair<map_location::t_maploc_set, map_location::t_maploc_set >
typedef std::pair<std::set<map_location>, std::set<map_location> >
teleport_pair;
/*
@ -108,15 +108,15 @@ public:
* @param adjacents used to return the adjacent hexes
* @param loc the map location for which we want to know the adjacent hexes
*/
void get_adjacents(map_location::t_maploc_set& adjacents, map_location loc) const;
void get_adjacents(std::set<map_location>& adjacents, map_location loc) const;
/*
* @param sources used to return the locations that are an entrance of the tunnel
*/
void get_sources(map_location::t_maploc_set& sources) const;
void get_sources(std::set<map_location>& sources) const;
/*
* @param targets used to return the locations that are an exit of the tunnel
*/
void get_targets(map_location::t_maploc_set& targets) const;
void get_targets(std::set<map_location>& targets) const;
/*
* @returns whether the teleport_map does contain any defined tunnel
@ -127,8 +127,8 @@ public:
private:
std::map<map_location, std::set<std::string> > teleport_map_;
std::map<std::string, map_location::t_maploc_set > sources_;
std::map<std::string, map_location::t_maploc_set > targets_;
std::map<std::string, std::set<map_location> > sources_;
std::map<std::string, std::set<map_location> > targets_;
};
/*

View file

@ -23,7 +23,6 @@
#include "pathutils.hpp"
#include "map.hpp"
#include <boost/unordered_map.hpp>
void get_tile_ring(const map_location& a, const int r, std::vector<map_location>& res)
{
@ -50,7 +49,7 @@ void get_tiles_in_radius(const map_location& a, const int r, std::vector<map_loc
}
static void get_tiles_radius_internal(const map_location& a, size_t radius,
map_location::t_maploc_set& res, boost::unordered_map<map_location,int>& visited)
std::set<map_location>& res, std::map<map_location,int>& visited)
{
visited[a] = radius;
res.insert(a);
@ -69,16 +68,16 @@ static void get_tiles_radius_internal(const map_location& a, size_t radius,
}
void get_tiles_radius(const map_location& a, size_t radius,
map_location::t_maploc_set& res)
std::set<map_location>& res)
{
boost::unordered_map<map_location,int> visited;
std::map<map_location,int> visited;
get_tiles_radius_internal(a,radius,res,visited);
}
void get_tiles_radius(gamemap const &map, std::vector<map_location> const &locs,
size_t radius, map_location::t_maploc_set &res, xy_pred *pred)
size_t radius, std::set<map_location> &res, xy_pred *pred)
{
typedef map_location::t_maploc_set location_set;
typedef std::set<map_location> location_set;
location_set not_visited(locs.begin(), locs.end()), must_visit, filtered_out;
++radius;

View file

@ -37,11 +37,12 @@ protected:
};
/** Function which, given a location, will find all tiles within 'radius' of that tile */
void get_tiles_radius(const map_location& a, size_t radius, map_location::t_maploc_set& res);
void get_tiles_radius(const map_location& a, size_t radius,
std::set<map_location>& res);
/** Function which, given a set of locations, will find all tiles within 'radius' of those tiles */
void get_tiles_radius(const gamemap& map, const std::vector<map_location>& locs, size_t radius,
map_location::t_maploc_set& res, xy_pred *pred=NULL);
std::set<map_location>& res, xy_pred *pred=NULL);
/**
* Function which, given a location, will place all locations in the radius of r in res

View file

@ -149,7 +149,7 @@ config persist_file_context::get_var(const std::string &global) const
for (size_t i = 0; i < arrsize; i++)
ret.add_child(global,cfg.child(global,i));
} else {
ret = pack_scalar(global,cfg[global].t_str());
ret = pack_scalar(global,cfg[global]);
}
} else {
ret = pack_scalar(global,"");

View file

@ -80,23 +80,13 @@ public:
{
}
name_space(std::string const &ns, bool doParse = false)
name_space(const std::string &ns, bool doParse = false)
: namespace_(ns)
, root_()
, node_()
, lineage_()
, descendants_()
, valid_(false)
{ construct_core(doParse); }
name_space(config::t_token const &ns, bool doParse = false)
: namespace_((*ns))
, root_()
, node_()
, lineage_()
, descendants_()
, valid_(false)
{ construct_core(doParse); }
void construct_core(bool doParse)
{
if (doParse)
parse();

View file

@ -59,7 +59,7 @@ static void get_global_variable(persist_context &ctx, const vconfig &pcfg)
if (cfg) {
size_t arrsize = cfg.child_count(global);
if (arrsize == 0) {
resources::state_of_game->set_variable(local,cfg[global].t_str());
resources::state_of_game->set_variable(local,cfg[global]);
} else {
resources::state_of_game->clear_variable(local);
for (size_t i = 0; i < arrsize; i++)
@ -87,7 +87,7 @@ static void set_global_variable(persist_context &ctx, const vconfig &pcfg)
const config &vars = resources::state_of_game->get_variables();
size_t arraylen = vars.child_count(local);
if (arraylen == 0) {
val = pack_scalar(global,resources::state_of_game->get_variable(local).t_str());
val = pack_scalar(global,resources::state_of_game->get_variable(local));
} else {
for (size_t i = 0; i < arraylen; i++)
val.add_child(global,vars.child(local,i));

View file

@ -196,7 +196,7 @@ void play_controller::init(CVideo& video){
std::string save_id = get_unique_saveid(side, seen_save_ids);
seen_save_ids.insert(save_id);
if (first_human_team_ == -1) {
const std::string controller = side["controller"];
const std::string &controller = side["controller"];
if (controller == preferences::client_type() &&
side["id"] == preferences::login()) {
first_human_team_ = team_num;
@ -271,9 +271,7 @@ void play_controller::init(CVideo& video){
init_managers();
// add era events for MP game
if (const config &era_cfg = level_.child("era")) {
static const config::t_token & z_era_events( generate_safe_static_const_t_interned(n_token::t_token("era_events")) );
game_events::add_events(era_cfg.child_range("event"), z_era_events);
game_events::add_events(era_cfg.child_range("event"), "era_events");
}
loadscreen::global_loadscreen->start_stage("start game");
@ -508,16 +506,14 @@ void play_controller::fire_prestart(bool execute)
// Run initialization scripts, even if loading from a snapshot.
resources::state_of_game->set_phase(game_state::PRELOAD);
resources::lua_kernel->initialize();
static const config::t_token & z_preload( generate_safe_static_const_t_interned(n_token::t_token("preload")) );
game_events::fire(z_preload);
game_events::fire("preload");
// pre-start events must be executed before any GUI operation,
// as those may cause the display to be refreshed.
if (execute){
update_locker lock_display(gui_->video());
resources::state_of_game->set_phase(game_state::PRESTART);
static const config::t_token & z_prestart( generate_safe_static_const_t_interned(n_token::t_token("prestart")) );
game_events::fire(z_prestart);
game_events::fire("prestart");
check_end_level();
// prestart event may modify start turn with WML, reflect any changes.
start_turn_ = turn();
@ -527,8 +523,7 @@ void play_controller::fire_prestart(bool execute)
void play_controller::fire_start(bool execute){
if(execute) {
resources::state_of_game->set_phase(game_state::START);
static const config::t_token & z_start( generate_safe_static_const_t_interned(n_token::t_token("start")) );
game_events::fire(z_start);
game_events::fire("start");
check_end_level();
// start event may modify start turn with WML, reflect any changes.
start_turn_ = turn();
@ -590,17 +585,15 @@ void play_controller::do_init_side(const unsigned int team_index, bool is_replay
if (!loading_game_) {
if(it_is_a_new_turn_)
{
static const config::t_token & z_new_turn( generate_safe_static_const_t_interned(n_token::t_token("new turn")) );
game_events::fire(config::t_token("turn " + turn_num));
game_events::fire(z_new_turn);
game_events::fire("turn " + turn_num);
game_events::fire("new turn");
it_is_a_new_turn_ = false;
}
static const config::t_token & z_side_turn( generate_safe_static_const_t_interned(n_token::t_token("side turn")) );
game_events::fire(z_side_turn);
game_events::fire(config::t_token("side " + side_num + " turn"));
game_events::fire(config::t_token("side turn " + turn_num));
game_events::fire(config::t_token("side " + side_num + " turn " + turn_num));
game_events::fire("side turn");
game_events::fire("side " + side_num + " turn");
game_events::fire("side turn " + turn_num);
game_events::fire("side " + side_num + " turn " + turn_num);
}
if(current_team.is_human() && !is_replay) {
@ -635,12 +628,10 @@ void play_controller::do_init_side(const unsigned int team_index, bool is_replay
}
if (!loading_game_) {
static const config::t_token & z_turn_refresh( generate_safe_static_const_t_interned(n_token::t_token("turn refresh")) );
game_events::fire(z_turn_refresh);
game_events::fire(config::t_token( "side " + side_num + " turn refresh" ));
game_events::fire(config::t_token( "turn " + turn_num + " refresh"));
game_events::fire(config::t_token( "side " + side_num + " turn " + turn_num + " refresh"));
game_events::fire("turn refresh");
game_events::fire("side " + side_num + " turn refresh");
game_events::fire("turn " + turn_num + " refresh");
game_events::fire("side " + side_num + " turn " + turn_num + " refresh");
}
const time_of_day &tod = tod_manager_.get_time_of_day();
@ -721,11 +712,10 @@ void play_controller::finish_side_turn(){
const std::string turn_num = str_cast(turn());
const std::string side_num = str_cast(player_number_);
static const config::t_token & z_side_turn_end( generate_safe_static_const_t_interned(n_token::t_token("side turn end")) );
game_events::fire(z_side_turn_end);
game_events::fire(config::t_token( "side "+ side_num + " turn end"));
game_events::fire(config::t_token( "side turn " + turn_num + " end"));
game_events::fire(config::t_token( "side " + side_num + " turn " + turn_num + " end"));
game_events::fire("side turn end");
game_events::fire("side "+ side_num + " turn end");
game_events::fire("side turn " + turn_num + " end");
game_events::fire("side " + side_num + " turn " + turn_num + " end");
// This implements "delayed map sharing."
// It is meant as an alternative to shared vision.
@ -743,9 +733,8 @@ void play_controller::finish_turn()
{
const std::string turn_num = str_cast(turn());
const std::string side_num = str_cast(player_number_);
static const config::t_token & z_turn_end( generate_safe_static_const_t_interned(n_token::t_token("turn end")) );
game_events::fire(z_turn_end);
game_events::fire(config::t_token( "turn " + turn_num + " end"));
game_events::fire("turn end");
game_events::fire("turn " + turn_num + " end");
}
bool play_controller::enemies_visible() const
@ -1323,8 +1312,7 @@ void play_controller::check_victory()
}
if (found_player) {
static const config::t_token & z_enemies_defeated( generate_safe_static_const_t_interned(n_token::t_token("enemies defeated")) );
game_events::fire(z_enemies_defeated);
game_events::fire("enemies defeated");
check_end_level();
}

View file

@ -455,16 +455,13 @@ LEVEL_RESULT playsingle_controller::play_scenario(
}
}
static const config::t_token & z_defeat( generate_safe_static_const_t_interned(n_token::t_token("defeat")) );
static const config::t_token & z_victory( generate_safe_static_const_t_interned(n_token::t_token("victory")) );
if (end_level_result == QUIT) {
return QUIT;
}
else if (end_level_result == DEFEAT)
{
gamestate_.classification().completion = "defeat";
game_events::fire(z_defeat);
game_events::fire("defeat");
if (!obs) {
const std::string& defeat_music = select_defeat_music();
@ -480,7 +477,7 @@ LEVEL_RESULT playsingle_controller::play_scenario(
{
gamestate_.classification().completion =
!end_level.linger_mode ? "running" : "victory";
game_events::fire(z_victory);
game_events::fire("victory");
//
// Play victory music once all victory events
@ -866,13 +863,12 @@ void playsingle_controller::handle_generic_event(const std::string& name){
}
void playsingle_controller::check_time_over(){
static const config::t_token & z_time_over( generate_safe_static_const_t_interned(n_token::t_token("time over")) );
bool b = tod_manager_.next_turn();
it_is_a_new_turn_ = true;
if(!b) {
LOG_NG << "firing time over event...\n";
game_events::fire(z_time_over);
game_events::fire("time over");
LOG_NG << "done firing time over event...\n";
//if turns are added while handling 'time over' event
if (tod_manager_.is_time_left()) {

View file

@ -147,8 +147,8 @@ turn_info::PROCESS_DATA_RESULT turn_info::process_network_data(const config& cfg
const int side = lexical_cast<int>(change["side"]);
const size_t index = static_cast<size_t>(side-1);
const std::string controller = change["controller"];
const std::string player = change["player"];
const std::string &controller = change["controller"];
const std::string &player = change["player"];
if(index < resources::teams->size()) {
team &tm = (*resources::teams)[index];

View file

@ -26,18 +26,6 @@
#include "random.hpp"
#include "simple_rng.hpp"
namespace {
DEFAULT_TOKEN_BODY(zf_trait, "trait")
DEFAULT_TOKEN_BODY(zf_topic, "topic")
DEFAULT_TOKEN_BODY(zf_id, "id")
DEFAULT_TOKEN_BODY(zf_plural_name, "plural_name")
DEFAULT_TOKEN_BODY(zf_description, "description")
DEFAULT_TOKEN_BODY(zf_num_traits, "num_traits")
DEFAULT_TOKEN_BODY(zf_markov_chain_size, "markov_chain_size")
DEFAULT_TOKEN_BODY(zf_ignore_global_traits, "ignore_global_traits")
}
static const config &empty_traits() {
static config cfg;
return cfg;
@ -58,12 +46,12 @@ static void add_prefixes(const wide_string& str, size_t length, markov_prefix_ma
}
}
static markov_prefix_map markov_prefixes(const std::vector<config::t_token>& items, size_t length)
static markov_prefix_map markov_prefixes(const std::vector<std::string>& items, size_t length)
{
markov_prefix_map res;
for(std::vector<config::t_token>::const_iterator i = items.begin(); i != items.end(); ++i) {
add_prefixes(utils::string_to_wstring( (**i) ),length,res);
for(std::vector<std::string>::const_iterator i = items.begin(); i != items.end(); ++i) {
add_prefixes(utils::string_to_wstring(*i),length,res);
}
return res;
@ -156,68 +144,56 @@ unit_race::unit_race() :
description_(),
ntraits_(0),
chain_size_(0),
traits_(empty_traits().child_range(zf_trait())),
topics_(empty_topics().child_range(zf_topic())),
traits_(empty_traits().child_range("trait")),
topics_(empty_topics().child_range("topic")),
global_traits_(true)
{
static const n_token::t_token & z_empty( generate_safe_static_const_t_interned(n_token::t_token("empty")) );
name_[MALE] = z_empty;
name_[FEMALE] = z_empty;
name_[MALE] = "";
name_[FEMALE] = "";
}
unit_race::unit_race(const config& cfg) :
cfg_(cfg),
id_(cfg[zf_id()].token()),
plural_name_(cfg[zf_plural_name()].t_str()),
description_(cfg[zf_description()].t_str()),
ntraits_(cfg[zf_num_traits()]),
chain_size_(cfg[zf_markov_chain_size()]),
traits_(cfg.child_range(zf_trait())),
topics_(cfg.child_range(zf_topic())),
global_traits_(!cfg[zf_ignore_global_traits()].to_bool())
id_(cfg["id"]),
plural_name_(cfg["plural_name"].t_str()),
description_(cfg["description"].t_str()),
ntraits_(cfg["num_traits"]),
chain_size_(cfg["markov_chain_size"]),
traits_(cfg.child_range("trait")),
topics_(cfg.child_range("topic")),
global_traits_(!cfg["ignore_global_traits"].to_bool())
{
static const config::t_token & z_name( generate_safe_static_const_t_interned(n_token::t_token("name")) );
static const config::t_token & z_male_name( generate_safe_static_const_t_interned(n_token::t_token("male_name")) );
static const config::t_token & z_female_name( generate_safe_static_const_t_interned(n_token::t_token("female_name")) );
static const config::t_token & z_male_names( generate_safe_static_const_t_interned(n_token::t_token("male_names")) );
static const config::t_token & z_female_names( generate_safe_static_const_t_interned(n_token::t_token("female_names")) );
config::attribute_value const & a_name= cfg[z_name];
config::attribute_value const & a_male_name= cfg[z_male_name];
config::attribute_value const & a_female_name= cfg[z_female_name];
if (id_.empty()) {
lg::wml_error << "[race] '" << a_name << "' is missing an id field.";
lg::wml_error << "[race] '" << cfg["name"] << "' is missing an id field.";
}
if (plural_name_.empty()) {
lg::wml_error << "[race] '" << a_name << "' is missing a plural_name field.";
plural_name_ = (a_name.t_str());
lg::wml_error << "[race] '" << cfg["name"] << "' is missing a plural_name field.";
plural_name_ = (cfg["name"]);
}
// use z_name if z_male_name or z_female_name aren't available
name_[MALE] = a_male_name;
// use "name" if "male_name" or "female_name" aren't available
name_[MALE] = cfg["male_name"];
if(name_[MALE].empty()) {
name_[MALE] = a_name;
name_[MALE] = (cfg["name"]);
}
name_[FEMALE] = a_female_name;
name_[FEMALE] = cfg["female_name"];
if(name_[FEMALE].empty()) {
name_[FEMALE] = a_name;
name_[FEMALE] = (cfg["name"]);
}
if(chain_size_ <= 0)
chain_size_ = 2;
//std::vector<std::string> names = ;
next_[MALE] = markov_prefixes(utils::split_attr(cfg[z_male_names]), chain_size_);
next_[FEMALE] = markov_prefixes(utils::split_attr(cfg[z_female_names]), chain_size_);
next_[MALE] = markov_prefixes(utils::split(cfg["male_names"]), chain_size_);
next_[FEMALE] = markov_prefixes(utils::split(cfg["female_names"]), chain_size_);
}
config::t_token unit_race::generate_name(
std::string unit_race::generate_name(
unit_race::GENDER gender, rand_rng::simple_rng* rng) const
{
return config::t_token(utils::wstring_to_string(markov_generate_name(next_[gender], chain_size_, 12, rng)) );
return utils::wstring_to_string(
markov_generate_name(next_[gender], chain_size_, 12, rng));
}
bool unit_race::uses_global_traits() const
@ -237,20 +213,19 @@ const config::const_child_itors &unit_race::additional_topics() const
unsigned int unit_race::num_traits() const { return ntraits_; }
config::t_token const& gender_string(unit_race::GENDER gender) {
static const config::t_token & z_female_string( generate_safe_static_const_t_interned(n_token::t_token("female")) );
static const config::t_token & z_male_string( generate_safe_static_const_t_interned(n_token::t_token("male")) );
std::string const& gender_string(unit_race::GENDER gender) {
static const std::string female_string = "female";
static const std::string male_string = "male";
switch(gender) {
case unit_race::FEMALE:
return z_female_string;
return female_string;
default:
case unit_race::MALE:
return z_male_string;
return male_string;
}
}
unit_race::GENDER string_gender(const config::t_token& str, unit_race::GENDER def) {
unit_race::GENDER string_gender(const std::string& str, unit_race::GENDER def) {
if(str == gender_string(unit_race::MALE)) {
return unit_race::MALE;
} else if(str == gender_string(unit_race::FEMALE)) {

View file

@ -35,23 +35,23 @@ public:
unit_race(const config& cfg);
const config& get_cfg() const { return cfg_; };
const config::t_token& id() const { return id_; };
const std::string& id() const { return id_; };
const t_string& name(GENDER gender=MALE) const { return name_[gender]; };
const t_string& plural_name() const { return plural_name_; };
const t_string& description() const { return description_; };
config::t_token generate_name(GENDER gender, rand_rng::simple_rng* rng = 0) const;
std::string generate_name(GENDER gender, rand_rng::simple_rng* rng = 0) const;
bool uses_global_traits() const;
const config::const_child_itors &additional_traits() const;
const config::const_child_itors &additional_topics() const;
const config::const_child_itors &additional_topics() const;
unsigned int num_traits() const;
private:
const config cfg_;
config::t_token id_;
std::string id_;
t_string name_[NUM_GENDERS];
t_string plural_name_;
t_string description_;
@ -60,13 +60,13 @@ private:
int chain_size_;
config::const_child_itors traits_;
config::const_child_itors topics_;
config::const_child_itors topics_;
bool global_traits_;
};
unit_race::GENDER string_gender(const config::t_token& str,unit_race::GENDER def=unit_race::MALE);
config::t_token const& gender_string(unit_race::GENDER gender);
unit_race::GENDER string_gender(const std::string& str,unit_race::GENDER def=unit_race::MALE);
std::string const& gender_string(unit_race::GENDER gender);
typedef boost::unordered_map<config::t_token,unit_race> race_map;
typedef std::map<std::string,unit_race> race_map;
#endif

View file

@ -55,7 +55,6 @@ static lg::log_domain log_random("random");
#define ERR_RND LOG_STREAM(err, log_random)
//functions to verify that the unit structure on both machines is identical
static void verify(const unit_map& units, const config& cfg) {
@ -750,13 +749,12 @@ bool do_replay(int side_num, replay *obj)
bool do_replay_handle(int side_num, const std::string &do_untill)
{
static const config::t_token & z_sighted( generate_safe_static_const_t_interned(n_token::t_token("sighted")) );
//a list of units that have promoted from the last attack
std::deque<map_location> advancing_units;
team &current_team = (*resources::teams)[side_num - 1];
for(;;) {
const config *cfg = get_replay_source().get_next_action();
@ -821,9 +819,9 @@ bool do_replay_handle(int side_num, const std::string &do_untill)
}
else if (const config &child = cfg->child("speak"))
{
const std::string team_name = child["team_name"];
const std::string speaker_name = child["id"];
const std::string message = child["message"];
const std::string &team_name = child["team_name"];
const std::string &speaker_name = child["id"];
const std::string &message = child["message"];
//if (!preferences::parse_should_show_lobby_join(speaker_name, message)) return;
bool is_whisper = (speaker_name.find("whisper: ") == 0);
get_replay_source().add_chat_message_location();
@ -851,7 +849,7 @@ bool do_replay_handle(int side_num, const std::string &do_untill)
else if (const config &child = cfg->child("rename"))
{
const map_location loc(child, resources::state_of_game);
const std::string name = child["name"];
const std::string &name = child["name"];
unit_map::iterator u = resources::units->find(loc);
if (u.valid()) {
@ -1028,7 +1026,7 @@ bool do_replay_handle(int side_num, const std::string &do_untill)
bool show_move = preferences::show_ai_moves() || !(current_team.is_ai() || current_team.is_network_ai());
::move_unit(NULL, steps, NULL, NULL, show_move, NULL, true, true, true);
//NOTE: The AI fire sighted event whem moving in the FoV of team 1
//NOTE: The AI fire sighetd event whem moving in the FoV of team 1
// (supposed to be the human player in SP)
// That's ugly but let's try to make the replay works like that too
if (side_num != 1 && resources::teams->front().fog_or_shroud() && !resources::teams->front().fogged(dst)
@ -1036,7 +1034,7 @@ bool do_replay_handle(int side_num, const std::string &do_untill)
{
// the second parameter is impossible to know
// and the AI doesn't use it too in the local version
game_events::fire(z_sighted,dst);
game_events::fire("sighted",dst);
}
}
@ -1123,13 +1121,13 @@ bool do_replay_handle(int side_num, const std::string &do_untill)
else if (const config &child = cfg->child("fire_event"))
{
foreach (const config &v, child.child_range("set_variable")) {
resources::state_of_game->set_variable(v["name"], v["value"].t_str());
resources::state_of_game->set_variable(v["name"], v["value"]);
}
const config::attribute_value &event = child["raise"];
const std::string &event = child["raise"];
if (const config &source = child.child("source")) {
game_events::fire(event.token(), map_location(source, resources::state_of_game));
game_events::fire(event, map_location(source, resources::state_of_game));
} else {
game_events::fire(event.token());
game_events::fire(event);
}
}

View file

@ -253,7 +253,7 @@ void replay_controller::reset_replay(){
// Add era events for MP game.
if (const config &era_cfg = level_.child("era")) {
game_events::add_events(era_cfg.child_range("event"), config::t_token("era_events"));
game_events::add_events(era_cfg.child_range("event"), "era_events");
}
fire_prestart(true);

View file

@ -37,7 +37,6 @@
#include <cassert>
#include <ctime>
static void add_text(config &report, const std::string &text,
const std::string &tooltip, const std::string &help = "")
{
@ -163,7 +162,7 @@ static config unit_type(unit* u)
str << span_color(font::unit_type_color) << u->type_name() << naps;
tooltip << _("Type: ") << "<b>" << u->type_name() << "</b>\n"
<< u->unit_description();
return text_report(str.str(), tooltip.str(), "unit_" + (* u->type_id()));
return text_report(str.str(), tooltip.str(), "unit_" + u->type_id());
}
REPORT_GENERATOR(unit_type)
{
@ -182,7 +181,7 @@ static config unit_race(unit* u)
std::ostringstream str, tooltip;
str << span_color(font::race_color) << u->race()->name(u->gender()) << naps;
tooltip << _("Race: ") << "<b>" << u->race()->name(u->gender()) << "</b>";
return text_report(str.str(), tooltip.str(), "..race_" + (* u->race()->id()));
return text_report(str.str(), tooltip.str(), "..race_" + u->race()->id());
}
REPORT_GENERATOR(unit_race)
{
@ -224,7 +223,7 @@ static config unit_level(unit* u)
std::ostringstream str, tooltip;
str << u->level();
tooltip << _("Level: ") << "<b>" << u->level() << "</b>\n";
const std::vector<config::t_token> &adv_to = u->advances_to();
const std::vector<std::string> &adv_to = u->advances_to();
if (adv_to.empty())
tooltip << _("No advancement");
else
@ -347,16 +346,16 @@ static config unit_abilities(unit* u)
{
if (!u) return report();
config res;
const std::vector<t_string> &abilities = u->ability_tooltips();
for (std::vector<t_string>::const_iterator i = abilities.begin(),
const std::vector<std::string> &abilities = u->ability_tooltips();
for (std::vector<std::string>::const_iterator i = abilities.begin(),
i_end = abilities.end(); i != i_end; ++i)
{
std::ostringstream str, tooltip;
const std::string &name = i->base_str();
str << i->str();
const std::string &name = *i;
str << gettext(name.c_str());
if (i + 2 != i_end) str << ", ";
++i;
tooltip << _("Ability: ") << i->str();
tooltip << _("Ability: ") << *i;
add_text(res, str.str(), tooltip.str(), "ability_" + name);
}
return res;
@ -548,10 +547,6 @@ REPORT_GENERATOR(selected_unit_moves)
static int attack_info(const attack_type &at, config &res, unit *u, const map_location &displayed_unit_hex)
{
static const config::t_token & z_swarm( generate_safe_static_const_t_interned(n_token::t_token("swarm")) );
static const config::t_token & z_swarm_attacks_min( generate_safe_static_const_t_interned(n_token::t_token("swarm_attacks_min")) );
static const config::t_token & z_swarm_attacks_max( generate_safe_static_const_t_interned(n_token::t_token("swarm_attacks_max")) );
std::ostringstream str, tooltip;
at.set_specials_context(displayed_unit_hex, map_location(), *u);
@ -571,16 +566,15 @@ static int attack_info(const attack_type &at, config &res, unit *u, const map_lo
int base_nattacks = at.num_attacks();
int nattacks = base_nattacks;
unit_ability_list swarm = at.get_specials(z_swarm);
unit_ability_list swarm = at.get_specials("swarm");
if (!swarm.empty())
{
int swarm_max_attacks = swarm.highest(z_swarm_attacks_max, nattacks).first;
int swarm_min_attacks = swarm.highest(z_swarm_attacks_min).first;
int swarm_max_attacks = swarm.highest("swarm_attacks_max", nattacks).first;
int swarm_min_attacks = swarm.highest("swarm_attacks_min").first;
int hitp = u->hitpoints();
int mhitp = u->max_hitpoints();
nattacks = swarm_min_attacks + (swarm_max_attacks - swarm_min_attacks) * hitp / mhitp;
}
SDL_Color dmg_color = font::weapon_color;
double dmg_bonus = double(damage) / base_damage;
if (dmg_bonus > 1.0)
@ -619,8 +613,8 @@ static int attack_info(const attack_type &at, config &res, unit *u, const map_lo
add_text(res, flush(str), flush(tooltip));
std::string range = string_table["range_" + (* at.range())];
std::string lang_type = string_table["type_" + (* at.type() )];
std::string range = string_table["range_" + at.range()];
std::string lang_type = string_table["type_" + at.type()];
str << span_color(font::weapon_details_color) << " "
<< range << font::weapon_details_sep

View file

@ -24,7 +24,6 @@ class game_state;
class LuaKernel;
class play_controller;
class team;
typedef std::vector<team> t_teams;
class tod_manager;
class unit_map;
class persist_manager;

View file

@ -126,7 +126,6 @@ static lg::log_domain log_engine("engine");
}
#endif /* _WIN32 */
namespace savegame {
const std::string save_info::format_time_local() const{
@ -353,27 +352,26 @@ void manager::delete_game(const std::string& name)
remove((get_saves_dir() + "/" + modified_name).c_str());
}
bool save_index::save_index_loaded = false;
config save_index::save_index_cfg;
config& save_index::load() {
static bool save_index_loaded = false;
//Intentionally not paired with a delete for static initialization purposes
static config * save_index_cfg = new config;
config& save_index::load()
{
if(save_index_loaded == false) {
try {
scoped_istream stream = istream_file(get_save_index_file());
read(*save_index_cfg, *stream);
read(save_index_cfg, *stream);
} catch(io_exception& e) {
ERR_SAVE << "error reading save index: '" << e.what() << "'\n";
} catch(config::error&) {
ERR_SAVE << "error parsing save index config file\n";
save_index_cfg->clear();
save_index_cfg.clear();
}
//Only try once
save_index_loaded = true;
}
return *save_index_cfg;
return save_index_cfg;
}
config& save_index::save_summary(std::string save)
@ -383,51 +381,16 @@ config& save_index::save_summary(std::string save)
* a file. If not some parts of the code use the name with and some parts
* without the .gz suffix.
*/
static const config::t_token & z_save( generate_safe_static_const_t_interned(n_token::t_token("save")) );
if(save.length() < 3 || save.substr(save.length() - 3) != ".gz") {
save += ".gz";
}
config& cfg = load();
if (config &sv = cfg.find_child(z_save, z_save, save))
if (config &sv = cfg.find_child("save", "save", save))
return sv;
config &res = cfg.add_child(z_save);
res[z_save] = save;
return res;
}
config::t_child_range_index const save_index::indexed_summaries(){
static const config::t_token & z_save( generate_safe_static_const_t_interned(n_token::t_token("save")) );
return load().child_range_index(z_save, z_save);
}
n_token::t_token save_index::gz_corrected_filename(n_token::t_token const & name) {
/*
* All saves are .gz files now so make sure we use that name when opening
* a file. If not some parts of the code use the name with and some parts
* without the .gz suffix.
*/
std::string sname(name);
if(sname.length() < 3 || sname.substr(sname.length() - 3) != ".gz") {
sname += ".gz"; }
return config::t_token(sname);
}
config & save_index::find_or_create_summary(config::t_child_range_index & index, n_token::t_token const & name) {
static const config::t_token & z_save( generate_safe_static_const_t_interned(n_token::t_token("save")) );
config::t_token iname(gz_corrected_filename(name));
config::t_child_range_index::iterator xcfgi = index.find( iname);
if(xcfgi != index.end()){
return *xcfgi->second; }
//Fallback create an empty summary
config & cfg = load();
config &res = cfg.add_child(z_save);
res[z_save] = iname;
config &res = cfg.add_child("save");
res["save"] = save;
return res;
}
@ -1042,7 +1005,7 @@ void autosave_savegame::create_filename()
if (gamestate().classification().label.empty())
filename = _("Auto-Save");
else
filename = gamestate().classification().label + "-" + _("Auto-Save") + snapshot()["turn_at"].str();
filename = gamestate().classification().label + "-" + _("Auto-Save") + snapshot()["turn_at"];
set_filename(filename);
}

Some files were not shown because too many files have changed in this diff Show more