time_in_byoyomi(): Rewrite, smoother to read and more flexible now
[pachi.git] / board.c
blob5e8aec4010e778dfd1a4590b68da0e56a5d7c451
1 #include <alloca.h>
2 #include <assert.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "mq.h"
10 #include "random.h"
12 #ifdef BOARD_SPATHASH
13 #include "patternsp.h"
14 #endif
15 #ifdef BOARD_PAT3
16 #include "pattern3.h"
17 #endif
19 bool random_pass = false;
22 #if 0
23 #define profiling_noinline __attribute__((noinline))
24 #else
25 #define profiling_noinline
26 #endif
28 #define gi_granularity 4
29 #define gi_allocsize(gids) ((1 << gi_granularity) + ((gids) >> gi_granularity) * (1 << gi_granularity))
32 static void
33 board_setup(struct board *b)
35 memset(b, 0, sizeof(*b));
37 struct move m = { pass, S_NONE };
38 b->last_move = b->last_move2 = b->last_ko = b->ko = m;
41 struct board *
42 board_init(void)
44 struct board *b = malloc(sizeof(struct board));
45 board_setup(b);
47 // Default setup
48 b->size = 9 + 2;
49 board_clear(b);
51 return b;
54 struct board *
55 board_copy(struct board *b2, struct board *b1)
57 memcpy(b2, b1, sizeof(struct board));
59 int bsize = board_size2(b2) * sizeof(*b2->b);
60 int gsize = board_size2(b2) * sizeof(*b2->g);
61 int fsize = board_size2(b2) * sizeof(*b2->f);
62 int nsize = board_size2(b2) * sizeof(*b2->n);
63 int psize = board_size2(b2) * sizeof(*b2->p);
64 int hsize = board_size2(b2) * 2 * sizeof(*b2->h);
65 int gisize = board_size2(b2) * sizeof(*b2->gi);
66 #ifdef WANT_BOARD_C
67 int csize = board_size2(b2) * sizeof(*b2->c);
68 #else
69 int csize = 0;
70 #endif
71 #ifdef BOARD_SPATHASH
72 int ssize = board_size2(b2) * sizeof(*b2->spathash);
73 #else
74 int ssize = 0;
75 #endif
76 #ifdef BOARD_PAT3
77 int p3size = board_size2(b2) * sizeof(*b2->pat3);
78 #else
79 int p3size = 0;
80 #endif
81 #ifdef BOARD_TRAITS
82 int tsize = board_size2(b2) * sizeof(*b2->t);
83 #else
84 int tsize = 0;
85 #endif
86 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
87 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
88 b2->b = x; x += bsize;
89 b2->g = x; x += gsize;
90 b2->f = x; x += fsize;
91 b2->p = x; x += psize;
92 b2->n = x; x += nsize;
93 b2->h = x; x += hsize;
94 b2->gi = x; x += gisize;
95 #ifdef WANT_BOARD_C
96 b2->c = x; x += csize;
97 #endif
98 #ifdef BOARD_SPATHASH
99 b2->spathash = x; x += ssize;
100 #endif
101 #ifdef BOARD_PAT3
102 b2->pat3 = x; x += p3size;
103 #endif
104 #ifdef BOARD_TRAITS
105 b2->t = x; x += tsize;
106 #endif
108 return b2;
111 void
112 board_done_noalloc(struct board *board)
114 if (board->b) free(board->b);
117 void
118 board_done(struct board *board)
120 board_done_noalloc(board);
121 free(board);
124 void
125 board_resize(struct board *board, int size)
127 #ifdef BOARD_SIZE
128 assert(board_size(board) == size + 2);
129 #else
130 board_size(board) = size + 2 /* S_OFFBOARD margin */;
131 board_size2(board) = board_size(board) * board_size(board);
132 #endif
133 if (board->b)
134 free(board->b);
136 int bsize = board_size2(board) * sizeof(*board->b);
137 int gsize = board_size2(board) * sizeof(*board->g);
138 int fsize = board_size2(board) * sizeof(*board->f);
139 int nsize = board_size2(board) * sizeof(*board->n);
140 int psize = board_size2(board) * sizeof(*board->p);
141 int hsize = board_size2(board) * 2 * sizeof(*board->h);
142 int gisize = board_size2(board) * sizeof(*board->gi);
143 #ifdef WANT_BOARD_C
144 int csize = board_size2(board) * sizeof(*board->c);
145 #else
146 int csize = 0;
147 #endif
148 #ifdef BOARD_SPATHASH
149 int ssize = board_size2(board) * sizeof(*board->spathash);
150 #else
151 int ssize = 0;
152 #endif
153 #ifdef BOARD_PAT3
154 int p3size = board_size2(board) * sizeof(*board->pat3);
155 #else
156 int p3size = 0;
157 #endif
158 #ifdef BOARD_TRAITS
159 int tsize = board_size2(board) * sizeof(*board->t);
160 #else
161 int tsize = 0;
162 #endif
163 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
164 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size + tsize);
165 board->b = x; x += bsize;
166 board->g = x; x += gsize;
167 board->f = x; x += fsize;
168 board->p = x; x += psize;
169 board->n = x; x += nsize;
170 board->h = x; x += hsize;
171 board->gi = x; x += gisize;
172 #ifdef WANT_BOARD_C
173 board->c = x; x += csize;
174 #endif
175 #ifdef BOARD_SPATHASH
176 board->spathash = x; x += ssize;
177 #endif
178 #ifdef BOARD_PAT3
179 board->pat3 = x; x += p3size;
180 #endif
181 #ifdef BOARD_TRAITS
182 board->t = x; x += tsize;
183 #endif
186 void
187 board_clear(struct board *board)
189 int size = board_size(board);
190 float komi = board->komi;
192 board_done_noalloc(board);
193 board_setup(board);
194 board_resize(board, size - 2 /* S_OFFBOARD margin */);
196 board->komi = komi;
198 /* Setup neighborhood iterators */
199 board->nei8[0] = -size - 1; // (-1,-1)
200 board->nei8[1] = 1;
201 board->nei8[2] = 1;
202 board->nei8[3] = size - 2; // (-1,0)
203 board->nei8[4] = 2;
204 board->nei8[5] = size - 2; // (-1,1)
205 board->nei8[6] = 1;
206 board->nei8[7] = 1;
207 board->dnei[0] = -size - 1;
208 board->dnei[1] = 2;
209 board->dnei[2] = size*2 - 2;
210 board->dnei[3] = 2;
212 /* Setup initial symmetry */
213 board->symmetry.d = 1;
214 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
215 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
216 board->symmetry.type = SYM_FULL;
218 /* Draw the offboard margin */
219 int top_row = board_size2(board) - board_size(board);
220 int i;
221 for (i = 0; i < board_size(board); i++)
222 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
223 for (i = 0; i <= top_row; i += board_size(board))
224 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
226 foreach_point(board) {
227 coord_t coord = c;
228 if (board_at(board, coord) == S_OFFBOARD)
229 continue;
230 foreach_neighbor(board, c, {
231 inc_neighbor_count_at(board, coord, board_at(board, c));
232 } );
233 } foreach_point_end;
235 /* First, pass is always a free position. */
236 board->f[board->flen++] = coord_raw(pass);
237 /* All positions are free! Except the margin. */
238 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
239 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
240 board->f[board->flen++] = i;
242 /* Initialize zobrist hashtable. */
243 foreach_point(board) {
244 int max = (sizeof(hash_t) << history_hash_bits);
245 /* fast_random() is 16-bit only */
246 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
247 | ((hash_t) fast_random(max) << 16)
248 | ((hash_t) fast_random(max) << 32)
249 | ((hash_t) fast_random(max) << 48);
250 if (!board->h[coord_raw(c) * 2])
251 /* Would be kinda "oops". */
252 board->h[coord_raw(c) * 2] = 1;
253 /* And once again for white */
254 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
255 | ((hash_t) fast_random(max) << 16)
256 | ((hash_t) fast_random(max) << 32)
257 | ((hash_t) fast_random(max) << 48);
258 if (!board->h[coord_raw(c) * 2 + 1])
259 board->h[coord_raw(c) * 2 + 1] = 1;
260 } foreach_point_end;
262 #ifdef BOARD_SPATHASH
263 /* Initialize spatial hashes. */
264 foreach_point(board) {
265 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
266 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
267 ptcoords_at(x, y, c, board, j);
268 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
269 pthashes[0][j][board_at(board, c)];
270 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
271 pthashes[0][j][stone_other(board_at(board, c))];
274 } foreach_point_end;
275 #endif
276 #ifdef BOARD_PAT3
277 /* Initialize 3x3 pattern codes. */
278 foreach_point(board) {
279 if (board_at(board, c) == S_NONE)
280 board->pat3[c] = pattern3_hash(board, c);
281 } foreach_point_end;
282 #endif
283 /* We don't need to initialize traits, they are all zero
284 * by default. */
288 static void
289 board_print_top(struct board *board, FILE *f, int c)
291 for (int i = 0; i < c; i++) {
292 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
293 fprintf(f, " ");
294 for (int x = 1; x < board_size(board) - 1; x++)
295 fprintf(f, "%c ", asdf[x - 1]);
296 fprintf(f, " ");
298 fprintf(f, "\n");
299 for (int i = 0; i < c; i++) {
300 fprintf(f, " +-");
301 for (int x = 1; x < board_size(board) - 1; x++)
302 fprintf(f, "--");
303 fprintf(f, "+");
305 fprintf(f, "\n");
308 static void
309 board_print_bottom(struct board *board, FILE *f, int c)
311 for (int i = 0; i < c; i++) {
312 fprintf(f, " +-");
313 for (int x = 1; x < board_size(board) - 1; x++)
314 fprintf(f, "--");
315 fprintf(f, "+");
317 fprintf(f, "\n");
320 static void
321 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
323 fprintf(f, " %2d | ", y);
324 for (int x = 1; x < board_size(board) - 1; x++) {
325 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
326 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
327 else
328 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
330 fprintf(f, "|");
331 if (cprint) {
332 fprintf(f, " %2d | ", y);
333 for (int x = 1; x < board_size(board) - 1; x++) {
334 cprint(board, coord_xy(board, x, y), f);
336 fprintf(f, "|");
338 fprintf(f, "\n");
341 void
342 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
344 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
345 board->moves, board->komi, board->handicap,
346 board->captures[S_BLACK], board->captures[S_WHITE]);
347 board_print_top(board, f, 1 + !!cprint);
348 for (int y = board_size(board) - 2; y >= 1; y--)
349 board_print_row(board, y, f, cprint);
350 board_print_bottom(board, f, 1 + !!cprint);
351 fprintf(f, "\n");
354 static void
355 cprint_group(struct board *board, coord_t c, FILE *f)
357 fprintf(f, "%d ", group_base(group_at(board, c)));
360 void
361 board_print(struct board *board, FILE *f)
363 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
367 /* Update board hash with given coordinate. */
368 static void profiling_noinline
369 board_hash_update(struct board *board, coord_t coord, enum stone color)
371 board->hash ^= hash_at(board, coord, color);
372 if (DEBUGL(8))
373 fprintf(stderr, "board_hash_update(%d,%d,%d) ^ %"PRIhash" -> %"PRIhash"\n", color, coord_x(coord, board), coord_y(coord, board), hash_at(board, coord, color), board->hash);
375 #ifdef BOARD_SPATHASH
376 /* Gridcular metric is reflective, so we update all hashes
377 * of appropriate ditance in OUR circle. */
378 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
379 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
380 ptcoords_at(x, y, coord, board, j);
381 /* We either changed from S_NONE to color
382 * or vice versa; doesn't matter. */
383 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
384 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
385 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
386 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
389 #endif
391 #if defined(BOARD_PAT3)
392 /* @color is not what we need in case of capture. */
393 enum stone new_color = board_at(board, coord);
394 if (new_color == S_NONE)
395 board->pat3[coord] = pattern3_hash(board, coord);
396 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
397 if (board_at(board, c) != S_NONE)
398 continue;
399 board->pat3[c] &= ~(3 << (fn__i*2));
400 board->pat3[c] |= new_color << (fn__i*2);
401 #if 0
402 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
403 board_print(board, stderr);
404 fprintf(stderr, "%s->%s %x != %x (%d-%d:%d)\n", coord2sstr(coord, board), coord2sstr(c, board), pattern3_hash(board, c), board->pat3[c], coord, c, fn__i);
405 assert(0);
407 #endif
408 } foreach_8neighbor_end;
409 #endif
412 /* Commit current board hash to history. */
413 static void profiling_noinline
414 board_hash_commit(struct board *board)
416 if (DEBUGL(8))
417 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
418 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
419 board->history_hash[board->hash & history_hash_mask] = board->hash;
420 } else {
421 hash_t i = board->hash;
422 while (board->history_hash[i & history_hash_mask]) {
423 if (board->history_hash[i & history_hash_mask] == board->hash) {
424 if (DEBUGL(5))
425 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
426 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
427 board->superko_violation = true;
428 return;
430 i = history_hash_next(i);
432 board->history_hash[i & history_hash_mask] = board->hash;
437 void
438 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
440 if (likely(symmetry->type == SYM_NONE)) {
441 /* Fully degenerated already. We do not support detection
442 * of restoring of symmetry, assuming that this is too rare
443 * a case to handle. */
444 return;
447 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
448 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
449 if (DEBUGL(6)) {
450 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
451 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
452 symmetry->d, symmetry->type, x, y);
455 switch (symmetry->type) {
456 case SYM_FULL:
457 if (x == t && y == t) {
458 /* Tengen keeps full symmetry. */
459 return;
461 /* New symmetry now? */
462 if (x == y) {
463 symmetry->type = SYM_DIAG_UP;
464 symmetry->x1 = symmetry->y1 = 1;
465 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
466 symmetry->d = 1;
467 } else if (dx == y) {
468 symmetry->type = SYM_DIAG_DOWN;
469 symmetry->x1 = symmetry->y1 = 1;
470 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
471 symmetry->d = 1;
472 } else if (x == t) {
473 symmetry->type = SYM_HORIZ;
474 symmetry->y1 = 1;
475 symmetry->y2 = board_size(b) - 1;
476 symmetry->d = 0;
477 } else if (y == t) {
478 symmetry->type = SYM_VERT;
479 symmetry->x1 = 1;
480 symmetry->x2 = board_size(b) - 1;
481 symmetry->d = 0;
482 } else {
483 break_symmetry:
484 symmetry->type = SYM_NONE;
485 symmetry->x1 = symmetry->y1 = 1;
486 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
487 symmetry->d = 0;
489 break;
490 case SYM_DIAG_UP:
491 if (x == y)
492 return;
493 goto break_symmetry;
494 case SYM_DIAG_DOWN:
495 if (dx == y)
496 return;
497 goto break_symmetry;
498 case SYM_HORIZ:
499 if (x == t)
500 return;
501 goto break_symmetry;
502 case SYM_VERT:
503 if (y == t)
504 return;
505 goto break_symmetry;
506 case SYM_NONE:
507 assert(0);
508 break;
511 if (DEBUGL(6)) {
512 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
513 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
514 symmetry->d, symmetry->type);
516 /* Whew. */
520 void
521 board_handicap_stone(struct board *board, int x, int y, FILE *f)
523 struct move m;
524 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
526 board_play(board, &m);
527 /* Simulate white passing; otherwise, UCT search can get confused since
528 * tree depth parity won't match the color to move. */
529 board->moves++;
531 char *str = coord2str(m.coord, board);
532 if (DEBUGL(1))
533 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
534 fprintf(f, "%s ", str);
535 free(str);
538 void
539 board_handicap(struct board *board, int stones, FILE *f)
541 int margin = 3 + (board_size(board) >= 13);
542 int min = margin;
543 int mid = board_size(board) / 2;
544 int max = board_size(board) - 1 - margin;
545 const int places[][2] = {
546 { min, min }, { max, max }, { max, min }, { min, max },
547 { min, mid }, { max, mid },
548 { mid, min }, { mid, max },
549 { mid, mid },
552 board->handicap = stones;
554 if (stones == 5 || stones == 7) {
555 board_handicap_stone(board, mid, mid, f);
556 stones--;
559 int i;
560 for (i = 0; i < stones; i++)
561 board_handicap_stone(board, places[i][0], places[i][1], f);
565 static void __attribute__((noinline))
566 check_libs_consistency(struct board *board, group_t g)
568 #ifdef DEBUG
569 if (!g) return;
570 struct group *gi = &board_group_info(board, g);
571 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
572 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
573 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
574 assert(0);
576 #endif
579 static void
580 board_capturable_add(struct board *board, group_t group, coord_t lib)
582 //fprintf(stderr, "group %s cap %s\n", coord2sstr(group, board), coord2sstr(lib, boarD));
583 #ifdef BOARD_TRAITS
584 /* Increase capturable count trait of my last lib. */
585 foreach_neighbor(board, lib, {
586 if (DEBUGL(8) && group_at(board, c) == group)
587 fprintf(stderr, "%s[%d] cap bump bc of %s(%d) member %s\n", coord2sstr(lib, board), board->t[lib].cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board));
588 board->t[lib].cap += (group_at(board, c) == group);
590 #endif
592 #ifdef WANT_BOARD_C
593 /* Update the list of capturable groups. */
594 assert(group);
595 assert(board->clen < board_size2(board));
596 board->c[board->clen++] = group;
597 #endif
599 static void
600 board_capturable_rm(struct board *board, group_t group, coord_t lib)
602 //fprintf(stderr, "group %s nocap %s\n", coord2sstr(group, board), coord2sstr(lib, board));
603 #ifdef BOARD_TRAITS
604 /* Decrease capturable count trait of my previously-last lib. */
605 foreach_neighbor(board, lib, {
606 if (DEBUGL(8) && group_at(board, c) == group)
607 fprintf(stderr, "%s[%d] cap dump bc of %s(%d) member %s\n", coord2sstr(lib, board), board->t[lib].cap, coord2sstr(group, board), board_group_info(board, group).libs, coord2sstr(c, board));
608 board->t[lib].cap -= (group_at(board, c) == group);
610 #endif
612 #ifdef WANT_BOARD_C
613 /* Update the list of capturable groups. */
614 for (int i = 0; i < board->clen; i++) {
615 if (unlikely(board->c[i] == group)) {
616 board->c[i] = board->c[--board->clen];
617 return;
620 fprintf(stderr, "rm of bad group %d\n", group_base(group));
621 assert(0);
622 #endif
625 static void
626 board_group_addlib(struct board *board, group_t group, coord_t coord)
628 if (DEBUGL(7)) {
629 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
630 group_base(group), coord2sstr(group_base(group), board),
631 board_group_info(board, group).libs, coord2sstr(coord, board));
634 check_libs_consistency(board, group);
636 struct group *gi = &board_group_info(board, group);
637 if (gi->libs < GROUP_KEEP_LIBS) {
638 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
639 #if 0
640 /* Seems extra branch just slows it down */
641 if (!gi->lib[i])
642 break;
643 #endif
644 if (unlikely(gi->lib[i] == coord))
645 return;
647 if (gi->libs == 0)
648 board_capturable_add(board, group, coord);
649 else if (gi->libs == 1)
650 board_capturable_rm(board, group, gi->lib[0]);
651 gi->lib[gi->libs++] = coord;
654 check_libs_consistency(board, group);
657 static void
658 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
660 /* Add extra liberty from the board to our liberty list. */
661 unsigned char watermark[board_size2(board) / 8];
662 memset(watermark, 0, sizeof(watermark));
663 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
664 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
666 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
667 watermark_set(gi->lib[i]);
668 watermark_set(avoid);
670 foreach_in_group(board, group) {
671 coord_t coord2 = c;
672 foreach_neighbor(board, coord2, {
673 if (board_at(board, c) + watermark_get(c) != S_NONE)
674 continue;
675 watermark_set(c);
676 gi->lib[gi->libs++] = c;
677 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
678 return;
679 } );
680 } foreach_in_group_end;
681 #undef watermark_get
682 #undef watermark_set
685 static void
686 board_group_rmlib(struct board *board, group_t group, coord_t coord)
688 if (DEBUGL(7)) {
689 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
690 group_base(group), coord2sstr(group_base(group), board),
691 board_group_info(board, group).libs, coord2sstr(coord, board));
694 struct group *gi = &board_group_info(board, group);
695 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
696 #if 0
697 /* Seems extra branch just slows it down */
698 if (!gi->lib[i])
699 break;
700 #endif
701 if (likely(gi->lib[i] != coord))
702 continue;
704 coord_t lib = gi->lib[i] = gi->lib[--gi->libs];
705 gi->lib[gi->libs] = 0;
707 check_libs_consistency(board, group);
709 /* Postpone refilling lib[] until we need to. */
710 assert(GROUP_REFILL_LIBS > 1);
711 if (gi->libs > GROUP_REFILL_LIBS)
712 return;
713 if (gi->libs == GROUP_REFILL_LIBS)
714 board_group_find_extra_libs(board, group, gi, coord);
716 if (gi->libs == 1)
717 board_capturable_add(board, group, gi->lib[0]);
718 else if (gi->libs == 0)
719 board_capturable_rm(board, group, lib);
720 return;
723 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
724 * can call this multiple times per coord. */
725 check_libs_consistency(board, group);
726 return;
730 /* This is a low-level routine that doesn't maintain consistency
731 * of all the board data structures. */
732 static void
733 board_remove_stone(struct board *board, group_t group, coord_t c)
735 enum stone color = board_at(board, c);
736 board_at(board, c) = S_NONE;
737 group_at(board, c) = 0;
738 board_hash_update(board, c, color);
739 #ifdef BOARD_TRAITS
740 /* We mark as cannot-capture now. If this is a ko/snapback,
741 * we will get incremented later in board_group_addlib(). */
742 board->t[c].cap = 0;
743 #endif
745 /* Increase liberties of surrounding groups */
746 coord_t coord = c;
747 foreach_neighbor(board, coord, {
748 dec_neighbor_count_at(board, c, color);
749 group_t g = group_at(board, c);
750 if (g && g != group)
751 board_group_addlib(board, g, coord);
754 if (DEBUGL(6))
755 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
756 board->f[board->flen++] = coord_raw(c);
759 static int profiling_noinline
760 board_group_capture(struct board *board, group_t group)
762 int stones = 0;
764 foreach_in_group(board, group) {
765 board->captures[stone_other(board_at(board, c))]++;
766 board_remove_stone(board, group, c);
767 stones++;
768 } foreach_in_group_end;
770 if (board_group_info(board, group).libs == 1)
771 board_capturable_rm(board, group, board_group_info(board, group).lib[0]);
772 memset(&board_group_info(board, group), 0, sizeof(struct group));
774 return stones;
778 static void profiling_noinline
779 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
781 group_at(board, coord) = group;
782 groupnext_at(board, coord) = groupnext_at(board, prevstone);
783 groupnext_at(board, prevstone) = coord_raw(coord);
785 #if defined(BOARD_TRAITS)
786 if (board_group_info(board, group).libs == 1) {
787 /* Our group is temporarily in atari; make sure the capturable
788 * counts also correspond to the newly added stone before we
789 * start adding liberties again so bump-dump ops match. */
790 coord_t lib = board_group_info(board, group).lib[0];
791 if (coord_is_adjecent(lib, coord, board)) {
792 if (DEBUGL(8)) fprintf(stderr, "add_to_group %s: %s[%d] bump\n", coord2sstr(group, board), coord2sstr(lib, board), board->t[lib].cap);
793 board->t[lib].cap++;
796 #endif
798 foreach_neighbor(board, coord, {
799 if (board_at(board, c) == S_NONE)
800 board_group_addlib(board, group, c);
803 if (DEBUGL(8))
804 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
805 coord_x(prevstone, board), coord_y(prevstone, board),
806 coord_x(coord, board), coord_y(coord, board),
807 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
808 group_base(group));
811 static void profiling_noinline
812 merge_groups(struct board *board, group_t group_to, group_t group_from)
814 if (DEBUGL(7))
815 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
816 group_base(group_from), group_base(group_to));
817 struct group *gi_from = &board_group_info(board, group_from);
818 struct group *gi_to = &board_group_info(board, group_to);
820 /* We do this early before the group info is rewritten. */
821 if (gi_from->libs == 1)
822 board_capturable_rm(board, group_from, gi_from->lib[0]);
824 if (DEBUGL(7))
825 fprintf(stderr,"---- (froml %d, tol %d)\n", gi_from->libs, gi_to->libs);
827 if (gi_to->libs < GROUP_KEEP_LIBS) {
828 for (int i = 0; i < gi_from->libs; i++) {
829 for (int j = 0; j < gi_to->libs; j++)
830 if (gi_to->lib[j] == gi_from->lib[i])
831 goto next_from_lib;
832 if (gi_to->libs == 0)
833 board_capturable_add(board, group_to, gi_from->lib[i]);
834 else if (gi_to->libs == 1)
835 board_capturable_rm(board, group_to, gi_to->lib[0]);
836 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
837 if (gi_to->libs >= GROUP_KEEP_LIBS)
838 break;
839 next_from_lib:;
843 #if defined(BOARD_TRAITS)
844 if (board_group_info(board, group_to).libs == 1) {
845 /* Our group is currently in atari; make sure we properly
846 * count in even the neighbors from the other group in the
847 * capturable counter. */
848 coord_t lib = board_group_info(board, group_to).lib[0];
849 foreach_neighbor(board, lib, {
850 if (DEBUGL(8) && group_at(board, c) == group_from) fprintf(stderr, "%s[%d] cap bump\n", coord2sstr(lib, board), board->t[lib].cap);
851 board->t[lib].cap += (group_at(board, c) == group_from);
854 #endif
856 coord_t last_in_group;
857 foreach_in_group(board, group_from) {
858 last_in_group = c;
859 group_at(board, c) = group_to;
860 } foreach_in_group_end;
861 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
862 groupnext_at(board, group_base(group_to)) = group_base(group_from);
863 memset(gi_from, 0, sizeof(struct group));
865 if (DEBUGL(7))
866 fprintf(stderr, "board_play_raw: merged group: %d\n",
867 group_base(group_to));
870 static group_t profiling_noinline
871 new_group(struct board *board, coord_t coord)
873 group_t group = coord_raw(coord);
874 struct group *gi = &board_group_info(board, group);
875 foreach_neighbor(board, coord, {
876 if (board_at(board, c) == S_NONE)
877 /* board_group_addlib is ridiculously expensive for us */
878 #if GROUP_KEEP_LIBS < 4
879 if (gi->libs < GROUP_KEEP_LIBS)
880 #endif
881 gi->lib[gi->libs++] = c;
884 group_at(board, coord) = group;
885 groupnext_at(board, coord) = 0;
887 if (gi->libs == 1)
888 board_capturable_add(board, group, gi->lib[0]);
889 check_libs_consistency(board, group);
891 if (DEBUGL(8))
892 fprintf(stderr, "new_group: added %d,%d to group %d\n",
893 coord_x(coord, board), coord_y(coord, board),
894 group_base(group));
896 return group;
899 static inline group_t
900 play_one_neighbor(struct board *board,
901 coord_t coord, enum stone color, enum stone other_color,
902 coord_t c, group_t group)
904 enum stone ncolor = board_at(board, c);
905 group_t ngroup = group_at(board, c);
907 inc_neighbor_count_at(board, c, color);
909 if (!ngroup)
910 return group;
912 board_group_rmlib(board, ngroup, coord);
913 if (DEBUGL(7))
914 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
915 group_base(ngroup), ncolor, color, other_color);
917 if (ncolor == color && ngroup != group) {
918 if (!group) {
919 group = ngroup;
920 add_to_group(board, group, c, coord);
921 } else {
922 merge_groups(board, group, ngroup);
924 } else if (ncolor == other_color) {
925 if (DEBUGL(8)) {
926 struct group *gi = &board_group_info(board, ngroup);
927 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
928 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
929 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
930 fprintf(stderr, "\n");
932 if (unlikely(board_group_captured(board, ngroup)))
933 board_group_capture(board, ngroup);
935 return group;
938 /* We played on a place with at least one liberty. We will become a member of
939 * some group for sure. */
940 static group_t profiling_noinline
941 board_play_outside(struct board *board, struct move *m, int f)
943 coord_t coord = m->coord;
944 enum stone color = m->color;
945 enum stone other_color = stone_other(color);
946 group_t group = 0;
948 board->f[f] = board->f[--board->flen];
949 if (DEBUGL(6))
950 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
952 #if defined(BOARD_TRAITS) && !defined(NDEBUG)
953 /* Sanity check that cap matches reality. */
955 int a = 0;
956 foreach_neighbor(board, coord, {
957 group_t g = group_at(board, c);
958 a += g && (board_group_info(board, g).libs == 1);
960 assert(a == board->t[coord].cap);
962 #endif
963 foreach_neighbor(board, coord, {
964 group = play_one_neighbor(board, coord, color, other_color, c, group);
967 if (unlikely(!group))
968 group = new_group(board, coord);
970 board_at(board, coord) = color;
971 board->last_move2 = board->last_move;
972 board->last_move = *m;
973 board->moves++;
974 board_hash_update(board, coord, color);
975 board_symmetry_update(board, &board->symmetry, coord);
976 struct move ko = { pass, S_NONE };
977 board->ko = ko;
979 return group;
982 /* We played in an eye-like shape. Either we capture at least one of the eye
983 * sides in the process of playing, or return -1. */
984 static int profiling_noinline
985 board_play_in_eye(struct board *board, struct move *m, int f)
987 coord_t coord = m->coord;
988 enum stone color = m->color;
989 /* Check ko: Capture at a position of ko capture one move ago */
990 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
991 if (DEBUGL(5))
992 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
993 return -1;
994 } else if (DEBUGL(6)) {
995 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
996 color, coord_x(coord, board), coord_y(coord, board),
997 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
1000 struct move ko = { pass, S_NONE };
1002 int captured_groups = 0;
1004 foreach_neighbor(board, coord, {
1005 group_t g = group_at(board, c);
1006 if (DEBUGL(7))
1007 fprintf(stderr, "board_check: group %d has %d libs\n",
1008 g, board_group_info(board, g).libs);
1009 captured_groups += (board_group_info(board, g).libs == 1);
1012 if (likely(captured_groups == 0)) {
1013 if (DEBUGL(5)) {
1014 if (DEBUGL(6))
1015 board_print(board, stderr);
1016 fprintf(stderr, "board_check: one-stone suicide\n");
1019 return -1;
1021 #ifdef BOARD_TRAITS
1022 /* We _will_ for sure capture something. */
1023 assert(board->t[coord].cap > 0);
1024 #endif
1026 board->f[f] = board->f[--board->flen];
1027 if (DEBUGL(6))
1028 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
1030 foreach_neighbor(board, coord, {
1031 inc_neighbor_count_at(board, c, color);
1033 group_t group = group_at(board, c);
1034 if (!group)
1035 continue;
1037 board_group_rmlib(board, group, coord);
1038 if (DEBUGL(7))
1039 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
1040 group_base(group));
1042 if (board_group_captured(board, group)) {
1043 if (board_group_capture(board, group) == 1) {
1044 /* If we captured multiple groups at once,
1045 * we can't be fighting ko so we don't need
1046 * to check for that. */
1047 ko.color = stone_other(color);
1048 ko.coord = c;
1049 board->last_ko = ko;
1050 board->last_ko_age = board->moves;
1051 if (DEBUGL(5))
1052 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
1057 board_at(board, coord) = color;
1058 group_t group = new_group(board, coord);
1060 board->last_move2 = board->last_move;
1061 board->last_move = *m;
1062 board->moves++;
1063 board_hash_update(board, coord, color);
1064 board_hash_commit(board);
1065 board_symmetry_update(board, &board->symmetry, coord);
1066 board->ko = ko;
1068 return !!group;
1071 static int __attribute__((flatten))
1072 board_play_f(struct board *board, struct move *m, int f)
1074 if (DEBUGL(7)) {
1075 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
1077 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
1078 /* NOT playing in an eye. Thus this move has to succeed. (This
1079 * is thanks to New Zealand rules. Otherwise, multi-stone
1080 * suicide might fail.) */
1081 group_t group = board_play_outside(board, m, f);
1082 if (unlikely(board_group_captured(board, group))) {
1083 board_group_capture(board, group);
1085 board_hash_commit(board);
1086 return 0;
1087 } else {
1088 return board_play_in_eye(board, m, f);
1093 board_play(struct board *board, struct move *m)
1095 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1096 board->last_move2 = board->last_move;
1097 board->last_move = *m;
1098 return 0;
1101 int f;
1102 for (f = 0; f < board->flen; f++)
1103 if (board->f[f] == coord_raw(m->coord))
1104 return board_play_f(board, m, f);
1106 if (DEBUGL(7))
1107 fprintf(stderr, "board_check: stone exists\n");
1108 return -1;
1112 static inline bool
1113 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1115 coord_raw(*coord) = b->f[f];
1116 if (unlikely(is_pass(*coord)))
1117 return random_pass;
1118 struct move m = { *coord, color };
1119 if (DEBUGL(6))
1120 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
1121 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
1122 && board_is_valid_move(b, &m)
1123 && (!permit || permit(permit_data, b, &m))
1124 && likely(board_play_f(b, &m, f) >= 0));
1127 void
1128 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1130 int base = fast_random(b->flen);
1131 coord_pos(*coord, base, b);
1132 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
1133 return;
1135 int f;
1136 for (f = base + 1; f < b->flen; f++)
1137 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1138 return;
1139 for (f = 0; f < base; f++)
1140 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1141 return;
1143 *coord = pass;
1147 bool
1148 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
1150 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1152 /* XXX: We attempt false eye detection but we will yield false
1153 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1155 foreach_diag_neighbor(board, *coord) {
1156 color_diag_libs[(enum stone) board_at(board, c)]++;
1157 } foreach_diag_neighbor_end;
1158 /* For false eye, we need two enemy stones diagonally in the
1159 * middle of the board, or just one enemy stone at the edge
1160 * or in the corner. */
1161 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1162 return color_diag_libs[stone_other(eye_color)] >= 2;
1165 bool
1166 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
1168 return board_is_eyelike(board, coord, eye_color)
1169 && !board_is_false_eyelike(board, coord, eye_color);
1172 enum stone
1173 board_get_one_point_eye(struct board *board, coord_t *coord)
1175 if (board_is_one_point_eye(board, coord, S_WHITE))
1176 return S_WHITE;
1177 else if (board_is_one_point_eye(board, coord, S_BLACK))
1178 return S_BLACK;
1179 else
1180 return S_NONE;
1184 float
1185 board_fast_score(struct board *board)
1187 int scores[S_MAX];
1188 memset(scores, 0, sizeof(scores));
1190 foreach_point(board) {
1191 enum stone color = board_at(board, c);
1192 if (color == S_NONE)
1193 color = board_get_one_point_eye(board, &c);
1194 scores[color]++;
1195 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1196 } foreach_point_end;
1198 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1201 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1203 /* One flood-fill iteration; returns true if next iteration
1204 * is required. */
1205 static bool
1206 board_tromp_taylor_iter(struct board *board, int *ownermap)
1208 bool needs_update = false;
1209 foreach_point(board) {
1210 /* Ignore occupied and already-dame positions. */
1211 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1212 continue;
1213 /* Count neighbors. */
1214 int nei[4] = {0};
1215 foreach_neighbor(board, c, {
1216 nei[ownermap[c]]++;
1218 /* If we have neighbors of both colors, or dame,
1219 * we are dame too. */
1220 if ((nei[1] && nei[2]) || nei[3]) {
1221 ownermap[c] = 3;
1222 /* Speed up the propagation. */
1223 foreach_neighbor(board, c, {
1224 if (board_at(board, c) == S_NONE)
1225 ownermap[c] = 3;
1227 needs_update = true;
1228 continue;
1230 /* If we have neighbors of one color, we are owned
1231 * by that color, too. */
1232 if (!ownermap[c] && (nei[1] || nei[2])) {
1233 int newowner = nei[1] ? 1 : 2;
1234 ownermap[c] = newowner;
1235 /* Speed up the propagation. */
1236 foreach_neighbor(board, c, {
1237 if (board_at(board, c) == S_NONE && !ownermap[c])
1238 ownermap[c] = newowner;
1240 needs_update = true;
1241 continue;
1243 } foreach_point_end;
1244 return needs_update;
1247 /* Tromp-Taylor Counting */
1248 float
1249 board_official_score(struct board *board, struct move_queue *q)
1252 /* A point P, not colored C, is said to reach C, if there is a path of
1253 * (vertically or horizontally) adjacent points of P's color from P to
1254 * a point of color C.
1256 * A player's score is the number of points of her color, plus the
1257 * number of empty points that reach only her color. */
1259 int ownermap[board_size2(board)];
1260 int s[4] = {0};
1261 const int o[4] = {0, 1, 2, 0};
1262 foreach_point(board) {
1263 ownermap[c] = o[board_at(board, c)];
1264 s[board_at(board, c)]++;
1265 } foreach_point_end;
1267 if (q) {
1268 /* Process dead groups. */
1269 for (int i = 0; i < q->moves; i++) {
1270 foreach_in_group(board, q->move[i]) {
1271 enum stone color = board_at(board, c);
1272 ownermap[c] = o[stone_other(color)];
1273 s[color]--; s[stone_other(color)]++;
1274 } foreach_in_group_end;
1278 /* We need to special-case empty board. */
1279 if (!s[S_BLACK] && !s[S_WHITE])
1280 return board->komi + board->handicap;
1282 while (board_tromp_taylor_iter(board, ownermap))
1283 /* Flood-fill... */;
1285 int scores[S_MAX];
1286 memset(scores, 0, sizeof(scores));
1288 foreach_point(board) {
1289 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1290 if (ownermap[c] == 3)
1291 continue;
1292 scores[ownermap[c]]++;
1293 } foreach_point_end;
1295 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1299 /* On average 25% of points remain empty at the end of a game */
1300 #define EXPECTED_FINAL_EMPTY_PERCENT 25
1302 /* Returns estimated number of remaining moves for one player until end of game. */
1304 board_estimated_moves_left(struct board *b)
1306 int total_points = (board_size(b)-2)*(board_size(b)-2);
1307 int moves_left = (b->flen - total_points*EXPECTED_FINAL_EMPTY_PERCENT/100)/2;
1308 return moves_left > MIN_MOVES_LEFT ? moves_left : MIN_MOVES_LEFT;