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