]> git.sesse.net Git - stockfish/blob - src/endgame.cpp
Indulge a bit on the template wizardy
[stockfish] / src / endgame.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <cassert>
21
22 #include "bitcount.h"
23 #include "endgame.h"
24 #include "pawns.h"
25
26 using std::string;
27
28 extern uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm);
29
30 namespace {
31
32   // Table used to drive the defending king towards the edge of the board
33   // in KX vs K and KQ vs KR endgames.
34   const int MateTable[64] = {
35     100, 90, 80, 70, 70, 80, 90, 100,
36      90, 70, 60, 50, 50, 60, 70,  90,
37      80, 60, 40, 30, 30, 40, 60,  80,
38      70, 50, 30, 20, 20, 30, 50,  70,
39      70, 50, 30, 20, 20, 30, 50,  70,
40      80, 60, 40, 30, 30, 40, 60,  80,
41      90, 70, 60, 50, 50, 60, 70,  90,
42     100, 90, 80, 70, 70, 80, 90, 100,
43   };
44
45   // Table used to drive the defending king towards a corner square of the
46   // right color in KBN vs K endgames.
47   const int KBNKMateTable[64] = {
48     200, 190, 180, 170, 160, 150, 140, 130,
49     190, 180, 170, 160, 150, 140, 130, 140,
50     180, 170, 155, 140, 140, 125, 140, 150,
51     170, 160, 140, 120, 110, 140, 150, 160,
52     160, 150, 140, 110, 120, 140, 160, 170,
53     150, 140, 125, 140, 140, 155, 170, 180,
54     140, 130, 140, 150, 160, 170, 180, 190,
55     130, 140, 150, 160, 170, 180, 190, 200
56   };
57
58   // The attacking side is given a descending bonus based on distance between
59   // the two kings in basic endgames.
60   const int DistanceBonus[8] = { 0, 0, 100, 80, 60, 40, 20, 10 };
61
62   // Penalty for big distance between king and knight for the defending king
63   // and knight in KR vs KN endgames.
64   const int KRKNKingKnightDistancePenalty[8] = { 0, 0, 4, 10, 20, 32, 48, 70 };
65
66   // Build corresponding key code for the opposite color: "KBPKN" -> "KNKBP"
67   const string swap_colors(const string& keyCode) {
68
69     size_t idx = keyCode.find('K', 1);
70     return keyCode.substr(idx) + keyCode.substr(0, idx);
71   }
72
73   // Get the material key of a position out of the given endgame key code
74   // like "KBPKN". The trick here is to first build up a FEN string and then
75   // let a Position object to do the work for us. Note that the FEN string
76   // could correspond to an illegal position.
77   Key mat_key(const string& keyCode) {
78
79     assert(keyCode.length() > 0 && keyCode.length() < 8);
80     assert(keyCode[0] == 'K');
81
82     string fen;
83     size_t i = 0;
84
85     // First add white and then black pieces
86     do fen += keyCode[i];                while (keyCode[++i] != 'K');
87     do fen += char(tolower(keyCode[i])); while (++i < keyCode.length());
88
89     // Add file padding and remaining empty ranks
90     fen += string(1, '0' + int(8 - keyCode.length())) + "/8/8/8/8/8/8/8 w - - 0 10";
91
92     // Build a Position out of the fen string and get its material key
93     return Position(fen, false, 0).get_material_key();
94   }
95
96   typedef Endgames::EMap<Value>::type EFMap;
97   typedef Endgames::EMap<ScaleFactor>::type SFMap;
98
99 } // namespace
100
101
102 /// Endgames member definitions
103
104 template<> const EFMap& Endgames::map<Value>() const { return maps.first; }
105 template<> const SFMap& Endgames::map<ScaleFactor>() const { return maps.second; }
106
107 Endgames::Endgames() {
108
109   add<Value, KPK>("KPK");
110   add<Value, KNNK>("KNNK");
111   add<Value, KBNK>("KBNK");
112   add<Value, KRKP>("KRKP");
113   add<Value, KRKB>("KRKB");
114   add<Value, KRKN>("KRKN");
115   add<Value, KQKR>("KQKR");
116   add<Value, KBBKN>("KBBKN");
117
118   add<ScaleFactor, KNPK>("KNPK");
119   add<ScaleFactor, KRPKR>("KRPKR");
120   add<ScaleFactor, KBPKB>("KBPKB");
121   add<ScaleFactor, KBPKN>("KBPKN");
122   add<ScaleFactor, KBPPKB>("KBPPKB");
123   add<ScaleFactor, KRPPKRP>("KRPPKRP");
124 }
125
126 Endgames::~Endgames() {
127
128   for (EFMap::const_iterator it = map<Value>().begin(); it != map<Value>().end(); ++it)
129       delete it->second;
130
131   for (SFMap::const_iterator it = map<ScaleFactor>().begin(); it != map<ScaleFactor>().end(); ++it)
132       delete it->second;
133 }
134
135 template<typename T, EndgameType E>
136 void Endgames::add(const string& keyCode) {
137
138   typedef Endgame<T, E> EG;
139   typedef typename EG::Base B;
140   typedef typename EMap<T>::type M;
141
142   const_cast<M&>(map<T>()).insert(std::pair<Key, B*>(mat_key(keyCode), new EG(WHITE)));
143   const_cast<M&>(map<T>()).insert(std::pair<Key, B*>(mat_key(swap_colors(keyCode)), new EG(BLACK)));
144 }
145
146 template<typename T>
147 EndgameBase<T>* Endgames::get(Key key) const {
148
149   typename EMap<T>::type::const_iterator it = map<T>().find(key);
150   return it != map<T>().end() ? it->second : NULL;
151 }
152
153 // Explicit template instantiations
154 template EndgameBase<Value>* Endgames::get<Value>(Key key) const;
155 template EndgameBase<ScaleFactor>* Endgames::get<ScaleFactor>(Key key) const;
156
157
158 /// Mate with KX vs K. This function is used to evaluate positions with
159 /// King and plenty of material vs a lone king. It simply gives the
160 /// attacking side a bonus for driving the defending king towards the edge
161 /// of the board, and for keeping the distance between the two kings small.
162 template<>
163 Value Endgame<Value, KXK>::apply(const Position& pos) const {
164
165   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
166   assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
167
168   Square winnerKSq = pos.king_square(strongerSide);
169   Square loserKSq = pos.king_square(weakerSide);
170
171   Value result =   pos.non_pawn_material(strongerSide)
172                  + pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
173                  + MateTable[loserKSq]
174                  + DistanceBonus[square_distance(winnerKSq, loserKSq)];
175
176   if (   pos.piece_count(strongerSide, QUEEN)
177       || pos.piece_count(strongerSide, ROOK)
178       || pos.piece_count(strongerSide, BISHOP) > 1)
179       // TODO: check for two equal-colored bishops!
180       result += VALUE_KNOWN_WIN;
181
182   return strongerSide == pos.side_to_move() ? result : -result;
183 }
184
185
186 /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
187 /// defending king towards a corner square of the right color.
188 template<>
189 Value Endgame<Value, KBNK>::apply(const Position& pos) const {
190
191   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
192   assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
193   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
194   assert(pos.piece_count(strongerSide, BISHOP) == 1);
195   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
196   assert(pos.piece_count(strongerSide, PAWN) == 0);
197
198   Square winnerKSq = pos.king_square(strongerSide);
199   Square loserKSq = pos.king_square(weakerSide);
200   Square bishopSquare = pos.piece_list(strongerSide, BISHOP)[0];
201
202   // kbnk_mate_table() tries to drive toward corners A1 or H8,
203   // if we have a bishop that cannot reach the above squares we
204   // mirror the kings so to drive enemy toward corners A8 or H1.
205   if (opposite_color_squares(bishopSquare, SQ_A1))
206   {
207       winnerKSq = flop_square(winnerKSq);
208       loserKSq = flop_square(loserKSq);
209   }
210
211   Value result =  VALUE_KNOWN_WIN
212                 + DistanceBonus[square_distance(winnerKSq, loserKSq)]
213                 + KBNKMateTable[loserKSq];
214
215   return strongerSide == pos.side_to_move() ? result : -result;
216 }
217
218
219 /// KP vs K. This endgame is evaluated with the help of a bitbase.
220 template<>
221 Value Endgame<Value, KPK>::apply(const Position& pos) const {
222
223   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
224   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
225   assert(pos.piece_count(strongerSide, PAWN) == 1);
226   assert(pos.piece_count(weakerSide, PAWN) == 0);
227
228   Square wksq, bksq, wpsq;
229   Color stm;
230
231   if (strongerSide == WHITE)
232   {
233       wksq = pos.king_square(WHITE);
234       bksq = pos.king_square(BLACK);
235       wpsq = pos.piece_list(WHITE, PAWN)[0];
236       stm = pos.side_to_move();
237   }
238   else
239   {
240       wksq = flip_square(pos.king_square(BLACK));
241       bksq = flip_square(pos.king_square(WHITE));
242       wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
243       stm = opposite_color(pos.side_to_move());
244   }
245
246   if (square_file(wpsq) >= FILE_E)
247   {
248       wksq = flop_square(wksq);
249       bksq = flop_square(bksq);
250       wpsq = flop_square(wpsq);
251   }
252
253   if (!probe_kpk_bitbase(wksq, wpsq, bksq, stm))
254       return VALUE_DRAW;
255
256   Value result =  VALUE_KNOWN_WIN
257                 + PawnValueEndgame
258                 + Value(square_rank(wpsq));
259
260   return strongerSide == pos.side_to_move() ? result : -result;
261 }
262
263
264 /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
265 /// a bitbase. The function below returns drawish scores when the pawn is
266 /// far advanced with support of the king, while the attacking king is far
267 /// away.
268 template<>
269 Value Endgame<Value, KRKP>::apply(const Position& pos) const {
270
271   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
272   assert(pos.piece_count(strongerSide, PAWN) == 0);
273   assert(pos.non_pawn_material(weakerSide) == 0);
274   assert(pos.piece_count(weakerSide, PAWN) == 1);
275
276   Square wksq, wrsq, bksq, bpsq;
277   int tempo = (pos.side_to_move() == strongerSide);
278
279   wksq = pos.king_square(strongerSide);
280   wrsq = pos.piece_list(strongerSide, ROOK)[0];
281   bksq = pos.king_square(weakerSide);
282   bpsq = pos.piece_list(weakerSide, PAWN)[0];
283
284   if (strongerSide == BLACK)
285   {
286       wksq = flip_square(wksq);
287       wrsq = flip_square(wrsq);
288       bksq = flip_square(bksq);
289       bpsq = flip_square(bpsq);
290   }
291
292   Square queeningSq = make_square(square_file(bpsq), RANK_1);
293   Value result;
294
295   // If the stronger side's king is in front of the pawn, it's a win
296   if (wksq < bpsq && square_file(wksq) == square_file(bpsq))
297       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
298
299   // If the weaker side's king is too far from the pawn and the rook,
300   // it's a win
301   else if (   square_distance(bksq, bpsq) - (tempo ^ 1) >= 3
302            && square_distance(bksq, wrsq) >= 3)
303       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
304
305   // If the pawn is far advanced and supported by the defending king,
306   // the position is drawish
307   else if (   square_rank(bksq) <= RANK_3
308            && square_distance(bksq, bpsq) == 1
309            && square_rank(wksq) >= RANK_4
310            && square_distance(wksq, bpsq) - tempo > 2)
311       result = Value(80 - square_distance(wksq, bpsq) * 8);
312
313   else
314       result =  Value(200)
315               - Value(square_distance(wksq, bpsq + DELTA_S) * 8)
316               + Value(square_distance(bksq, bpsq + DELTA_S) * 8)
317               + Value(square_distance(bpsq, queeningSq) * 8);
318
319   return strongerSide == pos.side_to_move() ? result : -result;
320 }
321
322
323 /// KR vs KB. This is very simple, and always returns drawish scores.  The
324 /// score is slightly bigger when the defending king is close to the edge.
325 template<>
326 Value Endgame<Value, KRKB>::apply(const Position& pos) const {
327
328   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
329   assert(pos.piece_count(strongerSide, PAWN) == 0);
330   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
331   assert(pos.piece_count(weakerSide, PAWN) == 0);
332   assert(pos.piece_count(weakerSide, BISHOP) == 1);
333
334   Value result = Value(MateTable[pos.king_square(weakerSide)]);
335   return strongerSide == pos.side_to_move() ? result : -result;
336 }
337
338
339 /// KR vs KN.  The attacking side has slightly better winning chances than
340 /// in KR vs KB, particularly if the king and the knight are far apart.
341 template<>
342 Value Endgame<Value, KRKN>::apply(const Position& pos) const {
343
344   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
345   assert(pos.piece_count(strongerSide, PAWN) == 0);
346   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
347   assert(pos.piece_count(weakerSide, PAWN) == 0);
348   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
349
350   Square defendingKSq = pos.king_square(weakerSide);
351   Square nSq = pos.piece_list(weakerSide, KNIGHT)[0];
352
353   int d = square_distance(defendingKSq, nSq);
354   Value result =   Value(10)
355                  + MateTable[defendingKSq]
356                  + KRKNKingKnightDistancePenalty[d];
357
358   return strongerSide == pos.side_to_move() ? result : -result;
359 }
360
361
362 /// KQ vs KR.  This is almost identical to KX vs K:  We give the attacking
363 /// king a bonus for having the kings close together, and for forcing the
364 /// defending king towards the edge.  If we also take care to avoid null move
365 /// for the defending side in the search, this is usually sufficient to be
366 /// able to win KQ vs KR.
367 template<>
368 Value Endgame<Value, KQKR>::apply(const Position& pos) const {
369
370   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
371   assert(pos.piece_count(strongerSide, PAWN) == 0);
372   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
373   assert(pos.piece_count(weakerSide, PAWN) == 0);
374
375   Square winnerKSq = pos.king_square(strongerSide);
376   Square loserKSq = pos.king_square(weakerSide);
377
378   Value result =  QueenValueEndgame
379                 - RookValueEndgame
380                 + MateTable[loserKSq]
381                 + DistanceBonus[square_distance(winnerKSq, loserKSq)];
382
383   return strongerSide == pos.side_to_move() ? result : -result;
384 }
385
386 template<>
387 Value Endgame<Value, KBBKN>::apply(const Position& pos) const {
388
389   assert(pos.piece_count(strongerSide, BISHOP) == 2);
390   assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
391   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
392   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
393   assert(pos.pieces(PAWN) == EmptyBoardBB);
394
395   Value result = BishopValueEndgame;
396   Square wksq = pos.king_square(strongerSide);
397   Square bksq = pos.king_square(weakerSide);
398   Square nsq = pos.piece_list(weakerSide, KNIGHT)[0];
399
400   // Bonus for attacking king close to defending king
401   result += Value(DistanceBonus[square_distance(wksq, bksq)]);
402
403   // Bonus for driving the defending king and knight apart
404   result += Value(square_distance(bksq, nsq) * 32);
405
406   // Bonus for restricting the knight's mobility
407   result += Value((8 - count_1s<CNT32_MAX15>(pos.attacks_from<KNIGHT>(nsq))) * 8);
408
409   return strongerSide == pos.side_to_move() ? result : -result;
410 }
411
412
413 /// K and two minors vs K and one or two minors or K and two knights against
414 /// king alone are always draw.
415 template<>
416 Value Endgame<Value, KmmKm>::apply(const Position&) const {
417   return VALUE_DRAW;
418 }
419
420 template<>
421 Value Endgame<Value, KNNK>::apply(const Position&) const {
422   return VALUE_DRAW;
423 }
424
425 /// KBPKScalingFunction scales endgames where the stronger side has king,
426 /// bishop and one or more pawns. It checks for draws with rook pawns and a
427 /// bishop of the wrong color. If such a draw is detected, SCALE_FACTOR_ZERO is
428 /// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
429 /// will be used.
430 template<>
431 ScaleFactor Endgame<ScaleFactor, KBPsK>::apply(const Position& pos) const {
432
433   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
434   assert(pos.piece_count(strongerSide, BISHOP) == 1);
435   assert(pos.piece_count(strongerSide, PAWN) >= 1);
436
437   // No assertions about the material of weakerSide, because we want draws to
438   // be detected even when the weaker side has some pawns.
439
440   Bitboard pawns = pos.pieces(PAWN, strongerSide);
441   File pawnFile = square_file(pos.piece_list(strongerSide, PAWN)[0]);
442
443   // All pawns are on a single rook file ?
444   if (   (pawnFile == FILE_A || pawnFile == FILE_H)
445       && (pawns & ~file_bb(pawnFile)) == EmptyBoardBB)
446   {
447       Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
448       Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
449       Square kingSq = pos.king_square(weakerSide);
450
451       if (   opposite_color_squares(queeningSq, bishopSq)
452           && abs(square_file(kingSq) - pawnFile) <= 1)
453       {
454           // The bishop has the wrong color, and the defending king is on the
455           // file of the pawn(s) or the neighboring file. Find the rank of the
456           // frontmost pawn.
457           Rank rank;
458           if (strongerSide == WHITE)
459           {
460               for (rank = RANK_7; (rank_bb(rank) & pawns) == EmptyBoardBB; rank--) {}
461               assert(rank >= RANK_2 && rank <= RANK_7);
462           }
463           else
464           {
465               for (rank = RANK_2; (rank_bb(rank) & pawns) == EmptyBoardBB; rank++) {}
466               rank = Rank(rank ^ 7);  // HACK to get the relative rank
467               assert(rank >= RANK_2 && rank <= RANK_7);
468           }
469           // If the defending king has distance 1 to the promotion square or
470           // is placed somewhere in front of the pawn, it's a draw.
471           if (   square_distance(kingSq, queeningSq) <= 1
472               || relative_rank(strongerSide, kingSq) >= rank)
473               return SCALE_FACTOR_ZERO;
474       }
475   }
476   return SCALE_FACTOR_NONE;
477 }
478
479
480 /// KQKRPScalingFunction scales endgames where the stronger side has only
481 /// king and queen, while the weaker side has at least a rook and a pawn.
482 /// It tests for fortress draws with a rook on the third rank defended by
483 /// a pawn.
484 template<>
485 ScaleFactor Endgame<ScaleFactor, KQKRPs>::apply(const Position& pos) const {
486
487   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
488   assert(pos.piece_count(strongerSide, QUEEN) == 1);
489   assert(pos.piece_count(strongerSide, PAWN) == 0);
490   assert(pos.piece_count(weakerSide, ROOK) == 1);
491   assert(pos.piece_count(weakerSide, PAWN) >= 1);
492
493   Square kingSq = pos.king_square(weakerSide);
494   if (   relative_rank(weakerSide, kingSq) <= RANK_2
495       && relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
496       && (pos.pieces(ROOK, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_3)))
497       && (pos.pieces(PAWN, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_2)))
498       && (pos.attacks_from<KING>(kingSq) & pos.pieces(PAWN, weakerSide)))
499   {
500       Square rsq = pos.piece_list(weakerSide, ROOK)[0];
501       if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(PAWN, weakerSide))
502           return SCALE_FACTOR_ZERO;
503   }
504   return SCALE_FACTOR_NONE;
505 }
506
507
508 /// KRPKRScalingFunction scales KRP vs KR endgames. This function knows a
509 /// handful of the most important classes of drawn positions, but is far
510 /// from perfect. It would probably be a good idea to add more knowledge
511 /// in the future.
512 ///
513 /// It would also be nice to rewrite the actual code for this function,
514 /// which is mostly copied from Glaurung 1.x, and not very pretty.
515 template<>
516 ScaleFactor Endgame<ScaleFactor, KRPKR>::apply(const Position& pos) const {
517
518   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
519   assert(pos.piece_count(strongerSide, PAWN) == 1);
520   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
521   assert(pos.piece_count(weakerSide, PAWN) == 0);
522
523   Square wksq = pos.king_square(strongerSide);
524   Square wrsq = pos.piece_list(strongerSide, ROOK)[0];
525   Square wpsq = pos.piece_list(strongerSide, PAWN)[0];
526   Square bksq = pos.king_square(weakerSide);
527   Square brsq = pos.piece_list(weakerSide, ROOK)[0];
528
529   // Orient the board in such a way that the stronger side is white, and the
530   // pawn is on the left half of the board.
531   if (strongerSide == BLACK)
532   {
533       wksq = flip_square(wksq);
534       wrsq = flip_square(wrsq);
535       wpsq = flip_square(wpsq);
536       bksq = flip_square(bksq);
537       brsq = flip_square(brsq);
538   }
539   if (square_file(wpsq) > FILE_D)
540   {
541       wksq = flop_square(wksq);
542       wrsq = flop_square(wrsq);
543       wpsq = flop_square(wpsq);
544       bksq = flop_square(bksq);
545       brsq = flop_square(brsq);
546   }
547
548   File f = square_file(wpsq);
549   Rank r = square_rank(wpsq);
550   Square queeningSq = make_square(f, RANK_8);
551   int tempo = (pos.side_to_move() == strongerSide);
552
553   // If the pawn is not too far advanced and the defending king defends the
554   // queening square, use the third-rank defence.
555   if (   r <= RANK_5
556       && square_distance(bksq, queeningSq) <= 1
557       && wksq <= SQ_H5
558       && (square_rank(brsq) == RANK_6 || (r <= RANK_3 && square_rank(wrsq) != RANK_6)))
559       return SCALE_FACTOR_ZERO;
560
561   // The defending side saves a draw by checking from behind in case the pawn
562   // has advanced to the 6th rank with the king behind.
563   if (   r == RANK_6
564       && square_distance(bksq, queeningSq) <= 1
565       && square_rank(wksq) + tempo <= RANK_6
566       && (square_rank(brsq) == RANK_1 || (!tempo && abs(square_file(brsq) - f) >= 3)))
567       return SCALE_FACTOR_ZERO;
568
569   if (   r >= RANK_6
570       && bksq == queeningSq
571       && square_rank(brsq) == RANK_1
572       && (!tempo || square_distance(wksq, wpsq) >= 2))
573       return SCALE_FACTOR_ZERO;
574
575   // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
576   // and the black rook is behind the pawn.
577   if (   wpsq == SQ_A7
578       && wrsq == SQ_A8
579       && (bksq == SQ_H7 || bksq == SQ_G7)
580       && square_file(brsq) == FILE_A
581       && (square_rank(brsq) <= RANK_3 || square_file(wksq) >= FILE_D || square_rank(wksq) <= RANK_5))
582       return SCALE_FACTOR_ZERO;
583
584   // If the defending king blocks the pawn and the attacking king is too far
585   // away, it's a draw.
586   if (   r <= RANK_5
587       && bksq == wpsq + DELTA_N
588       && square_distance(wksq, wpsq) - tempo >= 2
589       && square_distance(wksq, brsq) - tempo >= 2)
590       return SCALE_FACTOR_ZERO;
591
592   // Pawn on the 7th rank supported by the rook from behind usually wins if the
593   // attacking king is closer to the queening square than the defending king,
594   // and the defending king cannot gain tempi by threatening the attacking rook.
595   if (   r == RANK_7
596       && f != FILE_A
597       && square_file(wrsq) == f
598       && wrsq != queeningSq
599       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
600       && (square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo))
601       return ScaleFactor(SCALE_FACTOR_MAX - 2 * square_distance(wksq, queeningSq));
602
603   // Similar to the above, but with the pawn further back
604   if (   f != FILE_A
605       && square_file(wrsq) == f
606       && wrsq < wpsq
607       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
608       && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wpsq + DELTA_N) - 2 + tempo)
609       && (  square_distance(bksq, wrsq) + tempo >= 3
610           || (    square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo
611               && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wrsq) + tempo))))
612       return ScaleFactor(  SCALE_FACTOR_MAX
613                          - 8 * square_distance(wpsq, queeningSq)
614                          - 2 * square_distance(wksq, queeningSq));
615
616   // If the pawn is not far advanced, and the defending king is somewhere in
617   // the pawn's path, it's probably a draw.
618   if (r <= RANK_4 && bksq > wpsq)
619   {
620       if (square_file(bksq) == square_file(wpsq))
621           return ScaleFactor(10);
622       if (   abs(square_file(bksq) - square_file(wpsq)) == 1
623           && square_distance(wksq, bksq) > 2)
624           return ScaleFactor(24 - 2 * square_distance(wksq, bksq));
625   }
626   return SCALE_FACTOR_NONE;
627 }
628
629
630 /// KRPPKRPScalingFunction scales KRPP vs KRP endgames. There is only a
631 /// single pattern: If the stronger side has no pawns and the defending king
632 /// is actively placed, the position is drawish.
633 template<>
634 ScaleFactor Endgame<ScaleFactor, KRPPKRP>::apply(const Position& pos) const {
635
636   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
637   assert(pos.piece_count(strongerSide, PAWN) == 2);
638   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
639   assert(pos.piece_count(weakerSide, PAWN) == 1);
640
641   Square wpsq1 = pos.piece_list(strongerSide, PAWN)[0];
642   Square wpsq2 = pos.piece_list(strongerSide, PAWN)[1];
643   Square bksq = pos.king_square(weakerSide);
644
645   // Does the stronger side have a passed pawn?
646   if (   pos.pawn_is_passed(strongerSide, wpsq1)
647       || pos.pawn_is_passed(strongerSide, wpsq2))
648       return SCALE_FACTOR_NONE;
649
650   Rank r = Max(relative_rank(strongerSide, wpsq1), relative_rank(strongerSide, wpsq2));
651
652   if (   file_distance(bksq, wpsq1) <= 1
653       && file_distance(bksq, wpsq2) <= 1
654       && relative_rank(strongerSide, bksq) > r)
655   {
656       switch (r) {
657       case RANK_2: return ScaleFactor(10);
658       case RANK_3: return ScaleFactor(10);
659       case RANK_4: return ScaleFactor(15);
660       case RANK_5: return ScaleFactor(20);
661       case RANK_6: return ScaleFactor(40);
662       default: assert(false);
663       }
664   }
665   return SCALE_FACTOR_NONE;
666 }
667
668
669 /// KPsKScalingFunction scales endgames with king and two or more pawns
670 /// against king. There is just a single rule here: If all pawns are on
671 /// the same rook file and are blocked by the defending king, it's a draw.
672 template<>
673 ScaleFactor Endgame<ScaleFactor, KPsK>::apply(const Position& pos) const {
674
675   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
676   assert(pos.piece_count(strongerSide, PAWN) >= 2);
677   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
678   assert(pos.piece_count(weakerSide, PAWN) == 0);
679
680   Square ksq = pos.king_square(weakerSide);
681   Bitboard pawns = pos.pieces(PAWN, strongerSide);
682
683   // Are all pawns on the 'a' file?
684   if ((pawns & ~FileABB) == EmptyBoardBB)
685   {
686       // Does the defending king block the pawns?
687       if (   square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1
688           || (   square_file(ksq) == FILE_A
689               && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
690           return SCALE_FACTOR_ZERO;
691   }
692   // Are all pawns on the 'h' file?
693   else if ((pawns & ~FileHBB) == EmptyBoardBB)
694   {
695     // Does the defending king block the pawns?
696     if (   square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1
697         || (   square_file(ksq) == FILE_H
698             && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
699         return SCALE_FACTOR_ZERO;
700   }
701   return SCALE_FACTOR_NONE;
702 }
703
704
705 /// KBPKBScalingFunction scales KBP vs KB endgames. There are two rules:
706 /// If the defending king is somewhere along the path of the pawn, and the
707 /// square of the king is not of the same color as the stronger side's bishop,
708 /// it's a draw. If the two bishops have opposite color, it's almost always
709 /// a draw.
710 template<>
711 ScaleFactor Endgame<ScaleFactor, KBPKB>::apply(const Position& pos) const {
712
713   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
714   assert(pos.piece_count(strongerSide, BISHOP) == 1);
715   assert(pos.piece_count(strongerSide, PAWN) == 1);
716   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
717   assert(pos.piece_count(weakerSide, BISHOP) == 1);
718   assert(pos.piece_count(weakerSide, PAWN) == 0);
719
720   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
721   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
722   Square weakerBishopSq = pos.piece_list(weakerSide, BISHOP)[0];
723   Square weakerKingSq = pos.king_square(weakerSide);
724
725   // Case 1: Defending king blocks the pawn, and cannot be driven away
726   if (   square_file(weakerKingSq) == square_file(pawnSq)
727       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
728       && (   opposite_color_squares(weakerKingSq, strongerBishopSq)
729           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
730       return SCALE_FACTOR_ZERO;
731
732   // Case 2: Opposite colored bishops
733   if (opposite_color_squares(strongerBishopSq, weakerBishopSq))
734   {
735       // We assume that the position is drawn in the following three situations:
736       //
737       //   a. The pawn is on rank 5 or further back.
738       //   b. The defending king is somewhere in the pawn's path.
739       //   c. The defending bishop attacks some square along the pawn's path,
740       //      and is at least three squares away from the pawn.
741       //
742       // These rules are probably not perfect, but in practice they work
743       // reasonably well.
744
745       if (relative_rank(strongerSide, pawnSq) <= RANK_5)
746           return SCALE_FACTOR_ZERO;
747       else
748       {
749           Bitboard path = squares_in_front_of(strongerSide, pawnSq);
750
751           if (path & pos.pieces(KING, weakerSide))
752               return SCALE_FACTOR_ZERO;
753
754           if (  (pos.attacks_from<BISHOP>(weakerBishopSq) & path)
755               && square_distance(weakerBishopSq, pawnSq) >= 3)
756               return SCALE_FACTOR_ZERO;
757       }
758   }
759   return SCALE_FACTOR_NONE;
760 }
761
762
763 /// KBPPKBScalingFunction scales KBPP vs KB endgames. It detects a few basic
764 /// draws with opposite-colored bishops.
765 template<>
766 ScaleFactor Endgame<ScaleFactor, KBPPKB>::apply(const Position& pos) const {
767
768   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
769   assert(pos.piece_count(strongerSide, BISHOP) == 1);
770   assert(pos.piece_count(strongerSide, PAWN) == 2);
771   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
772   assert(pos.piece_count(weakerSide, BISHOP) == 1);
773   assert(pos.piece_count(weakerSide, PAWN) == 0);
774
775   Square wbsq = pos.piece_list(strongerSide, BISHOP)[0];
776   Square bbsq = pos.piece_list(weakerSide, BISHOP)[0];
777
778   if (!opposite_color_squares(wbsq, bbsq))
779       return SCALE_FACTOR_NONE;
780
781   Square ksq = pos.king_square(weakerSide);
782   Square psq1 = pos.piece_list(strongerSide, PAWN)[0];
783   Square psq2 = pos.piece_list(strongerSide, PAWN)[1];
784   Rank r1 = square_rank(psq1);
785   Rank r2 = square_rank(psq2);
786   Square blockSq1, blockSq2;
787
788   if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
789   {
790       blockSq1 = psq1 + pawn_push(strongerSide);
791       blockSq2 = make_square(square_file(psq2), square_rank(psq1));
792   }
793   else
794   {
795       blockSq1 = psq2 + pawn_push(strongerSide);
796       blockSq2 = make_square(square_file(psq1), square_rank(psq2));
797   }
798
799   switch (file_distance(psq1, psq2))
800   {
801   case 0:
802     // Both pawns are on the same file. Easy draw if defender firmly controls
803     // some square in the frontmost pawn's path.
804     if (   square_file(ksq) == square_file(blockSq1)
805         && relative_rank(strongerSide, ksq) >= relative_rank(strongerSide, blockSq1)
806         && opposite_color_squares(ksq, wbsq))
807         return SCALE_FACTOR_ZERO;
808     else
809         return SCALE_FACTOR_NONE;
810
811   case 1:
812     // Pawns on neighboring files. Draw if defender firmly controls the square
813     // in front of the frontmost pawn's path, and the square diagonally behind
814     // this square on the file of the other pawn.
815     if (   ksq == blockSq1
816         && opposite_color_squares(ksq, wbsq)
817         && (   bbsq == blockSq2
818             || (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(BISHOP, weakerSide))
819             || abs(r1 - r2) >= 2))
820         return SCALE_FACTOR_ZERO;
821
822     else if (   ksq == blockSq2
823              && opposite_color_squares(ksq, wbsq)
824              && (   bbsq == blockSq1
825                  || (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(BISHOP, weakerSide))))
826         return SCALE_FACTOR_ZERO;
827     else
828         return SCALE_FACTOR_NONE;
829
830   default:
831     // The pawns are not on the same file or adjacent files. No scaling.
832     return SCALE_FACTOR_NONE;
833   }
834 }
835
836
837 /// KBPKNScalingFunction scales KBP vs KN endgames. There is a single rule:
838 /// If the defending king is somewhere along the path of the pawn, and the
839 /// square of the king is not of the same color as the stronger side's bishop,
840 /// it's a draw.
841 template<>
842 ScaleFactor Endgame<ScaleFactor, KBPKN>::apply(const Position& pos) const {
843
844   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
845   assert(pos.piece_count(strongerSide, BISHOP) == 1);
846   assert(pos.piece_count(strongerSide, PAWN) == 1);
847   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
848   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
849   assert(pos.piece_count(weakerSide, PAWN) == 0);
850
851   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
852   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
853   Square weakerKingSq = pos.king_square(weakerSide);
854
855   if (   square_file(weakerKingSq) == square_file(pawnSq)
856       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
857       && (   opposite_color_squares(weakerKingSq, strongerBishopSq)
858           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
859       return SCALE_FACTOR_ZERO;
860
861   return SCALE_FACTOR_NONE;
862 }
863
864
865 /// KNPKScalingFunction scales KNP vs K endgames. There is a single rule:
866 /// If the pawn is a rook pawn on the 7th rank and the defending king prevents
867 /// the pawn from advancing, the position is drawn.
868 template<>
869 ScaleFactor Endgame<ScaleFactor, KNPK>::apply(const Position& pos) const {
870
871   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
872   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
873   assert(pos.piece_count(strongerSide, PAWN) == 1);
874   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
875   assert(pos.piece_count(weakerSide, PAWN) == 0);
876
877   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
878   Square weakerKingSq = pos.king_square(weakerSide);
879
880   if (   pawnSq == relative_square(strongerSide, SQ_A7)
881       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_A8)) <= 1)
882       return SCALE_FACTOR_ZERO;
883
884   if (   pawnSq == relative_square(strongerSide, SQ_H7)
885       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_H8)) <= 1)
886       return SCALE_FACTOR_ZERO;
887
888   return SCALE_FACTOR_NONE;
889 }
890
891
892 /// KPKPScalingFunction scales KP vs KP endgames. This is done by removing
893 /// the weakest side's pawn and probing the KP vs K bitbase: If the weakest
894 /// side has a draw without the pawn, she probably has at least a draw with
895 /// the pawn as well. The exception is when the stronger side's pawn is far
896 /// advanced and not on a rook file; in this case it is often possible to win
897 /// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
898 template<>
899 ScaleFactor Endgame<ScaleFactor, KPKP>::apply(const Position& pos) const {
900
901   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
902   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
903   assert(pos.piece_count(WHITE, PAWN) == 1);
904   assert(pos.piece_count(BLACK, PAWN) == 1);
905
906   Square wksq, bksq, wpsq;
907   Color stm;
908
909   if (strongerSide == WHITE)
910   {
911       wksq = pos.king_square(WHITE);
912       bksq = pos.king_square(BLACK);
913       wpsq = pos.piece_list(WHITE, PAWN)[0];
914       stm = pos.side_to_move();
915   }
916   else
917   {
918       wksq = flip_square(pos.king_square(BLACK));
919       bksq = flip_square(pos.king_square(WHITE));
920       wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
921       stm = opposite_color(pos.side_to_move());
922   }
923
924   if (square_file(wpsq) >= FILE_E)
925   {
926       wksq = flop_square(wksq);
927       bksq = flop_square(bksq);
928       wpsq = flop_square(wpsq);
929   }
930
931   // If the pawn has advanced to the fifth rank or further, and is not a
932   // rook pawn, it's too dangerous to assume that it's at least a draw.
933   if (   square_rank(wpsq) >= RANK_5
934       && square_file(wpsq) != FILE_A)
935       return SCALE_FACTOR_NONE;
936
937   // Probe the KPK bitbase with the weakest side's pawn removed. If it's a
938   // draw, it's probably at least a draw even with the pawn.
939   return probe_kpk_bitbase(wksq, wpsq, bksq, stm) ? SCALE_FACTOR_NONE : SCALE_FACTOR_ZERO;
940 }