Split off BOARD_SPATPROB; board.spatprob is not interesting for us so far
[pachi.git] / board.h
blob5c5822bfca9342560d9a52596e1661b858eb182b
1 /* probdist.h must be included before the include goard since we require
2 * proper including order. */
3 #include "probdist.h"
5 #ifndef PACHI_BOARD_H
6 #define PACHI_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_SPATHASH // incremental patternsp.h hashes
31 #define BOARD_SPATHASH_MAXD 5 // maximal diameter
32 //#define BOARD_SPATPROB // pattern probability cache
34 #define BOARD_PAT3 // incremental 3x3 pattern codes
36 //#define BOARD_TRAITS 1 // incremental point traits (see struct btraits)
37 //#define BOARD_TRAIT_SAFE 1 // include btraits.safe (rather expensive, unused)
38 //#define BOARD_TRAIT_SAFE 2 // include btraits.safe based on full is_bad_selfatari()
41 #define BOARD_MAX_MOVES (BOARD_MAX_SIZE * BOARD_MAX_SIZE)
42 #define BOARD_MAX_GROUPS (BOARD_MAX_SIZE * BOARD_MAX_SIZE / 2)
45 /* Some engines might normalize their reading and skip symmetrical
46 * moves. We will tell them how can they do it. */
47 struct board_symmetry {
48 /* Playground is in this rectangle. */
49 int x1, x2, y1, y2;
50 /* d == 0: Full rectangle
51 * d == 1: Top triangle */
52 int d;
53 /* General symmetry type. */
54 /* Note that the above is redundant to this, but just provided
55 * for easier usage. */
56 enum {
57 SYM_FULL,
58 SYM_DIAG_UP,
59 SYM_DIAG_DOWN,
60 SYM_HORIZ,
61 SYM_VERT,
62 SYM_NONE
63 } type;
67 typedef uint64_t hash_t;
68 #define PRIhash PRIx64
70 /* XXX: This really belongs in pattern3.h, unfortunately that would mean
71 * a dependency hell. */
72 typedef uint32_t hash3_t; // 3x3 pattern hash
75 /* Note that "group" is only chain of stones that is solidly
76 * connected for us. */
77 typedef coord_t group_t;
79 struct group {
80 /* We keep track of only up to GROUP_KEEP_LIBS; over that, we
81 * don't care. */
82 /* _Combination_ of these two values can make some difference
83 * in performance - fine-tune. */
84 #define GROUP_KEEP_LIBS 10
85 // refill lib[] only when we hit this; this must be at least 2!
86 // Moggy requires at least 3 - see below for semantic impact.
87 #define GROUP_REFILL_LIBS 5
88 coord_t lib[GROUP_KEEP_LIBS];
89 /* libs is only LOWER BOUND for the number of real liberties!!!
90 * It denotes only number of items in lib[], thus you can rely
91 * on it to store real liberties only up to <= GROUP_REFILL_LIBS. */
92 int libs;
95 struct neighbor_colors {
96 char colors[S_MAX];
100 /* Point traits bitmap; we update this information incrementally,
101 * it can be used e.g. for fast pattern features matching. */
102 struct btraits {
103 /* Number of neighbors we can capture. 0=this move is
104 * not capturing, 1..4=this many neighbors we can capture
105 * (can be multiple neighbors of same group). */
106 unsigned cap:3;
107 /* Number of 1-stone neighbors we can capture. */
108 unsigned cap1:3;
109 #ifdef BOARD_TRAIT_SAFE
110 /* Whether it is SAFE to play here. This is essentially just
111 * cached result of board_safe_to_play(). (Of course the concept
112 * of "safety" is not perfect here, but it's the cheapest
113 * reasonable thing we can do.) */
114 bool safe:1;
115 #endif
116 /* Whether we need to re-compute this coordinate; used to
117 * weed out duplicates. Maintained only for S_BLACK. */
118 bool dirty:1;
122 /* You should treat this struct as read-only. Always call functions below if
123 * you want to change it. */
125 struct board {
126 int size; /* Including S_OFFBOARD margin - see below. */
127 int size2; /* size^2 */
128 int bits2; /* ceiling(log2(size2)) */
129 int captures[S_MAX];
130 floating_t komi;
131 int handicap;
132 /* The ruleset is currently almost never taken into account;
133 * the board implementation is basically Chinese rules (handicap
134 * stones compensation) w/ suicide (or you can look at it as
135 * New Zealand w/o handi stones compensation), while the engine
136 * enforces no-suicide, making for real Chinese rules.
137 * However, we accept suicide moves by the opponent, so we
138 * should work with rules allowing suicide, just not taking
139 * full advantage of them. */
140 enum go_ruleset {
141 RULES_CHINESE, /* default value */
142 RULES_AGA,
143 RULES_NEW_ZEALAND,
144 RULES_JAPANESE,
145 RULES_STONES_ONLY, /* do not count eyes */
146 /* http://home.snafu.de/jasiek/siming.html */
147 /* Simplified ING rules - RULES_CHINESE with handicaps
148 * counting as points and pass stones. Also should
149 * allow suicide, but Pachi will never suicide
150 * nevertheless. */
151 /* XXX: I couldn't find the point about pass stones
152 * in the rule text, but it is Robert Jasiek's
153 * interpretation of them... These rules were
154 * used e.g. at the EGC2012 13x13 tournament.
155 * They are not supported by KGS. */
156 RULES_SIMING,
157 } rules;
159 char *fbookfile;
160 struct fbook *fbook;
162 /* Iterator offsets for foreach_neighbor*() */
163 int nei8[8], dnei[4];
165 int moves;
166 struct move last_move;
167 struct move last_move2; /* second-to-last move */
168 struct move last_move3; /* just before last_move2, only set if last_move is pass */
169 struct move last_move4; /* just before last_move3, only set if last_move & last_move2 are pass */
170 /* Whether we tried to add a hash twice; board_play*() can
171 * set this, but it will still carry out the move as well! */
172 bool superko_violation;
174 /* The following two structures are goban maps and are indexed by
175 * coord.pos. The map is surrounded by a one-point margin from
176 * S_OFFBOARD stones in order to speed up some internal loops.
177 * Some of the foreach iterators below might include these points;
178 * you need to handle them yourselves, if you need to. */
180 /* Stones played on the board */
181 enum stone *b; /* enum stone */
182 /* Group id the stones are part of; 0 == no group */
183 group_t *g;
184 /* Positions of next stones in the stone group; 0 == last stone */
185 coord_t *p;
186 /* Neighboring colors; numbers of neighbors of index color */
187 struct neighbor_colors *n;
188 /* Zobrist hash for each position */
189 hash_t *h;
190 #ifdef BOARD_SPATHASH
191 /* For spatial hashes, we use only 24 bits. */
192 /* [0] is d==1, we don't keep hash for d==0. */
193 /* We keep hashes for black-to-play ([][0]) and white-to-play
194 * ([][1], reversed stone colors since we match all patterns as
195 * black-to-play). */
196 uint32_t (*spathash)[BOARD_SPATHASH_MAXD][2];
197 #endif
198 #ifdef BOARD_SPATPROB
199 /* Probability of given pattern being played by either player
200 * (non-normalized). This is just a cache, by default filled
201 * with NAN. It is not cleared on liberty-related feature
202 * changes. */
203 /* XXX: This is useless for local followup selection as each
204 * move will clear cache of probabilities in the local area. */
205 floating_t (*spatprob)[2];
206 #endif
207 #ifdef BOARD_PAT3
208 /* 3x3 pattern code for each position; see pattern3.h for encoding
209 * specification. The information is only valid for empty points. */
210 hash3_t *pat3;
211 #endif
212 #ifdef BOARD_TRAITS
213 /* Incrementally matched point traits information, black-to-play
214 * ([][0]) and white-to-play ([][1]). */
215 /* The information is only valid for empty points. */
216 struct btraits (*t)[2];
217 #endif
218 /* Cached information on x-y coordinates so that we avoid division. */
219 uint8_t (*coord)[2];
221 /* Group information - indexed by gid (which is coord of base group stone) */
222 struct group *gi;
224 /* Positions of free positions - queue (not map) */
225 /* Note that free position here is any valid move; including single-point eyes!
226 * However, pass is not included. */
227 coord_t *f; int flen;
229 #ifdef WANT_BOARD_C
230 /* Queue of capturable groups */
231 group_t *c; int clen;
232 #endif
234 #ifdef BOARD_TRAITS
235 /* Queue of positions that need their traits updated */
236 coord_t *tq; int tqlen;
237 #endif
239 /* Symmetry information */
240 struct board_symmetry symmetry;
242 /* Last ko played on the board. */
243 struct move last_ko;
244 int last_ko_age;
246 /* Basic ko check */
247 struct move ko;
249 /* Engine-specific state; persistent through board development,
250 * is reset only at clear_board. */
251 void *es;
253 /* Playout-specific state; persistent through board development,
254 * but its lifetime is maintained in play_random_game(); it should
255 * not be set outside of it. */
256 void *ps;
259 /* --- PRIVATE DATA --- */
261 /* For superko check: */
263 /* Board "history" - hashes encountered. Size of the hash should be
264 * >> board_size^2. */
265 #define history_hash_bits 12
266 #define history_hash_mask ((1 << history_hash_bits) - 1)
267 #define history_hash_prev(i) ((i - 1) & history_hash_mask)
268 #define history_hash_next(i) ((i + 1) & history_hash_mask)
269 hash_t history_hash[1 << history_hash_bits];
270 /* Hash of current board position. */
271 hash_t hash;
272 /* Hash of current board position quadrants. */
273 hash_t qhash[4];
276 #ifdef BOARD_SIZE
277 /* Avoid unused variable warnings */
278 #define board_size(b_) (((b_) == (b_)) ? BOARD_SIZE + 2 : 0)
279 #define board_size2(b_) (board_size(b_) * board_size(b_))
280 #else
281 #define board_size(b_) ((b_)->size)
282 #define board_size2(b_) ((b_)->size2)
283 #endif
285 /* This is a shortcut for taking different action on smaller
286 * and large boards (e.g. picking different variable defaults).
287 * This is of course less optimal than fine-tuning dependency
288 * function of values on board size, but that is difficult and
289 * possibly not very rewarding if you are interested just in
290 * 9x9 and 19x19. */
291 #define board_large(b_) (board_size(b_)-2 >= 15)
292 #define board_small(b_) (board_size(b_)-2 <= 9)
294 #if BOARD_SIZE == 19
295 # define board_bits2(b_) 9
296 #elif BOARD_SIZE == 13
297 # define board_bits2(b_) 8
298 #elif BOARD_SIZE == 9
299 # define board_bits2(b_) 7
300 #else
301 # define board_bits2(b_) ((b_)->bits2)
302 #endif
304 #define board_at(b_, c) ((b_)->b[c])
305 #define board_atxy(b_, x, y) ((b_)->b[(x) + board_size(b_) * (y)])
307 #define group_at(b_, c) ((b_)->g[c])
308 #define group_atxy(b_, x, y) ((b_)->g[(x) + board_size(b_) * (y)])
310 /* Warning! Neighbor count is kept up-to-date for S_NONE! */
311 #define neighbor_count_at(b_, coord, color) ((b_)->n[coord].colors[(enum stone) color])
312 #define set_neighbor_count_at(b_, coord, color, count) (neighbor_count_at(b_, coord, color) = (count))
313 #define inc_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)++)
314 #define dec_neighbor_count_at(b_, coord, color) (neighbor_count_at(b_, coord, color)--)
315 #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))
317 #define trait_at(b_, coord, color) (b_)->t[coord][(color) - 1]
319 #define groupnext_at(b_, c) ((b_)->p[c])
320 #define groupnext_atxy(b_, x, y) ((b_)->p[(x) + board_size(b_) * (y)])
322 #define group_base(g_) (g_)
323 #define group_is_onestone(b_, g_) (groupnext_at(b_, group_base(g_)) == 0)
324 #define board_group_info(b_, g_) ((b_)->gi[(g_)])
325 #define board_group_captured(b_, g_) (board_group_info(b_, g_).libs == 0)
326 /* board_group_other_lib() makes sense only for groups with two liberties. */
327 #define board_group_other_lib(b_, g_, l_) (board_group_info(b_, g_).lib[board_group_info(b_, g_).lib[0] != (l_) ? 0 : 1])
329 #define hash_at(b_, coord, color) ((b_)->h[((color) == S_BLACK ? board_size2(b_) : 0) + coord])
331 struct board *board_init(char *fbookfile);
332 struct board *board_copy(struct board *board2, struct board *board1);
333 void board_done_noalloc(struct board *board);
334 void board_done(struct board *board);
335 /* size here is without the S_OFFBOARD margin. */
336 void board_resize(struct board *board, int size);
337 void board_clear(struct board *board);
339 struct FILE;
340 typedef char *(*board_cprint)(struct board *b, coord_t c, char *s, char *end);
341 void board_print(struct board *board, FILE *f);
342 void board_print_custom(struct board *board, FILE *f, board_cprint cprint);
344 /* Place given handicap on the board; coordinates are printed to f. */
345 void board_handicap(struct board *board, int stones, FILE *f);
347 /* Returns group id, 0 on allowed suicide, pass or resign, -1 on error */
348 int board_play(struct board *board, struct move *m);
349 /* Like above, but plays random move; the move coordinate is recorded
350 * to *coord. This method will never fill your own eye. pass is played
351 * when no move can be played. You can impose extra restrictions if you
352 * supply your own permit function; the permit function can also modify
353 * the move coordinate to redirect the move elsewhere. */
354 typedef bool (*ppr_permit)(void *data, struct board *b, struct move *m);
355 void board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data);
357 /*Undo, supported only for pass moves. Returns -1 on error, 0 otherwise. */
358 int board_undo(struct board *board);
360 /* Returns true if given move can be played. */
361 static bool board_is_valid_play(struct board *b, enum stone color, coord_t coord);
362 static bool board_is_valid_move(struct board *b, struct move *m);
363 /* Returns true if ko was just taken. */
364 static bool board_playing_ko_threat(struct board *b);
365 /* Returns 0 or ID of neighboring group in atari. */
366 static group_t board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color);
367 /* Returns true if the move is not obvious self-atari. */
368 static bool board_safe_to_play(struct board *b, coord_t coord, enum stone color);
370 /* Determine number of stones in a group, up to @max stones. */
371 static int group_stone_count(struct board *b, group_t group, int max);
373 /* Adjust symmetry information as if given coordinate has been played. */
374 void board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c);
375 /* Check if coordinates are within symmetry base. (If false, they can
376 * be derived from the base.) */
377 static bool board_coord_in_symmetry(struct board *b, coord_t c);
379 /* Returns true if given coordinate has all neighbors of given color or the edge. */
380 static bool board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color);
381 /* Returns true if given coordinate could be a false eye; this check makes
382 * sense only if you already know the coordinate is_eyelike(). */
383 bool board_is_false_eyelike(struct board *board, coord_t coord, enum stone eye_color);
384 /* Returns true if given coordinate is a 1-pt eye (checks against false eyes, or
385 * at least tries to). */
386 bool board_is_one_point_eye(struct board *board, coord_t c, enum stone eye_color);
387 /* Returns color of a 1pt eye owner, S_NONE if not an eye. */
388 enum stone board_get_one_point_eye(struct board *board, coord_t c);
390 /* board_official_score() is the scoring method for yielding score suitable
391 * for external presentation. For fast scoring of entirely filled boards
392 * (e.g. playouts), use board_fast_score(). */
393 /* Positive: W wins */
394 /* Compare number of stones + 1pt eyes. */
395 floating_t board_fast_score(struct board *board);
396 /* Tromp-Taylor scoring, assuming given groups are actually dead. */
397 struct move_queue;
398 floating_t board_official_score(struct board *board, struct move_queue *mq);
400 /* Set board rules according to given string. Returns false in case
401 * of unknown ruleset name. */
402 bool board_set_rules(struct board *board, char *name);
404 /** Iterators */
406 #define foreach_point(board_) \
407 do { \
408 coord_t c = 0; \
409 for (; c < board_size(board_) * board_size(board_); c++)
410 #define foreach_point_and_pass(board_) \
411 do { \
412 coord_t c = pass; \
413 for (; c < board_size(board_) * board_size(board_); c++)
414 #define foreach_point_end \
415 } while (0)
417 #define foreach_free_point(board_) \
418 do { \
419 int fmax__ = (board_)->flen; \
420 for (int f__ = 0; f__ < fmax__; f__++) { \
421 coord_t c = (board_)->f[f__];
422 #define foreach_free_point_end \
424 } while (0)
426 #define foreach_in_group(board_, group_) \
427 do { \
428 struct board *board__ = board_; \
429 coord_t c = group_base(group_); \
430 coord_t c2 = c; c2 = groupnext_at(board__, c2); \
431 do {
432 #define foreach_in_group_end \
433 c = c2; c2 = groupnext_at(board__, c2); \
434 } while (c != 0); \
435 } while (0)
437 /* NOT VALID inside of foreach_point() or another foreach_neighbor(), or rather
438 * on S_OFFBOARD coordinates. */
439 #define foreach_neighbor(board_, coord_, loop_body) \
440 do { \
441 struct board *board__ = board_; \
442 coord_t coord__ = coord_; \
443 coord_t c; \
444 c = coord__ - board_size(board__); do { loop_body } while (0); \
445 c = coord__ - 1; do { loop_body } while (0); \
446 c = coord__ + 1; do { loop_body } while (0); \
447 c = coord__ + board_size(board__); do { loop_body } while (0); \
448 } while (0)
450 #define foreach_8neighbor(board_, coord_) \
451 do { \
452 int fn__i; \
453 coord_t c = (coord_); \
454 for (fn__i = 0; fn__i < 8; fn__i++) { \
455 c += (board_)->nei8[fn__i];
456 #define foreach_8neighbor_end \
458 } while (0)
460 #define foreach_diag_neighbor(board_, coord_) \
461 do { \
462 int fn__i; \
463 coord_t c = (coord_); \
464 for (fn__i = 0; fn__i < 4; fn__i++) { \
465 c += (board_)->dnei[fn__i];
466 #define foreach_diag_neighbor_end \
468 } while (0)
471 static inline bool
472 board_is_eyelike(struct board *board, coord_t coord, enum stone eye_color)
474 return (neighbor_count_at(board, coord, eye_color)
475 + neighbor_count_at(board, coord, S_OFFBOARD)) == 4;
478 static inline bool
479 board_is_valid_play(struct board *board, enum stone color, coord_t coord)
481 if (board_at(board, coord) != S_NONE)
482 return false;
483 if (!board_is_eyelike(board, coord, stone_other(color)))
484 return true;
485 /* Play within {true,false} eye-ish formation */
486 if (board->ko.coord == coord && board->ko.color == color)
487 return false;
488 #ifdef BOARD_TRAITS
489 /* XXX: Disallows suicide. */
490 return trait_at(board, coord, color).cap > 0;
491 #else
492 int groups_in_atari = 0;
493 foreach_neighbor(board, coord, {
494 group_t g = group_at(board, c);
495 groups_in_atari += (board_group_info(board, g).libs == 1);
497 return !!groups_in_atari;
498 #endif
501 static inline bool
502 board_is_valid_move(struct board *board, struct move *m)
504 return board_is_valid_play(board, m->color, m->coord);
507 static inline bool
508 board_playing_ko_threat(struct board *b)
510 return !is_pass(b->ko.coord);
513 static inline group_t
514 board_get_atari_neighbor(struct board *b, coord_t coord, enum stone group_color)
516 #ifdef BOARD_TRAITS
517 if (!trait_at(b, coord, stone_other(group_color)).cap) return 0;
518 #endif
519 foreach_neighbor(b, coord, {
520 group_t g = group_at(b, c);
521 if (g && board_at(b, c) == group_color && board_group_info(b, g).libs == 1)
522 return g;
523 /* We return first match. */
525 return 0;
528 static inline bool
529 board_safe_to_play(struct board *b, coord_t coord, enum stone color)
531 /* number of free neighbors */
532 int libs = immediate_liberty_count(b, coord);
533 if (libs > 1)
534 return true;
536 #ifdef BOARD_TRAITS
537 /* number of capturable enemy groups */
538 if (trait_at(b, coord, color).cap > 0)
539 return true; // XXX: We don't account for snapback.
540 /* number of non-capturable friendly groups */
541 int noncap_ours = neighbor_count_at(b, coord, color) - trait_at(b, coord, stone_other(color)).cap;
542 if (noncap_ours < 1)
543 return false;
544 /*#else see below */
545 #endif
547 /* ok, but we need to check if they don't have just two libs. */
548 coord_t onelib = -1;
549 foreach_neighbor(b, coord, {
550 #ifndef BOARD_TRAITS
551 if (board_at(b, c) == stone_other(color) && board_group_info(b, group_at(b, c)).libs == 1)
552 return true; // can capture; no snapback check
553 #endif
554 if (board_at(b, c) != color) continue;
555 group_t g = group_at(b, c);
556 if (board_group_info(b, g).libs == 1) continue; // in atari
557 if (board_group_info(b, g).libs == 2) { // two liberties
558 if (libs > 0) return true; // we already have one real liberty
559 /* we might be connecting two 2-lib groups, which is ok;
560 * so remember the other liberty and just make sure it's
561 * not the same one */
562 if (onelib >= 0 && c != onelib) return true;
563 onelib = board_group_other_lib(b, g, c);
564 continue;
566 // many liberties
567 return true;
569 // no good support group
570 return false;
573 static inline int
574 group_stone_count(struct board *b, group_t group, int max)
576 int n = 0;
577 foreach_in_group(b, group) {
578 n++;
579 if (n >= max) return max;
580 } foreach_in_group_end;
581 return n;
584 static inline bool
585 board_coord_in_symmetry(struct board *b, coord_t c)
587 if (coord_y(c, b) < b->symmetry.y1 || coord_y(c, b) > b->symmetry.y2)
588 return false;
589 if (coord_x(c, b) < b->symmetry.x1 || coord_x(c, b) > b->symmetry.x2)
590 return false;
591 if (b->symmetry.d) {
592 int x = coord_x(c, b);
593 if (b->symmetry.type == SYM_DIAG_DOWN)
594 x = board_size(b) - 1 - x;
595 if (x > coord_y(c, b))
596 return false;
598 return true;
602 #endif