probdist_mute(): Introduce helper
[pachi.git] / board.h
blob328c9bc986af02aa3f950b7a31a737ffd4ec7ab5
1 #ifndef ZZGO_BOARD_H
2 #define ZZGO_BOARD_H
4 #include <inttypes.h>
5 #include <stdbool.h>
6 #include <stdint.h>
8 #include "util.h"
9 #include "stone.h"
10 #include "move.h"
11 #include "probdist.h"
13 struct features_gamma;
16 /* The board implementation has bunch of optional features.
17 * Turn them on below: */
19 #define WANT_BOARD_C // capturable groups queue
21 //#define BOARD_SIZE 9 // constant board size, allows better optimization
23 //#define BOARD_SPATHASH // incremental patternsp.h hashes
24 #define BOARD_SPATHASH_MAXD 3 // maximal diameter
26 #define BOARD_PAT3 // incremental 3x3 pattern codes
28 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
29 //#define BOARD_GAMMA 1 // incremental probability distribution (requires BOARD_TRAITS, BOARD_PAT3)
32 /* Some engines might normalize their reading and skip symmetrical
33 * moves. We will tell them how can they do it. */
34 struct board_symmetry {
35 /* Playground is in this rectangle. */
36 int x1, x2, y1, y2;
37 /* d == 0: Full rectangle
38 * d == 1: Top triangle */
39 int d;
40 /* General symmetry type. */
41 /* Note that the above is redundant to this, but just provided
42 * for easier usage. */
43 enum {
44 SYM_FULL,
45 SYM_DIAG_UP,
46 SYM_DIAG_DOWN,
47 SYM_HORIZ,
48 SYM_VERT,
49 SYM_NONE
50 } type;
54 typedef uint64_t hash_t;
55 #define PRIhash PRIx64
58 /* Note that "group" is only chain of stones that is solidly
59 * connected for us. */
60 typedef coord_t group_t;
62 struct group {
63 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
64 * don't care. */
65 /* _Combination_ of these two values can make some difference
66 * in performance - fine-tune. */
67 #define GROUP_KEEP_LIBS 10
68 // refill lib[] only when we hit this; this must be at least 2!
69 // Moggy requires at least 3 - see below for semantic impact.
70 #define GROUP_REFILL_LIBS 5
71 coord_t lib[GROUP_KEEP_LIBS];
72 /* libs is only LOWER BOUND for the number of real liberties!!!
73 * It denotes only number of items in lib[], thus you can rely
74 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
75 int libs;
78 struct neighbor_colors {
79 char colors[S_MAX];
83 /* Point traits bitmap; we update this information incrementally,
84 * it can be used e.g. for fast pattern.h features matching. */
85 struct btraits {
86 /* Number of neighbors we can capture. 0=this move is
87 * not capturing, 1..4=this many neighbors we can capture
88 * (can be multiple neighbors of same group). */
89 unsigned cap:3;
90 /* Whether it is SAFE to play here. This is essentially just
91 * cached result of board_safe_to_play(). (Of course the concept
92 * of "safety" is not perfect here, but it's the cheapest
93 * reasonable thing we can do.) */
94 bool safe:1;
95 /* Whether we need to re-compute this coordinate; used to
96 * weed out duplicates. Maintained only for S_BLACK. */
97 bool dirty:1;
101 /* You should treat this struct as read-only. Always call functions below if
102 * you want to change it. */
104 struct board {
105 int size; /* Including S_OFFBOARD margin - see below. */
106 int size2; /* size^2 */
107 int bits2; /* ceiling(log2(size2)) */
108 int captures[S_MAX];
109 float komi;
110 int handicap;
111 /* The ruleset is currently almost never taken into account;
112 * the board implementation is basically Chinese rules (handicap
113 * stones compensation) w/ suicide (or you can look at it as
114 * New Zealand w/o handi stones compensation), while the engine
115 * enforces no-suicide, making for real Chinese rules. */
116 enum {
117 RULES_CHINESE, /* default value */
118 RULES_AGA,
119 RULES_NEW_ZEALAND,
120 RULES_JAPANESE,
121 } rules;
123 /* Iterator offsets for foreach_neighbor*() */
124 int nei8[8], dnei[4];
126 int moves;
127 struct move last_move;
128 struct move last_move2; /* second-to-last move */
129 /* Whether we tried to add a hash twice; board_play*() can
130 * set this, but it will still carry out the move as well! */
131 bool superko_violation;
133 /* The following two structures are goban maps and are indexed by
134 * coord.pos. The map is surrounded by a one-point margin from
135 * S_OFFBOARD stones in order to speed up some internal loops.
136 * Some of the foreach iterators below might include these points;
137 * you need to handle them yourselves, if you need to. */
139 /* Stones played on the board */
140 enum stone *b; /* enum stone */
141 /* Group id the stones are part of; 0 == no group */
142 group_t *g;
143 /* Positions of next stones in the stone group; 0 == last stone */
144 coord_t *p;
145 /* Neighboring colors; numbers of neighbors of index color */
146 struct neighbor_colors *n;
147 /* Zobrist hash for each position */
148 hash_t *h;
149 #ifdef BOARD_SPATHASH
150 /* For spatial hashes, we use only 24 bits. */
151 /* [0] is d==1, we don't keep hash for d==0. */
152 /* We keep hashes for black-to-play ([][0]) and white-to-play
153 * ([][1], reversed stone colors since we match all patterns as
154 * black-to-play). */
155 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
156 #endif
157 #ifdef BOARD_PAT3
158 /* 3x3 pattern code for each position; see pattern3.h for encoding
159 * specification. The information is only valid for empty points. */
160 uint16_t *pat3;
161 #endif
162 #ifdef BOARD_TRAITS
163 /* Incrementally matched point traits information, black-to-play
164 * ([][0]) and white-to-play ([][1]). */
165 /* The information is only valid for empty points. */
166 struct btraits (*t)[2];
167 #endif
168 #ifdef BOARD_GAMMA
169 /* Relative probabilities of moves being played next, computed by
170 * multiplying gammas of the appropriate pattern features based on
171 * pat3 and traits (see pattern.h). The probability distribution
172 * is maintained over the full board grid. */
173 /* - Always invalid moves are guaranteed to have zero probability.
174 * - Self-eye-filling moves will always have zero probability.
175 * - Ko-prohibited moves might have non-zero probability.
176 * - FEAT_CONTIGUITY is not accounted for in the probability. */
177 struct probdist prob[2];
178 #endif
179 /* Cached information on x-y coordinates so that we avoid division. */
180 uint8_t (*coord)[2];
182 /* Group information - indexed by gid (which is coord of base group stone) */
183 struct group *gi;
185 /* Positions of free positions - queue (not map) */
186 /* Note that free position here is any valid move; including single-point eyes!
187 * However, pass is not included. */
188 coord_t *f; int flen;
190 #ifdef WANT_BOARD_C
191 /* Queue of capturable groups */
192 group_t *c; int clen;
193 #endif
195 #ifdef BOARD_TRAITS
196 /* Queue of positions that need their traits updated */
197 coord_t *tq; int tqlen;
198 #endif
200 /* Symmetry information */
201 struct board_symmetry symmetry;
203 /* Last ko played on the board. */
204 struct move last_ko;
205 int last_ko_age;
207 /* Basic ko check */
208 struct move ko;
210 /* Engine-specific state; persistent through board development,
211 * is reset only at clear_board. */
212 void *es;
214 /* Playout-specific state; persistent through board development,
215 * but its lifetime is maintained in play_random_game(); it should
216 * not be set outside of it. */
217 void *ps;
219 #ifdef BOARD_GAMMA
220 /* Gamma values for probability distribution; user must setup
221 * this pointer before any move is played, using board_gamma_set(). */
222 struct features_gamma *gamma;
223 /* Whether to compute the 'safe' trait using board_safe_to_play()
224 * (false) or is_bad_selfatari() (true, much slower). */
225 bool precise_selfatari;
226 #endif
229 /* --- PRIVATE DATA --- */
231 /* For superko check: */
233 /* Board "history" - hashes encountered. Size of the hash should be
234 * >> board_size^2. */
235 #define history_hash_bits 12
236 #define history_hash_mask ((1 << history_hash_bits) - 1)
237 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
238 #define history_hash_next(i) ((i + 1) & history_hash_mask)
239 hash_t history_hash[1 << history_hash_bits];
240 /* Hash of current board position. */
241 hash_t hash;
244 #ifdef BOARD_SIZE
245 /* Avoid unused variable warnings */
246 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
247 #define board_size2(b_) (board_size(b_) * board_size(b_))
248 #else
249 #define board_size(b_) ((b_)->size)
250 #define board_size2(b_) ((b_)->size2)
251 #endif
253 #if BOARD_SIZE == 19
254 # define board_bits2(b_) 9
255 #elif BOARD_SIZE == 13
256 # define board_bits2(b_) 8
257 #elif BOARD_SIZE == 9
258 # define board_bits2(b_) 7
259 #else
260 # define board_bits2(b_) ((b_)->bits2)
261 #endif
263 #define board_at(b_, c) ((b_)->b[c])
264 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
266 #define group_at(b_, c) ((b_)->g[c])
267 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
269 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
270 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
271 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
272 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
273 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
274 #define immediate_liberty_count(b_, coord) (4 - neighbor_count_at(b_, coord, S_BLACK) - neighbor_count_at(b_, coord, S_WHITE) - neighbor_count_at(b_, coord, S_OFFBOARD))
276 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
278 #define groupnext_at(b_, c) ((b_)->p[c])
279 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
281 #define group_base(g_) (g_)
282 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
283 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
284 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
286 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
288 struct board *board_init(void);
289 struct board *board_copy(struct board *board2, struct board *board1);
290 void board_done_noalloc(struct board *board);
291 void board_done(struct board *board);
292 /* size here is without the S_OFFBOARD margin. */
293 void board_resize(struct board *board, int size);
294 void board_clear(struct board *board);
296 struct FILE;
297 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
298 void board_print(struct board *board, FILE *f);
299 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
301 /* Place given handicap on the board; coordinates are printed to f. */
302 void board_handicap(struct board *board, int stones, FILE *f);
304 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
305 int board_play(struct board *board, struct move *m);
306 /* Like above, but plays random move; the move coordinate is recorded
307 * to *coord. This method will never fill your own eye. pass is played
308 * when no move can be played. You can impose extra restrictions if you
309 * supply your own permit function; the permit function can also modify
310 * the move coordinate to redirect the move elsewhere. */
311 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
312 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
314 /* Returns true if given move can be played. */
315 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
316 static bool board_is_valid_move(struct board *b, struct move *m);
317 /* Returns true if ko was just taken. */
318 static bool board_playing_ko_threat(struct board *b);
319 /* Returns 0 or ID of neighboring group in atari. */
320 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
321 /* Returns true if the move is not obvious self-atari. */
322 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
324 /* Adjust symmetry information as if given coordinate has been played. */
325 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
326 /* Associate a set of feature gamma values (for pd building) with the board. */
327 void board_gamma_set(struct board *b, struct features_gamma *gamma, bool precise_selfatari);
328 /* Force re-compute of a probability distribution item. */
329 void board_gamma_update(struct board *b, coord_t coord, enum stone color);
331 /* Returns true if given coordinate has all neighbors of given color or the edge. */
332 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
333 /* Returns true if given coordinate could be a false eye; this check makes
334 * sense only if you already know the coordinate is_eyelike(). */
335 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
336 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
337 * at least tries to). */
338 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
339 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
340 enum stone board_get_one_point_eye(struct board *board, coord_t c);
342 /* board_official_score() is the scoring method for yielding score suitable
343 * for external presentation. For fast scoring of entirely filled boards
344 * (e.g. playouts), use board_fast_score(). */
345 /* Positive: W wins */
346 /* Compare number of stones + 1pt eyes. */
347 float board_fast_score(struct board *board);
348 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
349 struct move_queue;
350 float board_official_score(struct board *board, struct move_queue *mq);
352 /** Iterators */
354 #define foreach_point(board_) \
355 do { \
356 coord_t c = 0; \
357 for (; c < board_size(board_) * board_size(board_); c++)
358 #define foreach_point_and_pass(board_) \
359 do { \
360 coord_t c = pass; \
361 for (; c < board_size(board_) * board_size(board_); c++)
362 #define foreach_point_end \
363 } while (0)
365 #define foreach_in_group(board_, group_) \
366 do { \
367 struct board *board__ = board_; \
368 coord_t c = group_base(group_); \
369 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
370 do {
371 #define foreach_in_group_end \
372 c = c2; c2 = groupnext_at(board__, c2); \
373 } while (c != 0); \
374 } while (0)
376 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
377 * on S_OFFBOARD coordinates. */
378 #define foreach_neighbor(board_, coord_, loop_body) \
379 do { \
380 struct board *board__ = board_; \
381 coord_t coord__ = coord_; \
382 coord_t c; \
383 c = coord__ - 1; do { loop_body } while (0); \
384 c = coord__ - board_size(board__); do { loop_body } while (0); \
385 c = coord__ + 1; do { loop_body } while (0); \
386 c = coord__ + board_size(board__); do { loop_body } while (0); \
387 } while (0)
389 #define foreach_8neighbor(board_, coord_) \
390 do { \
391 int fn__i; \
392 coord_t c = (coord_); \
393 for (fn__i = 0; fn__i < 8; fn__i++) { \
394 c += (board_)->nei8[fn__i];
395 #define foreach_8neighbor_end \
397 } while (0)
399 #define foreach_diag_neighbor(board_, coord_) \
400 do { \
401 int fn__i; \
402 coord_t c = (coord_); \
403 for (fn__i = 0; fn__i < 4; fn__i++) { \
404 c += (board_)->dnei[fn__i];
405 #define foreach_diag_neighbor_end \
407 } while (0)
410 static inline bool
411 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
413 return (neighbor_count_at(board, coord, eye_color)
414 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
417 static inline bool
418 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
420 if (board_at(board, coord) != S_NONE)
421 return false;
422 if (!board_is_eyelike(board, coord, stone_other(color)))
423 return true;
424 /* Play within {true,false} eye-ish formation */
425 if (board->ko.coord == coord && board->ko.color == color)
426 return false;
427 #ifdef BOARD_TRAITS
428 /* XXX: Disallows suicide. */
429 return trait_at(board, coord, color).cap > 0;
430 #else
431 int groups_in_atari = 0;
432 foreach_neighbor(board, coord, {
433 group_t g = group_at(board, c);
434 groups_in_atari += (board_group_info(board, g).libs == 1);
436 return !!groups_in_atari;
437 #endif
440 static inline bool
441 board_is_valid_move(struct board *board, struct move *m)
443 return board_is_valid_play(board, m->color, m->coord);
446 static inline bool
447 board_playing_ko_threat(struct board *b)
449 return !is_pass(b->ko.coord);
452 static inline group_t
453 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
455 #ifdef BOARD_TRAITS
456 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
457 #endif
458 foreach_neighbor(b, coord, {
459 group_t g = group_at(b, c);
460 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
461 return g;
462 /* We return first match. */
464 return 0;
467 static inline bool
468 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
470 /* number of free neighbors */
471 int libs = immediate_liberty_count(b, coord);
472 if (libs > 1)
473 return true;
475 #ifdef BOARD_TRAITS
476 /* number of capturable enemy groups */
477 if (trait_at(b, coord, color).cap > 0)
478 return true; // XXX: We don't account for snapback.
479 /* number of non-capturable friendly groups */
480 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
481 if (noncap_ours < 1)
482 return false;
483 /*#else see below */
484 #endif
486 /* ok, but we need to check if they don't have just two libs. */
487 coord_t onelib = -1;
488 foreach_neighbor(b, coord, {
489 #ifndef BOARD_TRAITS
490 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
491 return true; // can capture; no snapback check
492 #endif
493 if (board_at(b, c) != color) continue;
494 group_t g = group_at(b, c);
495 if (board_group_info(b, g).libs == 1) continue; // in atari
496 if (board_group_info(b, g).libs == 2) { // two liberties
497 if (libs > 0) return true; // we already have one real liberty
498 // get the other liberty
499 coord_t lib = board_group_info(b, g).lib[0];
500 if (lib == coord) lib = board_group_info(b, g).lib[0];
501 /* we might be connecting two 2-lib groups, which is ok;
502 * so remember the other liberty and just make sure it's
503 * not the same one */
504 if (onelib >= 0 && lib != onelib) return true;
505 onelib = lib;
506 continue;
508 // many liberties
509 return true;
511 // no good support group
512 return false;
515 #endif