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