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