2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2021 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #ifndef ENDGAME_H_INCLUDED
20 #define ENDGAME_H_INCLUDED
24 #include <type_traits>
25 #include <unordered_map>
33 /// EndgameCode lists all supported endgame functions by corresponding codes
40 KXK, // Generic "mate lone king" eval
50 KBPsK, // KB and pawns vs K
51 KQKRPs, // KQ vs KR and pawns
54 KRPPKRP, // KRPP vs KRP
55 KPsK, // K and pawns vs K
63 /// Endgame functions can be of two types depending on whether they return a
64 /// Value or a ScaleFactor.
66 template<EndgameCode E> using
67 eg_type = typename std::conditional<(E < SCALING_FUNCTIONS), Value, ScaleFactor>::type;
70 /// Base and derived functors for endgame evaluation and scaling functions
75 explicit EndgameBase(Color c) : strongSide(c), weakSide(~c) {}
76 virtual ~EndgameBase() = default;
77 virtual T operator()(const Position&) const = 0;
79 const Color strongSide, weakSide;
83 template<EndgameCode E, typename T = eg_type<E>>
84 struct Endgame : public EndgameBase<T> {
86 explicit Endgame(Color c) : EndgameBase<T>(c) {}
87 T operator()(const Position&) const override;
91 /// The Endgames namespace handles the pointers to endgame evaluation and scaling
92 /// base objects in two std::map. We use polymorphism to invoke the actual
93 /// endgame function by calling its virtual operator().
97 template<typename T> using Ptr = std::unique_ptr<EndgameBase<T>>;
98 template<typename T> using Map = std::unordered_map<Key, Ptr<T>>;
100 extern std::pair<Map<Value>, Map<ScaleFactor>> maps;
106 return std::get<std::is_same<T, ScaleFactor>::value>(maps);
109 template<EndgameCode E, typename T = eg_type<E>>
110 void add(const std::string& code) {
113 map<T>()[Position().set(code, WHITE, &st).material_key()] = Ptr<T>(new Endgame<E>(WHITE));
114 map<T>()[Position().set(code, BLACK, &st).material_key()] = Ptr<T>(new Endgame<E>(BLACK));
118 const EndgameBase<T>* probe(Key key) {
119 auto it = map<T>().find(key);
120 return it != map<T>().end() ? it->second.get() : nullptr;
124 } // namespace Stockfish
126 #endif // #ifndef ENDGAME_H_INCLUDED