]> git.sesse.net Git - stockfish/blob - src/material.cpp
9f0fb9ed295fba16038a89081a8ab92c56cab797
[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 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 #include <map>
27
28 #include "material.h"
29
30
31 ////
32 //// Local definitions
33 ////
34
35 namespace {
36
37   const Value BishopPairMidgameBonus = Value(100);
38   const Value BishopPairEndgameBonus = Value(100);
39
40   Key KNNKMaterialKey, KKNNMaterialKey;
41
42 }
43
44 ////
45 //// Classes
46 ////
47
48
49 /// See header for a class description. It is declared here to avoid
50 /// to include <map> in the header file.
51
52 class EndgameFunctions {
53
54 public:
55   EndgameFunctions();
56   EndgameEvaluationFunction* getEEF(Key key) const;
57   ScalingFunction* getESF(Key key, Color* c) const;
58
59 private:
60   void add(Key k, EndgameEvaluationFunction* f);
61   void add(Key k, Color c, ScalingFunction* f);
62
63   struct ScalingInfo
64   {
65       Color col;
66       ScalingFunction* fun;
67   };
68
69   std::map<Key, EndgameEvaluationFunction*> EEFmap;
70   std::map<Key, ScalingInfo> ESFmap;
71 };
72
73
74 ////
75 //// Functions
76 ////
77
78
79 /// Constructor for the MaterialInfoTable class
80
81 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
82
83   size = numOfEntries;
84   entries = new MaterialInfo[size];
85   funcs = new EndgameFunctions();
86   if (!entries || !funcs)
87   {
88       std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
89                 << " bytes for material hash table." << std::endl;
90       exit(EXIT_FAILURE);
91   }
92   clear();
93 }
94
95
96 /// Destructor for the MaterialInfoTable class
97
98 MaterialInfoTable::~MaterialInfoTable() {
99
100   delete [] entries;
101   delete funcs;
102 }
103
104
105 /// MaterialInfoTable::clear() clears a material hash table by setting
106 /// all entries to 0.
107
108 void MaterialInfoTable::clear() {
109
110   memset(entries, 0, size * sizeof(MaterialInfo));
111 }
112
113
114 /// MaterialInfoTable::get_material_info() takes a position object as input,
115 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
116 /// If the material configuration is not already present in the table, it
117 /// is stored there, so we don't have to recompute everything when the
118 /// same material configuration occurs again.
119
120 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
121
122   Key key = pos.get_material_key();
123   int index = key & (size - 1);
124   MaterialInfo* mi = entries + index;
125
126   // If mi->key matches the position's material hash key, it means that we
127   // have analysed this material configuration before, and we can simply
128   // return the information we found the last time instead of recomputing it.
129   if (mi->key == key)
130       return mi;
131
132   // Clear the MaterialInfo object, and set its key
133   mi->clear();
134   mi->key = key;
135
136   // A special case before looking for a specialized evaluation function
137   // KNN vs K is a draw.
138   if (key == KNNKMaterialKey || key == KKNNMaterialKey)
139   {
140       mi->factor[WHITE] = mi->factor[BLACK] = 0;
141       return mi;
142   }
143
144   // Let's look if we have a specialized evaluation function for this
145   // particular material configuration.
146   if ((mi->evaluationFunction = funcs->getEEF(key)) != NULL)
147       return mi;
148
149   else if (   pos.non_pawn_material(BLACK) == Value(0)
150            && pos.piece_count(BLACK, PAWN) == 0
151            && pos.non_pawn_material(WHITE) >= RookValueEndgame)
152   {
153       mi->evaluationFunction = &EvaluateKXK;
154       return mi;
155   }
156   else if (   pos.non_pawn_material(WHITE) == Value(0)
157            && pos.piece_count(WHITE, PAWN) == 0
158            && pos.non_pawn_material(BLACK) >= RookValueEndgame)
159   {
160       mi->evaluationFunction = &EvaluateKKX;
161       return mi;
162   }
163
164   // OK, we didn't find any special evaluation function for the current
165   // material configuration. Is there a suitable scaling function?
166   //
167   // The code below is rather messy, and it could easily get worse later,
168   // if we decide to add more special cases.  We face problems when there
169   // are several conflicting applicable scaling functions and we need to
170   // decide which one to use.
171   Color c;
172   ScalingFunction* sf;
173
174   if ((sf = funcs->getESF(key, &c)) != NULL)
175   {
176       mi->scalingFunction[c] = sf;
177       return mi;
178   }
179
180   if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
181       && pos.piece_count(WHITE, BISHOP) == 1
182       && pos.piece_count(WHITE, PAWN) >= 1)
183       mi->scalingFunction[WHITE] = &ScaleKBPK;
184
185   if (   pos.non_pawn_material(BLACK) == BishopValueMidgame
186       && pos.piece_count(BLACK, BISHOP) == 1
187       && pos.piece_count(BLACK, PAWN) >= 1)
188       mi->scalingFunction[BLACK] = &ScaleKKBP;
189
190   if (   pos.piece_count(WHITE, PAWN) == 0
191       && pos.non_pawn_material(WHITE) == QueenValueMidgame
192       && pos.piece_count(WHITE, QUEEN) == 1
193       && pos.piece_count(BLACK, ROOK) == 1
194       && pos.piece_count(BLACK, PAWN) >= 1)
195       mi->scalingFunction[WHITE] = &ScaleKQKRP;
196
197   else if (   pos.piece_count(BLACK, PAWN) == 0
198            && pos.non_pawn_material(BLACK) == QueenValueMidgame
199            && pos.piece_count(BLACK, QUEEN) == 1
200            && pos.piece_count(WHITE, ROOK) == 1
201            && pos.piece_count(WHITE, PAWN) >= 1)
202       mi->scalingFunction[BLACK] = &ScaleKRPKQ;
203
204   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
205   {
206       if (pos.piece_count(BLACK, PAWN) == 0)
207       {
208           assert(pos.piece_count(WHITE, PAWN) >= 2);
209           mi->scalingFunction[WHITE] = &ScaleKPsK;
210       }
211       else if (pos.piece_count(WHITE, PAWN) == 0)
212       {
213           assert(pos.piece_count(BLACK, PAWN) >= 2);
214           mi->scalingFunction[BLACK] = &ScaleKKPs;
215       }
216       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
217       {
218           mi->scalingFunction[WHITE] = &ScaleKPKPw;
219           mi->scalingFunction[BLACK] = &ScaleKPKPb;
220       }
221   }
222
223   // Evaluate the material balance
224
225   int sign;
226   Value egValue = Value(0);
227   Value mgValue = Value(0);
228
229   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
230   {
231     // No pawns makes it difficult to win, even with a material advantage
232     if (   pos.piece_count(c, PAWN) == 0
233         && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
234     {
235         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
236             || pos.non_pawn_material(c) < RookValueMidgame)
237             mi->factor[c] = 0;
238         else
239         {
240             switch (pos.piece_count(c, BISHOP)) {
241             case 2:
242                 mi->factor[c] = 32;
243                 break;
244             case 1:
245                 mi->factor[c] = 12;
246                 break;
247             case 0:
248                 mi->factor[c] = 6;
249                 break;
250             }
251         }
252     }
253
254     // Bishop pair
255     if (pos.piece_count(c, BISHOP) >= 2)
256     {
257         mgValue += sign * BishopPairMidgameBonus;
258         egValue += sign * BishopPairEndgameBonus;
259     }
260
261     // Knights are stronger when there are many pawns on the board.  The
262     // formula is taken from Larry Kaufman's paper "The Evaluation of Material
263     // Imbalances in Chess":
264     // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
265     mgValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
266     egValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
267
268     // Redundancy of major pieces, again based on Kaufman's paper:
269     if (pos.piece_count(c, ROOK) >= 1)
270     {
271         Value v = Value((pos.piece_count(c, ROOK) - 1) * 32 + pos.piece_count(c, QUEEN) * 16);
272         mgValue -= sign * v;
273         egValue -= sign * v;
274     }
275   }
276   mi->mgValue = int16_t(mgValue);
277   mi->egValue = int16_t(egValue);
278   return mi;
279 }
280
281
282 /// EndgameFunctions member definitions. This class is used to store the maps
283 /// of end game and scaling functions that MaterialInfoTable will query for 
284 /// each key. The maps are constant and are populated only at construction,
285 /// but are per-thread instead of globals to avoid expensive locks.
286
287 EndgameFunctions::EndgameFunctions() {
288
289   typedef Key ZM[2][8][16];
290   const ZM& z = Position::zobMaterial;
291
292   static const Color W = WHITE;
293   static const Color B = BLACK;
294
295   KNNKMaterialKey = z[W][KNIGHT][1] ^ z[W][KNIGHT][2];
296   KKNNMaterialKey = z[B][KNIGHT][1] ^ z[B][KNIGHT][2];
297
298   add(z[W][PAWN][1], &EvaluateKPK);
299   add(z[B][PAWN][1], &EvaluateKKP);
300
301   add(z[W][BISHOP][1] ^ z[W][KNIGHT][1], &EvaluateKBNK);
302   add(z[B][BISHOP][1] ^ z[B][KNIGHT][1], &EvaluateKKBN);
303   add(z[W][ROOK][1]   ^ z[B][PAWN][1],   &EvaluateKRKP);
304   add(z[W][PAWN][1]   ^ z[B][ROOK][1],   &EvaluateKPKR);
305   add(z[W][ROOK][1]   ^ z[B][BISHOP][1], &EvaluateKRKB);
306   add(z[W][BISHOP][1] ^ z[B][ROOK][1],   &EvaluateKBKR);
307   add(z[W][ROOK][1]   ^ z[B][KNIGHT][1], &EvaluateKRKN);
308   add(z[W][KNIGHT][1] ^ z[B][ROOK][1],   &EvaluateKNKR);
309   add(z[W][QUEEN][1]  ^ z[B][ROOK][1],   &EvaluateKQKR);
310   add(z[W][ROOK][1]   ^ z[B][QUEEN][1],  &EvaluateKRKQ);
311
312   add(z[W][KNIGHT][1] ^ z[W][PAWN][1], W, &ScaleKNPK);
313   add(z[B][KNIGHT][1] ^ z[B][PAWN][1], B, &ScaleKKNP);
314
315   add(z[W][ROOK][1]   ^ z[W][PAWN][1]   ^ z[B][ROOK][1]  , W, &ScaleKRPKR);
316   add(z[W][ROOK][1]   ^ z[B][ROOK][1]   ^ z[B][PAWN][1]  , B, &ScaleKRKRP);
317   add(z[W][BISHOP][1] ^ z[W][PAWN][1]   ^ z[B][BISHOP][1], W, &ScaleKBPKB);
318   add(z[W][BISHOP][1] ^ z[B][BISHOP][1] ^ z[B][PAWN][1]  , B, &ScaleKBKBP);
319   add(z[W][BISHOP][1] ^ z[W][PAWN][1]   ^ z[B][KNIGHT][1], W, &ScaleKBPKN);
320   add(z[W][KNIGHT][1] ^ z[B][BISHOP][1] ^ z[B][PAWN][1]  , B, &ScaleKNKBP);
321
322   add(z[W][ROOK][1] ^ z[W][PAWN][1] ^ z[W][PAWN][2] ^ z[B][ROOK][1] ^ z[B][PAWN][1], W, &ScaleKRPPKRP);
323   add(z[W][ROOK][1] ^ z[W][PAWN][1] ^ z[B][ROOK][1] ^ z[B][PAWN][1] ^ z[B][PAWN][2], B, &ScaleKRPKRPP);
324 }
325
326 void EndgameFunctions::add(Key k, EndgameEvaluationFunction* f) {
327
328   EEFmap.insert(std::pair<Key, EndgameEvaluationFunction*>(k, f));
329 }
330
331 void EndgameFunctions::add(Key k, Color c, ScalingFunction* f) {
332
333   ScalingInfo s = {c, f};
334   ESFmap.insert(std::pair<Key, ScalingInfo>(k, s));
335 }
336
337 EndgameEvaluationFunction* EndgameFunctions::getEEF(Key key) const {
338
339   std::map<Key, EndgameEvaluationFunction*>::const_iterator it(EEFmap.find(key));
340   return (it != EEFmap.end() ? it->second : NULL);
341 }
342
343 ScalingFunction* EndgameFunctions::getESF(Key key, Color* c) const {
344
345   std::map<Key, ScalingInfo>::const_iterator it(ESFmap.find(key));
346   if (it == ESFmap.end())
347       return NULL;
348
349   *c = it->second.col;
350   return it->second.fun;
351 }