Moggy: Better nlibrate default for 19x19
[pachi/json.git] / board.h
blob01fad08e036cd9def756ce88146c2f1370b5104e
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef ZZGO_BOARD_H
6 #define ZZGO_BOARD_H
8 #include <inttypes.h>
9 #include <stdbool.h>
10 #include <stdint.h>
12 #include "util.h"
13 #include "stone.h"
14 #include "move.h"
16 struct fbook;
19 /* Maximum supported board size. (Without the S_OFFBOARD edges.) */
20 #define BOARD_MAX_SIZE 19
23 /* The board implementation has bunch of optional features.
24 * Turn them on below: */
26 #define WANT_BOARD_C // capturable groups queue
28 //#define BOARD_SIZE 9 // constant board size, allows better optimization
30 #define BOARD_PAT3 // incremental 3x3 pattern codes
32 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
35 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
36 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
39 /* Some engines might normalize their reading and skip symmetrical
40 * moves. We will tell them how can they do it. */
41 struct board_symmetry {
42 /* Playground is in this rectangle. */
43 int x1, x2, y1, y2;
44 /* d == 0: Full rectangle
45 * d == 1: Top triangle */
46 int d;
47 /* General symmetry type. */
48 /* Note that the above is redundant to this, but just provided
49 * for easier usage. */
50 enum {
51 SYM_FULL,
52 SYM_DIAG_UP,
53 SYM_DIAG_DOWN,
54 SYM_HORIZ,
55 SYM_VERT,
56 SYM_NONE
57 } type;
61 typedef uint64_t hash_t;
62 #define PRIhash PRIx64
64 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
65 * a dependency hell. */
66 typedef uint32_t hash3_t; // 3x3 pattern hash
69 /* Note that "group" is only chain of stones that is solidly
70 * connected for us. */
71 typedef coord_t group_t;
73 struct group {
74 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
75 * don't care. */
76 /* _Combination_ of these two values can make some difference
77 * in performance - fine-tune. */
78 #define GROUP_KEEP_LIBS 10
79 // refill lib[] only when we hit this; this must be at least 2!
80 // Moggy requires at least 3 - see below for semantic impact.
81 #define GROUP_REFILL_LIBS 5
82 coord_t lib[GROUP_KEEP_LIBS];
83 /* libs is only LOWER BOUND for the number of real liberties!!!
84 * It denotes only number of items in lib[], thus you can rely
85 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
86 int libs;
89 struct neighbor_colors {
90 char colors[S_MAX];
94 /* Point traits bitmap; we update this information incrementally,
95 * it can be used e.g. for fast pattern features matching. */
96 struct btraits {
97 /* Number of neighbors we can capture. 0=this move is
98 * not capturing, 1..4=this many neighbors we can capture
99 * (can be multiple neighbors of same group). */
100 unsigned cap:3;
101 /* Number of 1-stone neighbors we can capture. */
102 unsigned cap1:3;
103 /* Whether it is SAFE to play here. This is essentially just
104 * cached result of board_safe_to_play(). (Of course the concept
105 * of "safety" is not perfect here, but it's the cheapest
106 * reasonable thing we can do.) */
107 bool safe:1;
108 /* Whether we need to re-compute this coordinate; used to
109 * weed out duplicates. Maintained only for S_BLACK. */
110 bool dirty:1;
114 /* You should treat this struct as read-only. Always call functions below if
115 * you want to change it. */
117 struct board {
118 int size; /* Including S_OFFBOARD margin - see below. */
119 int size2; /* size^2 */
120 int bits2; /* ceiling(log2(size2)) */
121 int captures[S_MAX];
122 floating_t komi;
123 int handicap;
124 /* The ruleset is currently almost never taken into account;
125 * the board implementation is basically Chinese rules (handicap
126 * stones compensation) w/ suicide (or you can look at it as
127 * New Zealand w/o handi stones compensation), while the engine
128 * enforces no-suicide, making for real Chinese rules. */
129 enum {
130 RULES_CHINESE, /* default value */
131 RULES_AGA,
132 RULES_NEW_ZEALAND,
133 RULES_JAPANESE,
134 } rules;
136 char *fbookfile;
137 struct fbook *fbook;
139 /* Iterator offsets for foreach_neighbor*() */
140 int nei8[8], dnei[4];
142 int moves;
143 struct move last_move;
144 struct move last_move2; /* second-to-last move */
145 /* Whether we tried to add a hash twice; board_play*() can
146 * set this, but it will still carry out the move as well! */
147 bool superko_violation;
149 /* The following two structures are goban maps and are indexed by
150 * coord.pos. The map is surrounded by a one-point margin from
151 * S_OFFBOARD stones in order to speed up some internal loops.
152 * Some of the foreach iterators below might include these points;
153 * you need to handle them yourselves, if you need to. */
155 /* Stones played on the board */
156 enum stone *b; /* enum stone */
157 /* Group id the stones are part of; 0 == no group */
158 group_t *g;
159 /* Positions of next stones in the stone group; 0 == last stone */
160 coord_t *p;
161 /* Neighboring colors; numbers of neighbors of index color */
162 struct neighbor_colors *n;
163 /* Zobrist hash for each position */
164 hash_t *h;
165 #ifdef BOARD_PAT3
166 /* 3x3 pattern code for each position; see pattern3.h for encoding
167 * specification. The information is only valid for empty points. */
168 hash3_t *pat3;
169 #endif
170 #ifdef BOARD_TRAITS
171 /* Incrementally matched point traits information, black-to-play
172 * ([][0]) and white-to-play ([][1]). */
173 /* The information is only valid for empty points. */
174 struct btraits (*t)[2];
175 #endif
176 /* Cached information on x-y coordinates so that we avoid division. */
177 uint8_t (*coord)[2];
179 /* Group information - indexed by gid (which is coord of base group stone) */
180 struct group *gi;
182 /* Positions of free positions - queue (not map) */
183 /* Note that free position here is any valid move; including single-point eyes!
184 * However, pass is not included. */
185 coord_t *f; int flen;
187 #ifdef WANT_BOARD_C
188 /* Queue of capturable groups */
189 group_t *c; int clen;
190 #endif
192 #ifdef BOARD_TRAITS
193 /* Queue of positions that need their traits updated */
194 coord_t *tq; int tqlen;
195 #endif
197 /* Symmetry information */
198 struct board_symmetry symmetry;
200 /* Last ko played on the board. */
201 struct move last_ko;
202 int last_ko_age;
204 /* Basic ko check */
205 struct move ko;
207 /* Engine-specific state; persistent through board development,
208 * is reset only at clear_board. */
209 void *es;
211 /* Playout-specific state; persistent through board development,
212 * but its lifetime is maintained in play_random_game(); it should
213 * not be set outside of it. */
214 void *ps;
217 /* --- PRIVATE DATA --- */
219 /* For superko check: */
221 /* Board "history" - hashes encountered. Size of the hash should be
222 * >> board_size^2. */
223 #define history_hash_bits 12
224 #define history_hash_mask ((1 << history_hash_bits) - 1)
225 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
226 #define history_hash_next(i) ((i + 1) & history_hash_mask)
227 hash_t history_hash[1 << history_hash_bits];
228 /* Hash of current board position. */
229 hash_t hash;
230 /* Hash of current board position quadrants. */
231 hash_t qhash[4];
234 #ifdef BOARD_SIZE
235 /* Avoid unused variable warnings */
236 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
237 #define board_size2(b_) (board_size(b_) * board_size(b_))
238 #else
239 #define board_size(b_) ((b_)->size)
240 #define board_size2(b_) ((b_)->size2)
241 #endif
243 /* This is a shortcut for taking different action on smaller
244 * and large boards (e.g. picking different variable defaults).
245 * This is of course less optimal than fine-tuning dependency
246 * function of values on board size, but that is difficult and
247 * possibly not very rewarding if you are interested just in
248 * 9x9 and 19x19. */
249 #define board_large(b_) (board_size(b_)-2 >= 15)
251 #if BOARD_SIZE == 19
252 # define board_bits2(b_) 9
253 #elif BOARD_SIZE == 13
254 # define board_bits2(b_) 8
255 #elif BOARD_SIZE == 9
256 # define board_bits2(b_) 7
257 #else
258 # define board_bits2(b_) ((b_)->bits2)
259 #endif
261 #define board_at(b_, c) ((b_)->b[c])
262 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
264 #define group_at(b_, c) ((b_)->g[c])
265 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
267 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
268 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
269 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
270 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
271 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
272 #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))
274 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
276 #define groupnext_at(b_, c) ((b_)->p[c])
277 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
279 #define group_base(g_) (g_)
280 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
281 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
282 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
283 /* board_group_other_lib() makes sense only for groups with two liberties. */
284 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
286 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
288 struct board *board_init(char *fbookfile);
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);
327 /* Returns true if given coordinate has all neighbors of given color or the edge. */
328 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
329 /* Returns true if given coordinate could be a false eye; this check makes
330 * sense only if you already know the coordinate is_eyelike(). */
331 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
332 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
333 * at least tries to). */
334 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
335 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
336 enum stone board_get_one_point_eye(struct board *board, coord_t c);
338 /* board_official_score() is the scoring method for yielding score suitable
339 * for external presentation. For fast scoring of entirely filled boards
340 * (e.g. playouts), use board_fast_score(). */
341 /* Positive: W wins */
342 /* Compare number of stones + 1pt eyes. */
343 floating_t board_fast_score(struct board *board);
344 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
345 struct move_queue;
346 floating_t board_official_score(struct board *board, struct move_queue *mq);
348 /** Iterators */
350 #define foreach_point(board_) \
351 do { \
352 coord_t c = 0; \
353 for (; c < board_size(board_) * board_size(board_); c++)
354 #define foreach_point_and_pass(board_) \
355 do { \
356 coord_t c = pass; \
357 for (; c < board_size(board_) * board_size(board_); c++)
358 #define foreach_point_end \
359 } while (0)
361 #define foreach_free_point(board_) \
362 do { \
363 int fmax__ = (board_)->flen; \
364 for (int f__ = 0; f__ < fmax__; f__++) { \
365 coord_t c = (board_)->f[f__];
366 #define foreach_free_point_end \
368 } while (0)
370 #define foreach_in_group(board_, group_) \
371 do { \
372 struct board *board__ = board_; \
373 coord_t c = group_base(group_); \
374 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
375 do {
376 #define foreach_in_group_end \
377 c = c2; c2 = groupnext_at(board__, c2); \
378 } while (c != 0); \
379 } while (0)
381 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
382 * on S_OFFBOARD coordinates. */
383 #define foreach_neighbor(board_, coord_, loop_body) \
384 do { \
385 struct board *board__ = board_; \
386 coord_t coord__ = coord_; \
387 coord_t c; \
388 c = coord__ - board_size(board__); do { loop_body } while (0); \
389 c = coord__ - 1; do { loop_body } while (0); \
390 c = coord__ + 1; do { loop_body } while (0); \
391 c = coord__ + board_size(board__); do { loop_body } while (0); \
392 } while (0)
394 #define foreach_8neighbor(board_, coord_) \
395 do { \
396 int fn__i; \
397 coord_t c = (coord_); \
398 for (fn__i = 0; fn__i < 8; fn__i++) { \
399 c += (board_)->nei8[fn__i];
400 #define foreach_8neighbor_end \
402 } while (0)
404 #define foreach_diag_neighbor(board_, coord_) \
405 do { \
406 int fn__i; \
407 coord_t c = (coord_); \
408 for (fn__i = 0; fn__i < 4; fn__i++) { \
409 c += (board_)->dnei[fn__i];
410 #define foreach_diag_neighbor_end \
412 } while (0)
415 static inline bool
416 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
418 return (neighbor_count_at(board, coord, eye_color)
419 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
422 static inline bool
423 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
425 if (board_at(board, coord) != S_NONE)
426 return false;
427 if (!board_is_eyelike(board, coord, stone_other(color)))
428 return true;
429 /* Play within {true,false} eye-ish formation */
430 if (board->ko.coord == coord && board->ko.color == color)
431 return false;
432 #ifdef BOARD_TRAITS
433 /* XXX: Disallows suicide. */
434 return trait_at(board, coord, color).cap > 0;
435 #else
436 int groups_in_atari = 0;
437 foreach_neighbor(board, coord, {
438 group_t g = group_at(board, c);
439 groups_in_atari += (board_group_info(board, g).libs == 1);
441 return !!groups_in_atari;
442 #endif
445 static inline bool
446 board_is_valid_move(struct board *board, struct move *m)
448 return board_is_valid_play(board, m->color, m->coord);
451 static inline bool
452 board_playing_ko_threat(struct board *b)
454 return !is_pass(b->ko.coord);
457 static inline group_t
458 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
460 #ifdef BOARD_TRAITS
461 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
462 #endif
463 foreach_neighbor(b, coord, {
464 group_t g = group_at(b, c);
465 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
466 return g;
467 /* We return first match. */
469 return 0;
472 static inline bool
473 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
475 /* number of free neighbors */
476 int libs = immediate_liberty_count(b, coord);
477 if (libs > 1)
478 return true;
480 #ifdef BOARD_TRAITS
481 /* number of capturable enemy groups */
482 if (trait_at(b, coord, color).cap > 0)
483 return true; // XXX: We don't account for snapback.
484 /* number of non-capturable friendly groups */
485 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
486 if (noncap_ours < 1)
487 return false;
488 /*#else see below */
489 #endif
491 /* ok, but we need to check if they don't have just two libs. */
492 coord_t onelib = -1;
493 foreach_neighbor(b, coord, {
494 #ifndef BOARD_TRAITS
495 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
496 return true; // can capture; no snapback check
497 #endif
498 if (board_at(b, c) != color) continue;
499 group_t g = group_at(b, c);
500 if (board_group_info(b, g).libs == 1) continue; // in atari
501 if (board_group_info(b, g).libs == 2) { // two liberties
502 if (libs > 0) return true; // we already have one real liberty
503 /* we might be connecting two 2-lib groups, which is ok;
504 * so remember the other liberty and just make sure it's
505 * not the same one */
506 if (onelib >= 0 && c != onelib) return true;
507 onelib = board_group_other_lib(b, g, c);
508 continue;
510 // many liberties
511 return true;
513 // no good support group
514 return false;
517 #endif