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