]> git.sesse.net Git - stockfish/blob - src/material.cpp
Sync with master
[stockfish] / src / material.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-2015 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 <algorithm> // For std::min
21 #include <cassert>
22 #include <cstring>   // For std::memset
23
24 #include "material.h"
25 #include "thread.h"
26
27 using namespace std;
28
29 namespace {
30
31   // Polynomial material imbalance parameters
32
33   //                      pair  pawn knight bishop rook queen
34   const int Linear[6] = { 1852, -162, -1122, -183,  249, -154 };
35
36   const int QuadraticOurs[][PIECE_TYPE_NB] = {
37     //            OUR PIECES
38     // pair pawn knight bishop rook queen
39     {   0                               }, // Bishop pair
40     {  39,    2                         }, // Pawn
41     {  35,  271,  -4                    }, // Knight      OUR PIECES
42     {   0,  105,   4,    0              }, // Bishop
43     { -27,   -2,  46,   100,  -141      }, // Rook
44     {-177,   25, 129,   142,  -137,   0 }  // Queen
45   };
46
47   const int QuadraticTheirs[][PIECE_TYPE_NB] = {
48     //           THEIR PIECES
49     // pair pawn knight bishop rook queen
50     {   0                               }, // Bishop pair
51     {  37,    0                         }, // Pawn
52     {  10,   62,   0                    }, // Knight      OUR PIECES
53     {  57,   64,  39,     0             }, // Bishop
54     {  50,   40,  23,   -22,    0       }, // Rook
55     {  98,  105, -39,   141,  274,    0 }  // Queen
56   };
57
58   // Endgame evaluation and scaling functions are accessed directly and not through
59   // the function maps because they correspond to more than one material hash key.
60   Endgame<KXK>    EvaluateKXK[] = { Endgame<KXK>(WHITE),    Endgame<KXK>(BLACK) };
61
62   Endgame<KBPsK>  ScaleKBPsK[]  = { Endgame<KBPsK>(WHITE),  Endgame<KBPsK>(BLACK) };
63   Endgame<KQKRPs> ScaleKQKRPs[] = { Endgame<KQKRPs>(WHITE), Endgame<KQKRPs>(BLACK) };
64   Endgame<KPsK>   ScaleKPsK[]   = { Endgame<KPsK>(WHITE),   Endgame<KPsK>(BLACK) };
65   Endgame<KPKP>   ScaleKPKP[]   = { Endgame<KPKP>(WHITE),   Endgame<KPKP>(BLACK) };
66
67   // Helper templates used to detect a given material distribution
68   template<Color Us> bool is_KXK(const Position& pos) {
69     const Color Them = (Us == WHITE ? BLACK : WHITE);
70     return  !more_than_one(pos.pieces(Them))
71           && pos.non_pawn_material(Us) >= RookValueMg;
72   }
73
74   template<Color Us> bool is_KBPsKs(const Position& pos) {
75     return   pos.non_pawn_material(Us) == BishopValueMg
76           && pos.count<BISHOP>(Us) == 1
77           && pos.count<PAWN  >(Us) >= 1;
78   }
79
80   template<Color Us> bool is_KQKRPs(const Position& pos) {
81     const Color Them = (Us == WHITE ? BLACK : WHITE);
82     return  !pos.count<PAWN>(Us)
83           && pos.non_pawn_material(Us) == QueenValueMg
84           && pos.count<QUEEN>(Us)  == 1
85           && pos.count<ROOK>(Them) == 1
86           && pos.count<PAWN>(Them) >= 1;
87   }
88
89   /// imbalance() calculates the imbalance by comparing the piece count of each
90   /// piece type for both colors.
91
92   template<Color Us>
93   int imbalance(const int pieceCount[][PIECE_TYPE_NB]) {
94
95     const Color Them = (Us == WHITE ? BLACK : WHITE);
96
97     int bonus = 0;
98
99     // Second-degree polynomial material imbalance by Tord Romstad
100     for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; ++pt1)
101     {
102         if (!pieceCount[Us][pt1])
103             continue;
104
105         int v = Linear[pt1];
106
107         for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; ++pt2)
108             v +=  QuadraticOurs[pt1][pt2] * pieceCount[Us][pt2]
109                 + QuadraticTheirs[pt1][pt2] * pieceCount[Them][pt2];
110
111         bonus += pieceCount[Us][pt1] * v;
112     }
113
114     return bonus;
115   }
116
117 } // namespace
118
119 namespace Material {
120
121 /// Material::probe() looks up the current position's material configuration in
122 /// the material hash table. It returns a pointer to the Entry if the position
123 /// is found. Otherwise a new Entry is computed and stored there, so we don't
124 /// have to recompute all when the same material configuration occurs again.
125
126 Entry* probe(const Position& pos) {
127
128   Key key = pos.material_key();
129   Entry* e = pos.this_thread()->materialTable[key];
130
131   if (e->key == key)
132       return e;
133
134   std::memset(e, 0, sizeof(Entry));
135   e->key = key;
136   e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
137   e->gamePhase = pos.game_phase();
138
139   // Let's look if we have a specialized evaluation function for this particular
140   // material configuration. Firstly we look for a fixed configuration one, then
141   // for a generic one if the previous search failed.
142   if ((e->evaluationFunction = pos.this_thread()->endgames.probe<Value>(key)) != nullptr)
143       return e;
144
145   if (is_KXK<WHITE>(pos))
146   {
147       e->evaluationFunction = &EvaluateKXK[WHITE];
148       return e;
149   }
150
151   if (is_KXK<BLACK>(pos))
152   {
153       e->evaluationFunction = &EvaluateKXK[BLACK];
154       return e;
155   }
156
157   // OK, we didn't find any special evaluation function for the current material
158   // configuration. Is there a suitable specialized scaling function?
159   EndgameBase<ScaleFactor>* sf;
160
161   if ((sf = pos.this_thread()->endgames.probe<ScaleFactor>(key)) != nullptr)
162   {
163       e->scalingFunction[sf->strong_side()] = sf; // Only strong color assigned
164       return e;
165   }
166
167   // We didn't find any specialized scaling function, so fall back on generic
168   // ones that refer to more than one material distribution. Note that in this
169   // case we don't return after setting the function.
170   if (is_KBPsKs<WHITE>(pos))
171       e->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
172
173   if (is_KBPsKs<BLACK>(pos))
174       e->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
175
176   if (is_KQKRPs<WHITE>(pos))
177       e->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
178
179   else if (is_KQKRPs<BLACK>(pos))
180       e->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
181
182   Value npm_w = pos.non_pawn_material(WHITE);
183   Value npm_b = pos.non_pawn_material(BLACK);
184
185   if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN)) // Only pawns on the board
186   {
187       if (!pos.count<PAWN>(BLACK))
188       {
189           assert(pos.count<PAWN>(WHITE) >= 2);
190
191           e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
192       }
193       else if (!pos.count<PAWN>(WHITE))
194       {
195           assert(pos.count<PAWN>(BLACK) >= 2);
196
197           e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
198       }
199       else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1)
200       {
201           // This is a special case because we set scaling functions
202           // for both colors instead of only one.
203           e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
204           e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
205       }
206   }
207
208   // Zero or just one pawn makes it difficult to win, even with a small material
209   // advantage. This catches some trivial draws like KK, KBK and KNK and gives a
210   // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
211   if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
212       e->factor[WHITE] = uint8_t(npm_w <  RookValueMg   ? SCALE_FACTOR_DRAW :
213                                  npm_b <= BishopValueMg ? 4 : 12);
214
215   if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
216       e->factor[BLACK] = uint8_t(npm_b <  RookValueMg   ? SCALE_FACTOR_DRAW :
217                                  npm_w <= BishopValueMg ? 4 : 12);
218
219   if (pos.count<PAWN>(WHITE) == 1 && npm_w - npm_b <= BishopValueMg)
220       e->factor[WHITE] = (uint8_t) SCALE_FACTOR_ONEPAWN;
221
222   if (pos.count<PAWN>(BLACK) == 1 && npm_b - npm_w <= BishopValueMg)
223       e->factor[BLACK] = (uint8_t) SCALE_FACTOR_ONEPAWN;
224
225   // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
226   // for the bishop pair "extended piece", which allows us to be more flexible
227   // in defining bishop pair bonuses.
228   const int PieceCount[COLOR_NB][PIECE_TYPE_NB] = {
229   { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE),
230     pos.count<BISHOP>(WHITE)    , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) },
231   { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK),
232     pos.count<BISHOP>(BLACK)    , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } };
233
234   e->value = int16_t((imbalance<WHITE>(PieceCount) - imbalance<BLACK>(PieceCount)) / 16);
235   return e;
236 }
237
238 } // namespace Material