/
abilities.cpp
1207 lines (1082 loc) · 38.4 KB
/
abilities.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2006 - 2018 by Dominic Bolin <dominic.bolin@exong.net>
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.
*/
/**
* @file
* Manage unit-abilities, like heal, cure, and weapon_specials.
*/
#include "display.hpp"
#include "display_context.hpp"
#include "game_board.hpp"
#include "lexical_cast.hpp"
#include "log.hpp"
#include "resources.hpp"
#include "team.hpp"
#include "terrain/filter.hpp"
#include "units/unit.hpp"
#include "units/abilities.hpp"
#include "units/filter.hpp"
#include "units/map.hpp"
#include "filter_context.hpp"
#include "formula/callable_objects.hpp"
#include "formula/formula.hpp"
#include "formula/function_gamestate.hpp"
#include "serialization/string_view.hpp"
#include <boost/dynamic_bitset.hpp>
#include <boost/algorithm/string/predicate.hpp>
static lg::log_domain log_engine("engine");
#define ERR_NG LOG_STREAM(err, log_engine)
namespace {
class temporary_facing
{
map_location::DIRECTION save_dir_;
const unit* u_;
public:
temporary_facing(const unit* u, map_location::DIRECTION new_dir)
: save_dir_(u ? u->facing() : map_location::NDIRECTIONS)
, u_(u)
{
if (u_) {
u_->set_facing(new_dir);
}
}
~temporary_facing()
{
if (u_) {
u_->set_facing(save_dir_);
}
}
};
}
/*
*
* [abilities]
* ...
*
* [heals]
* value=4
* max_value=8
* cumulative=no
* affect_allies=yes
* name= _ "heals"
* female_name= _ "female^heals"
* name_inactive=null
* female_name_inactive=null
* description= _ "Heals:
Allows the unit to heal adjacent friendly units at the beginning of each turn.
A unit cared for by a healer may heal up to 4 HP per turn.
A poisoned unit cannot be cured of its poison by a healer, and must seek the care of a village or a unit that can cure."
* description_inactive=null
*
* affect_self=yes
* [filter] // SUF
* ...
* [/filter]
* [filter_self] // SUF
* ...
* [/filter_self]
* [filter_adjacent] // SUF
* adjacent=n,ne,nw
* ...
* [/filter_adjacent]
* [filter_adjacent_location]
* adjacent=n,ne,nw
* ...
* [/filter_adjacent]
* [affect_adjacent]
* adjacent=n,ne,nw
* [filter] // SUF
* ...
* [/filter]
* [/affect_adjacent]
* [affect_adjacent]
* adjacent=s,se,sw
* [filter] // SUF
* ...
* [/filter]
* [/affect_adjacent]
*
* [/heals]
*
* ...
* [/abilities]
*
*/
namespace {
bool affects_side(const config& cfg, const std::vector<team>& teams, size_t side, size_t other_side)
{
if (side == other_side)
return cfg["affect_allies"].to_bool(true);
if (teams[side - 1].is_enemy(other_side))
return cfg["affect_enemies"].to_bool();
else
return cfg["affect_allies"].to_bool();
}
}
bool unit::get_ability_bool(const std::string& tag_name, const map_location& loc, const display_context& dc) const
{
for (const config &i : this->abilities_.child_range(tag_name)) {
if (ability_active(tag_name, i, loc) &&
ability_affects_self(tag_name, i, loc))
{
return true;
}
}
assert(display::get_singleton());
const unit_map& units = display::get_singleton()->get_units();
adjacent_loc_array_t adjacent;
get_adjacent_tiles(loc,adjacent.data());
for(unsigned i = 0; i < adjacent.size(); ++i) {
const unit_map::const_iterator it = units.find(adjacent[i]);
if (it == units.end() || it->incapacitated())
continue;
// Abilities may be tested at locations other than the unit's current
// location. This is intentional to allow for less messing with the unit
// map during calculations, particularly with regards to movement.
// Thus, we need to make sure the adjacent unit (*it) is not actually
// ourself.
if ( &*it == this )
continue;
for (const config &j : it->abilities_.child_range(tag_name)) {
if (affects_side(j, dc.teams(), side(), it->side()) &&
it->ability_active(tag_name, j, adjacent[i]) &&
ability_affects_adjacent(tag_name, j, i, loc, *it))
{
return true;
}
}
}
return false;
}
unit_ability_list unit::get_abilities(const std::string& tag_name, const map_location& loc) const
{
unit_ability_list res(loc_);
for (const config &i : this->abilities_.child_range(tag_name)) {
if (ability_active(tag_name, i, loc) &&
ability_affects_self(tag_name, i, loc))
{
res.push_back(unit_ability(&i, loc));
}
}
assert(display::get_singleton());
const unit_map& units = display::get_singleton()->get_units();
adjacent_loc_array_t adjacent;
get_adjacent_tiles(loc,adjacent.data());
for(unsigned i = 0; i < adjacent.size(); ++i) {
const unit_map::const_iterator it = units.find(adjacent[i]);
if (it == units.end() || it->incapacitated())
continue;
// Abilities may be tested at locations other than the unit's current
// location. This is intentional to allow for less messing with the unit
// map during calculations, particularly with regards to movement.
// Thus, we need to make sure the adjacent unit (*it) is not actually
// ourself.
if ( &*it == this )
continue;
for (const config &j : it->abilities_.child_range(tag_name)) {
if (affects_side(j, resources::gameboard->teams(), side(), it->side()) &&
it->ability_active(tag_name, j, adjacent[i]) &&
ability_affects_adjacent(tag_name, j, i, loc, *it))
{
res.push_back(unit_ability(&j, adjacent[i]));
}
}
}
return res;
}
std::vector<std::string> unit::get_ability_list() const
{
std::vector<std::string> res;
for (const config::any_child &ab : this->abilities_.all_children_range()) {
std::string id = ab.cfg["id"];
if (!id.empty())
res.push_back(std::move(id));
}
return res;
}
namespace {
// These functions might have wider usefulness than this file, but for now
// I'll make them local.
/**
* Chooses a value from the given config. If the value specified by @a key is
* blank, then @a default_key is chosen instead.
*/
inline const config::attribute_value & default_value(
const config & cfg, const std::string & key, const std::string & default_key)
{
const config::attribute_value & value = cfg[key];
return !value.blank() ? value : cfg[default_key];
}
/**
* Chooses a value from the given config based on gender. If the value for
* the specified gender is blank, then @a default_key is chosen instead.
*/
inline const config::attribute_value & gender_value(
const config & cfg, unit_race::GENDER gender, const std::string & male_key,
const std::string & female_key, const std::string & default_key)
{
return default_value(cfg,
gender == unit_race::MALE ? male_key : female_key,
default_key);
}
}
std::vector<std::tuple<std::string, t_string, t_string, t_string>> unit::ability_tooltips(boost::dynamic_bitset<>* active_list) const
{
std::vector<std::tuple<std::string, t_string,t_string,t_string>> res;
if ( active_list )
active_list->clear();
for (const config::any_child &ab : this->abilities_.all_children_range())
{
if ( !active_list || ability_active(ab.key, ab.cfg, loc_) )
{
const t_string& name =
gender_value(ab.cfg, gender_, "name", "female_name", "name").t_str();
if (!name.empty()) {
res.emplace_back(
ab.cfg["id"],
ab.cfg["name"].t_str(),
name,
ab.cfg["description"].t_str() );
if ( active_list )
active_list->push_back(true);
}
}
else
{
// See if an inactive name was specified.
const config::attribute_value& inactive_value =
gender_value(ab.cfg, gender_, "name_inactive",
"female_name_inactive", "name_inactive");
const t_string& name = !inactive_value.blank() ? inactive_value.t_str() :
gender_value(ab.cfg, gender_, "name", "female_name", "name").t_str();
if (!name.empty()) {
res.emplace_back(
ab.cfg["id"],
default_value(ab.cfg, "name_inactive", "name").t_str(),
name,
default_value(ab.cfg, "description_inactive", "description").t_str() );
active_list->push_back(false);
}
}
}
return res;
}
bool unit::ability_active(const std::string& ability,const config& cfg,const map_location& loc) const
{
bool illuminates = ability == "illuminates";
if (const config &afilter = cfg.child("filter"))
if ( !unit_filter(vconfig(afilter)).set_use_flat_tod(illuminates).matches(*this, loc) )
return false;
adjacent_loc_array_t adjacent;
get_adjacent_tiles(loc,adjacent.data());
assert(display::get_singleton());
const unit_map& units = display::get_singleton()->get_units();
for (const config &i : cfg.child_range("filter_adjacent"))
{
size_t count = 0;
unit_filter ufilt{ vconfig(i) };
ufilt.set_use_flat_tod(illuminates);
std::vector<map_location::DIRECTION> dirs = map_location::parse_directions(i["adjacent"]);
for (const map_location::DIRECTION index : dirs)
{
if (index == map_location::NDIRECTIONS)
continue;
unit_map::const_iterator unit = units.find(adjacent[index]);
if (unit == units.end())
return false;
if (!ufilt(*unit, *this))
return false;
if (i.has_attribute("is_enemy")) {
const display_context& dc = resources::filter_con->get_disp_context();
if (i["is_enemy"].to_bool() != dc.get_team(unit->side()).is_enemy(side_)) {
continue;
}
}
count++;
}
if (i["count"].empty() && count != dirs.size()) {
return false;
}
if (!in_ranges<int>(count, utils::parse_ranges(i["count"].str()))) {
return false;
}
}
for (const config &i : cfg.child_range("filter_adjacent_location"))
{
size_t count = 0;
terrain_filter adj_filter(vconfig(i), resources::filter_con);
adj_filter.flatten(illuminates);
std::vector<map_location::DIRECTION> dirs = map_location::parse_directions(i["adjacent"]);
for (const map_location::DIRECTION index : dirs)
{
if (index == map_location::NDIRECTIONS) {
continue;
}
if(!adj_filter.match(adjacent[index])) {
return false;
}
count++;
}
if (i["count"].empty() && count != dirs.size()) {
return false;
}
if (!in_ranges<int>(count, utils::parse_ranges(i["count"].str()))) {
return false;
}
}
return true;
}
bool unit::ability_affects_adjacent(const std::string& ability, const config& cfg,int dir,const map_location& loc,const unit& from) const
{
bool illuminates = ability == "illuminates";
assert(dir >=0 && dir <= 5);
map_location::DIRECTION direction = static_cast<map_location::DIRECTION>(dir);
for (const config &i : cfg.child_range("affect_adjacent"))
{
if (i.has_attribute("adjacent")) { //key adjacent defined
std::vector<map_location::DIRECTION> dirs = map_location::parse_directions(i["adjacent"]);
if (std::find(dirs.begin(), dirs.end(), direction) == dirs.end()) {
continue;
}
}
const config &filter = i.child("filter");
if (!filter || //filter tag given
unit_filter(vconfig(filter)).set_use_flat_tod(illuminates).matches(*this, loc, from) ) {
return true;
}
}
return false;
}
bool unit::ability_affects_self(const std::string& ability,const config& cfg,const map_location& loc) const
{
const config &filter = cfg.child("filter_self");
bool affect_self = cfg["affect_self"].to_bool(true);
if (!filter || !affect_self) return affect_self;
return unit_filter(vconfig(filter)).set_use_flat_tod(ability == "illuminates").matches(*this, loc);
}
bool unit::has_ability_type(const std::string& ability) const
{
return !abilities_.child_range(ability).empty();
}
namespace {
template<typename T, typename TFuncFormula>
class get_ability_value_visitor : public boost::static_visitor<T>
{
public:
// Constructor stores the default value.
get_ability_value_visitor(T def, const TFuncFormula& formula_handler) : def_(def), formula_handler_(formula_handler) {}
T operator()(const boost::blank&) const { return def_; }
T operator()(bool) const { return def_; }
T operator()(int i) const { return static_cast<T>(i); }
T operator()(unsigned long long u) const { return static_cast<T>(u); }
T operator()(double d) const { return static_cast<T>(d); }
T operator()(const t_string&) const { return def_; }
T operator()(const std::string& s) const
{
if(s.size() >= 2 && s[0] == '(') {
return formula_handler_(s);
}
return lexical_cast_default<T>(s, def_);
}
private:
const T def_;
const TFuncFormula& formula_handler_;
};
template<typename T, typename TFuncFormula>
get_ability_value_visitor<T, TFuncFormula> make_get_ability_value_visitor(T def, const TFuncFormula& formula_handler)
{
return get_ability_value_visitor<T, TFuncFormula>(def, formula_handler);
}
template<typename T, typename TFuncFormula>
T get_single_ability_value(const config::attribute_value& v, T def, const map_location& sender_loc, const map_location& receiver_loc, const TFuncFormula& formula_handler)
{
return v.apply_visitor(make_get_ability_value_visitor(def, [&](const std::string& s) {
try {
assert(display::get_singleton());
const unit_map& units = display::get_singleton()->get_units();
auto u_itor = units.find(sender_loc);
if(u_itor == units.end()) {
return def;
}
wfl::map_formula_callable callable(std::make_shared<wfl::unit_callable>(*u_itor));
u_itor = units.find(receiver_loc);
if(u_itor != units.end()) {
callable.add("other", wfl::variant(std::make_shared<wfl::unit_callable>(*u_itor)));
}
return formula_handler(wfl::formula(s, new wfl::gamestate_function_symbol_table), callable);
} catch(wfl::formula_error& e) {
lg::wml_error() << "Formula error in ability or weapon special: " << e.type << " at " << e.filename << ':' << e.line << ")\n";
return def;
}
}));
}
}
template<typename TComp>
std::pair<int,map_location> unit_ability_list::get_extremum(const std::string& key, int def, const TComp& comp) const
{
if ( cfgs_.empty() ) {
return std::make_pair(def, map_location());
}
// The returned location is the best non-cumulative one, if any,
// the best absolute cumulative one otherwise.
map_location best_loc;
bool only_cumulative = true;
int abs_max = 0;
int flat = 0;
int stack = 0;
for (const unit_ability& p : cfgs_)
{
int value = get_single_ability_value((*p.first)[key], def, p.second, loc(),[&](const wfl::formula& formula, wfl::map_formula_callable& callable) {
return formula.evaluate(callable).as_int();
});
if ((*p.first)["cumulative"].to_bool()) {
stack += value;
if (value < 0) value = -value;
if (only_cumulative && !comp(value, abs_max)) {
abs_max = value;
best_loc = p.second;
}
} else if (only_cumulative || comp(flat, value)) {
only_cumulative = false;
flat = value;
best_loc = p.second;
}
}
return std::make_pair(flat + stack, best_loc);
}
template std::pair<int, map_location> unit_ability_list::get_extremum<std::less<int>>(const std::string& key, int def, const std::less<int>& comp) const;
template std::pair<int, map_location> unit_ability_list::get_extremum<std::greater<int>>(const std::string& key, int def, const std::greater<int>& comp) const;
/*
*
* [special]
* [swarm]
* name= _ "swarm"
* name_inactive= _ ""
* description= _ ""
* description_inactive= _ ""
* cumulative=no
* apply_to=self #self,opponent,defender,attacker,both
* #active_on=defense # or offense; omitting this means "both"
*
* swarm_attacks_max=4
* swarm_attacks_min=2
*
* [filter_self] // SUF
* ...
* [/filter_self]
* [filter_opponent] // SUF
* [filter_attacker] // SUF
* [filter_defender] // SUF
* [filter_adjacent] // SAUF
* [filter_adjacent_location] // SAUF + locs
* [/swarm]
* [/special]
*
*/
namespace {
/**
* Gets the children of @parent (which should be the specials for an
* attack_type) and places the ones whose tag or id= matches @a id into
* @a result.
* If @a just_peeking is set to true, then @a result is not touched;
* instead the return value is used to indicate if any matching children
* were found.
*
* @returns true if @a just_peeking is true and a match was found;
* false otherwise.
*/
bool get_special_children(std::vector<const config*>& result, const config& parent,
const std::string& id, bool just_peeking=false) {
for (const config::any_child &sp : parent.all_children_range())
{
if (sp.key == id || sp.cfg["id"] == id) {
if(just_peeking) {
return true; // peek succeeded; done
} else {
result.push_back(&sp.cfg);
}
}
}
return false;
}
}
/**
* Returns whether or not @a *this has a special with a tag or id equal to
* @a special. If @a simple_check is set to true, then the check is merely
* for being present. Otherwise (the default), the check is for a special
* active in the current context (see set_specials_context), including
* specials obtained from the opponent's attack.
*/
bool attack_type::get_special_bool(const std::string& special, bool simple_check) const
{
{
std::vector<const config*> list;
if ( get_special_children(list, specials_, special, simple_check) ) {
return true;
}
// If we make it to here, then either list.empty() or !simple_check.
// So if the list is not empty, then this is not a simple check and
// we need to check each special in the list to see if any are active.
for (std::vector<const config*>::iterator i = list.begin(), i_end = list.end(); i != i_end; ++i) {
if ( special_active(**i, AFFECT_SELF) ) {
return true;
}
}
}
// Skip checking the opponent's attack?
if ( simple_check || !other_attack_ ) {
return false;
}
std::vector<const config*> list;
get_special_children(list, other_attack_->specials_, special);
for (std::vector<const config*>::iterator i = list.begin(), i_end = list.end(); i != i_end; ++i) {
if ( other_attack_->special_active(**i, AFFECT_OTHER) ) {
return true;
}
}
return false;
}
/**
* Returns the currently active specials as an ability list, given the current
* context (see set_specials_context).
*/
unit_ability_list attack_type::get_specials(const std::string& special) const
{
//log_scope("get_specials");
unit_ability_list res(self_loc_);
for (const config &i : specials_.child_range(special)) {
if ( special_active(i, AFFECT_SELF) )
res.push_back(unit_ability(&i, self_loc_));
}
if (!other_attack_) return res;
for (const config &i : other_attack_->specials_.child_range(special)) {
if ( other_attack_->special_active(i, AFFECT_OTHER) )
res.push_back(unit_ability(&i, other_loc_));
}
return res;
}
/**
* Returns a vector of names and descriptions for the specials of *this.
* Each std::pair in the vector has first = name and second = description.
*
* This uses either the active or inactive name/description for each special,
* based on the current context (see set_specials_context), provided
* @a active_list is not nullptr. Otherwise specials are assumed active.
* If the appropriate name is empty, the special is skipped.
*/
std::vector<std::pair<t_string, t_string>> attack_type::special_tooltips(
boost::dynamic_bitset<>* active_list) const
{
//log_scope("special_tooltips");
std::vector<std::pair<t_string, t_string>> res;
if ( active_list )
active_list->clear();
for (const config::any_child &sp : specials_.all_children_range())
{
if ( !active_list || special_active(sp.cfg, AFFECT_EITHER) ) {
const t_string &name = sp.cfg["name"];
if (!name.empty()) {
res.emplace_back(name, sp.cfg["description"].t_str() );
if ( active_list )
active_list->push_back(true);
}
} else {
const t_string& name = default_value(sp.cfg, "name_inactive", "name").t_str();
if (!name.empty()) {
res.emplace_back(name, default_value(sp.cfg, "description_inactive", "description").t_str() );
active_list->push_back(false);
}
}
}
return res;
}
/**
* Returns a comma-separated string of active names for the specials of *this.
* Empty names are skipped.
*
* This excludes inactive specials if only_active is true. Whether or not a
* special is active depends on the current context (see set_specials_context)
* and the @a is_backstab parameter.
*/
std::string attack_type::weapon_specials(bool only_active, bool is_backstab) const
{
//log_scope("weapon_specials");
std::string res;
for (const config::any_child &sp : specials_.all_children_range())
{
if ( only_active && !special_active(sp.cfg, AFFECT_EITHER, is_backstab) )
continue;
const std::string& name = sp.cfg["name"].str();
if (!name.empty()) {
if (!res.empty()) res += ", ";
res += name;
}
}
return res;
}
/**
* Sets the context under which specials will be checked for being active.
* This version is appropriate if both units in a combat are known.
* @param[in] self A reference to the unit with this weapon.
* @param[in] other A reference to the other unit in the combat.
* @param[in] unit_loc The location of the unit with this weapon.
* @param[in] other_loc The location of the other unit in the combat.
* @param[in] attacking Whether or not the unit with this weapon is the attacker.
* @param[in] other_attack The attack used by the other unit.
*/
void attack_type::set_specials_context(const unit& self,
const unit& other,
const map_location& unit_loc,
const map_location& other_loc,
bool attacking,
const_attack_ptr other_attack) const
{
self_ = &self;
other_ = &other;
self_loc_ = unit_loc;
other_loc_ = other_loc;
is_attacker_ = attacking;
other_attack_ = other_attack;
is_for_listing_ = false;
}
/**
* Sets the context under which specials will be checked for being active.
* This version is appropriate if there is no specific combat being considered.
* @param[in] self A reference to the unit with this weapon.
* @param[in] loc The location of the unit with this weapon.
* @param[in] attacking Whether or not the unit with this weapon is the attacker.
*/
void attack_type::set_specials_context(const unit& self, const map_location& loc, bool attacking) const
{
self_ = &self;
other_ = nullptr;
self_loc_ = loc;
other_loc_ = map_location::null_location();
is_attacker_ = attacking;
other_attack_ = nullptr;
is_for_listing_ = false;
}
/**
* Sets the context under which specials will be checked for being active.
* This version is appropriate for theoretical units of a particular type.
* @param[in] self_type A reference to the type of the unit with this weapon.
* @param[in] loc The location of the unit with this weapon.
* @param[in] attacking Whether or not the unit with this weapon is the attacker.
*/
void attack_type::set_specials_context(const unit_type* self_type, const map_location& loc, bool attacking) const
{
UNUSED(self_type);
self_ = nullptr;
other_ = nullptr;
self_loc_ = loc;
other_loc_ = map_location::null_location();
is_attacker_ = attacking;
other_attack_ = nullptr;
is_for_listing_ = false;
}
void attack_type::set_specials_context_for_listing() const
{
is_for_listing_ = true;
}
/**
* Calculates the number of attacks this weapon has, considering specials.
* This returns two numbers because of the swarm special. The actual number of
* attacks depends on the unit's health and should be:
* min_attacks + (max_attacks - min_attacks) * (current hp) / (max hp)
* c.f. swarm_blows()
*/
void attack_type::modified_attacks(bool is_backstab, unsigned & min_attacks,
unsigned & max_attacks) const
{
// Apply [attacks].
unit_abilities::effect attacks_effect(get_specials("attacks"),
num_attacks(), is_backstab);
int attacks_value = attacks_effect.get_composite_value();
if ( attacks_value < 0 ) {
attacks_value = num_attacks();
ERR_NG << "negative number of strikes after applying weapon specials" << std::endl;
}
// Apply [swarm].
unit_ability_list swarm_specials = get_specials("swarm");
if ( !swarm_specials.empty() ) {
min_attacks = std::max<int>(0, swarm_specials.highest("swarm_attacks_min").first);
max_attacks = std::max<int>(0, swarm_specials.highest("swarm_attacks_max", attacks_value).first);
} else {
min_attacks = max_attacks = attacks_value;
}
}
/**
* Returns the damage per attack of this weapon, considering specials.
*/
int attack_type::modified_damage(bool is_backstab) const
{
unit_abilities::effect dmg_effect(get_specials("damage"), damage(), is_backstab);
return dmg_effect.get_composite_value();
}
namespace { // Helpers for attack_type::special_active()
/**
* Returns whether or not the given special affects the opponent of the unit
* with the special.
* @param[in] special a weapon special WML structure
* @param[in] is_attacker whether or not the unit with the special is the attacker
*/
bool special_affects_opponent(const config& special, bool is_attacker)
{
//log_scope("special_affects_opponent");
const std::string& apply_to = special["apply_to"];
if ( apply_to.empty() )
return false;
if ( apply_to == "both" )
return true;
if ( apply_to == "opponent" )
return true;
if ( is_attacker && apply_to == "defender" )
return true;
if ( !is_attacker && apply_to == "attacker" )
return true;
return false;
}
/**
* Returns whether or not the given special affects the unit with the special.
* @param[in] special a weapon special WML structure
* @param[in] is_attacker whether or not the unit with the special is the attacker
*/
bool special_affects_self(const config& special, bool is_attacker)
{
//log_scope("special_affects_self");
const std::string& apply_to = special["apply_to"];
if ( apply_to.empty() )
return true;
if ( apply_to == "both" )
return true;
if ( apply_to == "self" )
return true;
if ( is_attacker && apply_to == "attacker" )
return true;
if ( !is_attacker && apply_to == "defender")
return true;
return false;
}
/**
* Determines if a unit/weapon combination matches the specified child
* (normally a [filter_*] child) of the provided filter.
* @param[in] un_it The unit to filter.
* @param[in] loc The presumed location of @a un_it.
* @param[in] weapon The attack_type to filter.
* @param[in] filter The filter containing the child filter to use.
* @param[in] child_tag The tag of the child filter to use.
*/
static bool special_unit_matches(const unit* & u,
const unit* & u2,
const map_location & loc,
const_attack_ptr weapon,
const config & filter,
const bool for_listing,
const std::string & child_tag)
{
if (for_listing && !loc.valid())
// The special's context was set to ignore this unit, so assume we pass.
// (This is used by reports.cpp to show active specials when the
// opponent is not known. From a player's perspective, the special
// is active, in that it can be used, even though the player might
// need to select an appropriate opponent.)
return true;
const config & filter_child = filter.child(child_tag);
if ( !filter_child )
// The special does not filter on this unit, so we pass.
return true;
// If the primary unit doesn't exist, there's nothing to match
if (!u) {
return false;
}
unit_filter ufilt{vconfig(filter_child)};
// If the other unit doesn't exist, try matching without it
if (!u2) {
return ufilt.matches(*u, loc);
}
// Check for a unit match.
if (!ufilt.matches(*u, loc, *u2)) {
return false;
}
// Check for a weapon match.
if ( const config & filter_weapon = filter_child.child("filter_weapon") ) {
if ( !weapon || !weapon->matches_filter(filter_weapon) )
return false;
}
// Passed.
return true;
}
}//anonymous namespace
/**
* Returns whether or not the given special is active for the specified unit,
* based on the current context (see set_specials_context).
* @param[in] special a weapon special WML structure
* @param[in] whom specifies which combatant we care about
* @param[in] include_backstab false if backstab specials should not be active
* (usually true since backstab is usually accounted
* for elsewhere)
*/
bool attack_type::special_active(const config& special, AFFECTS whom,
bool include_backstab) const
{
//log_scope("special_active");
// Backstab check
if ( !include_backstab )
if ( special["backstab"].to_bool() )
return false;
// Does this affect the specified unit?
if ( whom == AFFECT_SELF ) {
if ( !special_affects_self(special, is_attacker_) )
return false;
}
if ( whom == AFFECT_OTHER ) {
if ( !special_affects_opponent(special, is_attacker_) )
return false;
}
// Is this active on attack/defense?
const std::string & active_on = special["active_on"];
if ( !active_on.empty() ) {
if ( is_attacker_ && active_on != "offense" )
return false;
if ( !is_attacker_ && active_on != "defense" )
return false;
}
// Get the units involved.
assert(display::get_singleton());
const unit_map& units = display::get_singleton()->get_units();
const unit* self = self_;
const unit* other = other_;
if(self == nullptr) {
unit_map::const_iterator it = units.find(self_loc_);
if(it.valid()) {
self = it.get_shared_ptr().get();
}
}
if(other == nullptr) {
unit_map::const_iterator it = units.find(other_loc_);
if(it.valid()) {
other = it.get_shared_ptr().get();
}
}
// Make sure they're facing each other.
temporary_facing self_facing(self, self_loc_.get_relative_dir(other_loc_));
temporary_facing other_facing(other, other_loc_.get_relative_dir(self_loc_));
// Translate our context into terms of "attacker" and "defender".
const unit* & att = is_attacker_ ? self : other;
const unit* & def = is_attacker_ ? other : self;
const map_location & att_loc = is_attacker_ ? self_loc_ : other_loc_;
const map_location & def_loc = is_attacker_ ? other_loc_ : self_loc_;
const_attack_ptr att_weapon = is_attacker_ ? shared_from_this() : other_attack_;
const_attack_ptr def_weapon = is_attacker_ ? other_attack_ : shared_from_this();
// Filter the units involved.
if (!special_unit_matches(self, other, self_loc_, shared_from_this(), special, is_for_listing_, "filter_self"))
return false;
if (!special_unit_matches(other, self, other_loc_, other_attack_, special, is_for_listing_, "filter_opponent"))
return false;
if (!special_unit_matches(att, def, att_loc, att_weapon, special, is_for_listing_, "filter_attacker"))
return false;
if (!special_unit_matches(def, att, def_loc, def_weapon, special, is_for_listing_, "filter_defender"))
return false;
adjacent_loc_array_t adjacent;
get_adjacent_tiles(self_loc_, adjacent.data());
// Filter the adjacent units.
for (const config &i : special.child_range("filter_adjacent"))
{
size_t count = 0;
std::vector<map_location::DIRECTION> dirs = map_location::parse_directions(i["adjacent"]);
unit_filter filter{ vconfig(i) };
for (const map_location::DIRECTION index : dirs)
{