UCT max_tree_size: Print a notification when memory gets full
[pachi.git] / board.c
blob8cb509cdb24cf3831d46312946b827aa9c99afd8
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 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size);
82 memcpy(x, b1->b, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size);
83 b2->b = x; x += bsize;
84 b2->g = x; x += gsize;
85 b2->f = x; x += fsize;
86 b2->p = x; x += psize;
87 b2->n = x; x += nsize;
88 b2->h = x; x += hsize;
89 b2->gi = x; x += gisize;
90 #ifdef WANT_BOARD_C
91 b2->c = x; x += csize;
92 #endif
93 #ifdef BOARD_SPATHASH
94 b2->spathash = x; x += ssize;
95 #endif
96 #ifdef BOARD_PAT3
97 b2->pat3 = x; x += p3size;
98 #endif
100 return b2;
103 void
104 board_done_noalloc(struct board *board)
106 if (board->b) free(board->b);
109 void
110 board_done(struct board *board)
112 board_done_noalloc(board);
113 free(board);
116 void
117 board_resize(struct board *board, int size)
119 #ifdef BOARD_SIZE
120 assert(board_size(board) == size + 2);
121 #else
122 board_size(board) = size + 2 /* S_OFFBOARD margin */;
123 board_size2(board) = board_size(board) * board_size(board);
124 #endif
125 if (board->b)
126 free(board->b);
128 int bsize = board_size2(board) * sizeof(*board->b);
129 int gsize = board_size2(board) * sizeof(*board->g);
130 int fsize = board_size2(board) * sizeof(*board->f);
131 int nsize = board_size2(board) * sizeof(*board->n);
132 int psize = board_size2(board) * sizeof(*board->p);
133 int hsize = board_size2(board) * 2 * sizeof(*board->h);
134 int gisize = board_size2(board) * sizeof(*board->gi);
135 #ifdef WANT_BOARD_C
136 int csize = board_size2(board) * sizeof(*board->c);
137 #else
138 int csize = 0;
139 #endif
140 #ifdef BOARD_SPATHASH
141 int ssize = board_size2(board) * sizeof(*board->spathash);
142 #else
143 int ssize = 0;
144 #endif
145 #ifdef BOARD_PAT3
146 int p3size = board_size2(board) * sizeof(*board->pat3);
147 #else
148 int p3size = 0;
149 #endif
150 void *x = malloc(bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size);
151 memset(x, 0, bsize + gsize + fsize + psize + nsize + hsize + gisize + csize + ssize + p3size);
152 board->b = x; x += bsize;
153 board->g = x; x += gsize;
154 board->f = x; x += fsize;
155 board->p = x; x += psize;
156 board->n = x; x += nsize;
157 board->h = x; x += hsize;
158 board->gi = x; x += gisize;
159 #ifdef WANT_BOARD_C
160 board->c = x; x += csize;
161 #endif
162 #ifdef BOARD_SPATHASH
163 board->spathash = x; x += ssize;
164 #endif
165 #ifdef BOARD_PAT3
166 board->pat3 = x; x += p3size;
167 #endif
170 void
171 board_clear(struct board *board)
173 int size = board_size(board);
174 float komi = board->komi;
176 board_done_noalloc(board);
177 board_setup(board);
178 board_resize(board, size - 2 /* S_OFFBOARD margin */);
180 board->komi = komi;
182 /* Setup neighborhood iterators */
183 board->nei8[0] = -size - 1; // (-1,-1)
184 board->nei8[1] = 1;
185 board->nei8[2] = 1;
186 board->nei8[3] = size - 2; // (-1,0)
187 board->nei8[4] = 2;
188 board->nei8[5] = size - 2; // (-1,1)
189 board->nei8[6] = 1;
190 board->nei8[7] = 1;
191 board->dnei[0] = -size - 1;
192 board->dnei[1] = 2;
193 board->dnei[2] = size*2 - 2;
194 board->dnei[3] = 2;
196 /* Setup initial symmetry */
197 board->symmetry.d = 1;
198 board->symmetry.x1 = board->symmetry.y1 = board_size(board) / 2;
199 board->symmetry.x2 = board->symmetry.y2 = board_size(board) - 1;
200 board->symmetry.type = SYM_FULL;
202 /* Draw the offboard margin */
203 int top_row = board_size2(board) - board_size(board);
204 int i;
205 for (i = 0; i < board_size(board); i++)
206 board->b[i] = board->b[top_row + i] = S_OFFBOARD;
207 for (i = 0; i <= top_row; i += board_size(board))
208 board->b[i] = board->b[board_size(board) - 1 + i] = S_OFFBOARD;
210 foreach_point(board) {
211 coord_t coord = c;
212 if (board_at(board, coord) == S_OFFBOARD)
213 continue;
214 foreach_neighbor(board, c, {
215 inc_neighbor_count_at(board, coord, board_at(board, c));
216 } );
217 } foreach_point_end;
219 /* First, pass is always a free position. */
220 board->f[board->flen++] = coord_raw(pass);
221 /* All positions are free! Except the margin. */
222 for (i = board_size(board); i < (board_size(board) - 1) * board_size(board); i++)
223 if (i % board_size(board) != 0 && i % board_size(board) != board_size(board) - 1)
224 board->f[board->flen++] = i;
226 /* Initialize zobrist hashtable. */
227 foreach_point(board) {
228 int max = (sizeof(hash_t) << history_hash_bits);
229 /* fast_random() is 16-bit only */
230 board->h[coord_raw(c) * 2] = ((hash_t) fast_random(max))
231 | ((hash_t) fast_random(max) << 16)
232 | ((hash_t) fast_random(max) << 32)
233 | ((hash_t) fast_random(max) << 48);
234 if (!board->h[coord_raw(c) * 2])
235 /* Would be kinda "oops". */
236 board->h[coord_raw(c) * 2] = 1;
237 /* And once again for white */
238 board->h[coord_raw(c) * 2 + 1] = ((hash_t) fast_random(max))
239 | ((hash_t) fast_random(max) << 16)
240 | ((hash_t) fast_random(max) << 32)
241 | ((hash_t) fast_random(max) << 48);
242 if (!board->h[coord_raw(c) * 2 + 1])
243 board->h[coord_raw(c) * 2 + 1] = 1;
244 } foreach_point_end;
246 #ifdef BOARD_SPATHASH
247 /* Initialize spatial hashes. */
248 foreach_point(board) {
249 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
250 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
251 ptcoords_at(x, y, c, board, j);
252 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
253 pthashes[0][j][board_at(board, c)];
254 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
255 pthashes[0][j][stone_other(board_at(board, c))];
258 } foreach_point_end;
259 #endif
260 #ifdef BOARD_PAT3
261 /* Initialize 3x3 pattern codes. */
262 foreach_point(board) {
263 if (board_at(board, c) == S_NONE)
264 board->pat3[c] = pattern3_hash(board, c);
265 } foreach_point_end;
266 #endif
270 static void
271 board_print_top(struct board *board, FILE *f, int c)
273 for (int i = 0; i < c; i++) {
274 char asdf[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
275 fprintf(f, " ");
276 for (int x = 1; x < board_size(board) - 1; x++)
277 fprintf(f, "%c ", asdf[x - 1]);
278 fprintf(f, " ");
280 fprintf(f, "\n");
281 for (int i = 0; i < c; i++) {
282 fprintf(f, " +-");
283 for (int x = 1; x < board_size(board) - 1; x++)
284 fprintf(f, "--");
285 fprintf(f, "+");
287 fprintf(f, "\n");
290 static void
291 board_print_bottom(struct board *board, FILE *f, int c)
293 for (int i = 0; i < c; i++) {
294 fprintf(f, " +-");
295 for (int x = 1; x < board_size(board) - 1; x++)
296 fprintf(f, "--");
297 fprintf(f, "+");
299 fprintf(f, "\n");
302 static void
303 board_print_row(struct board *board, int y, FILE *f, board_cprint cprint)
305 fprintf(f, " %2d | ", y);
306 for (int x = 1; x < board_size(board) - 1; x++) {
307 if (coord_x(board->last_move.coord, board) == x && coord_y(board->last_move.coord, board) == y)
308 fprintf(f, "%c)", stone2char(board_atxy(board, x, y)));
309 else
310 fprintf(f, "%c ", stone2char(board_atxy(board, x, y)));
312 fprintf(f, "|");
313 if (cprint) {
314 fprintf(f, " %2d | ", y);
315 for (int x = 1; x < board_size(board) - 1; x++) {
316 cprint(board, coord_xy(board, x, y), f);
318 fprintf(f, "|");
320 fprintf(f, "\n");
323 void
324 board_print_custom(struct board *board, FILE *f, board_cprint cprint)
326 fprintf(f, "Move: % 3d Komi: %2.1f Handicap: %d Captures B: %d W: %d\n",
327 board->moves, board->komi, board->handicap,
328 board->captures[S_BLACK], board->captures[S_WHITE]);
329 board_print_top(board, f, 1 + !!cprint);
330 for (int y = board_size(board) - 2; y >= 1; y--)
331 board_print_row(board, y, f, cprint);
332 board_print_bottom(board, f, 1 + !!cprint);
333 fprintf(f, "\n");
336 static void
337 cprint_group(struct board *board, coord_t c, FILE *f)
339 fprintf(f, "%d ", group_base(group_at(board, c)));
342 void
343 board_print(struct board *board, FILE *f)
345 board_print_custom(board, f, DEBUGL(6) ? cprint_group : NULL);
349 /* Update board hash with given coordinate. */
350 static void profiling_noinline
351 board_hash_update(struct board *board, coord_t coord, enum stone color)
353 board->hash ^= hash_at(board, coord, color);
354 if (DEBUGL(8))
355 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);
357 #ifdef BOARD_SPATHASH
358 /* Gridcular metric is reflective, so we update all hashes
359 * of appropriate ditance in OUR circle. */
360 for (int d = 1; d <= BOARD_SPATHASH_MAXD; d++) {
361 for (int j = ptind[d]; j < ptind[d + 1]; j++) {
362 ptcoords_at(x, y, coord, board, j);
363 /* We either changed from S_NONE to color
364 * or vice versa; doesn't matter. */
365 board->spathash[coord_xy(board, x, y)][d - 1][0] ^=
366 pthashes[0][j][color] ^ pthashes[0][j][S_NONE];
367 board->spathash[coord_xy(board, x, y)][d - 1][1] ^=
368 pthashes[0][j][stone_other(color)] ^ pthashes[0][j][S_NONE];
371 #endif
373 #ifdef BOARD_PAT3
374 /* @color is not what we need in case of capture. */
375 enum stone new_color = board_at(board, coord);
376 if (new_color == S_NONE)
377 board->pat3[coord] = pattern3_hash(board, coord);
378 foreach_8neighbor(board, coord) { // internally, the loop uses fn__i=[0..7]
379 if (board_at(board, c) != S_NONE)
380 continue;
381 board->pat3[c] &= ~(3 << (fn__i*2));
382 board->pat3[c] |= new_color << (fn__i*2);
383 #if 0
384 if (board_at(board, c) != S_OFFBOARD && pattern3_hash(board, c) != board->pat3[c]) {
385 board_print(board, stderr);
386 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);
387 assert(0);
389 #endif
390 } foreach_8neighbor_end;
391 #endif
394 /* Commit current board hash to history. */
395 static void profiling_noinline
396 board_hash_commit(struct board *board)
398 if (DEBUGL(8))
399 fprintf(stderr, "board_hash_commit %"PRIhash"\n", board->hash);
400 if (likely(board->history_hash[board->hash & history_hash_mask]) == 0) {
401 board->history_hash[board->hash & history_hash_mask] = board->hash;
402 } else {
403 hash_t i = board->hash;
404 while (board->history_hash[i & history_hash_mask]) {
405 if (board->history_hash[i & history_hash_mask] == board->hash) {
406 if (DEBUGL(5))
407 fprintf(stderr, "SUPERKO VIOLATION noted at %d,%d\n",
408 coord_x(board->last_move.coord, board), coord_y(board->last_move.coord, board));
409 board->superko_violation = true;
410 return;
412 i = history_hash_next(i);
414 board->history_hash[i & history_hash_mask] = board->hash;
419 void
420 board_symmetry_update(struct board *b, struct board_symmetry *symmetry, coord_t c)
422 if (likely(symmetry->type == SYM_NONE)) {
423 /* Fully degenerated already. We do not support detection
424 * of restoring of symmetry, assuming that this is too rare
425 * a case to handle. */
426 return;
429 int x = coord_x(c, b), y = coord_y(c, b), t = board_size(b) / 2;
430 int dx = board_size(b) - 1 - x; /* for SYM_DOWN */
431 if (DEBUGL(6)) {
432 fprintf(stderr, "SYMMETRY [%d,%d,%d,%d|%d=%d] update for %d,%d\n",
433 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
434 symmetry->d, symmetry->type, x, y);
437 switch (symmetry->type) {
438 case SYM_FULL:
439 if (x == t && y == t) {
440 /* Tengen keeps full symmetry. */
441 return;
443 /* New symmetry now? */
444 if (x == y) {
445 symmetry->type = SYM_DIAG_UP;
446 symmetry->x1 = symmetry->y1 = 1;
447 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
448 symmetry->d = 1;
449 } else if (dx == y) {
450 symmetry->type = SYM_DIAG_DOWN;
451 symmetry->x1 = symmetry->y1 = 1;
452 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
453 symmetry->d = 1;
454 } else if (x == t) {
455 symmetry->type = SYM_HORIZ;
456 symmetry->y1 = 1;
457 symmetry->y2 = board_size(b) - 1;
458 symmetry->d = 0;
459 } else if (y == t) {
460 symmetry->type = SYM_VERT;
461 symmetry->x1 = 1;
462 symmetry->x2 = board_size(b) - 1;
463 symmetry->d = 0;
464 } else {
465 break_symmetry:
466 symmetry->type = SYM_NONE;
467 symmetry->x1 = symmetry->y1 = 1;
468 symmetry->x2 = symmetry->y2 = board_size(b) - 1;
469 symmetry->d = 0;
471 break;
472 case SYM_DIAG_UP:
473 if (x == y)
474 return;
475 goto break_symmetry;
476 case SYM_DIAG_DOWN:
477 if (dx == y)
478 return;
479 goto break_symmetry;
480 case SYM_HORIZ:
481 if (x == t)
482 return;
483 goto break_symmetry;
484 case SYM_VERT:
485 if (y == t)
486 return;
487 goto break_symmetry;
488 case SYM_NONE:
489 assert(0);
490 break;
493 if (DEBUGL(6)) {
494 fprintf(stderr, "NEW SYMMETRY [%d,%d,%d,%d|%d=%d]\n",
495 symmetry->x1, symmetry->y1, symmetry->x2, symmetry->y2,
496 symmetry->d, symmetry->type);
498 /* Whew. */
502 void
503 board_handicap_stone(struct board *board, int x, int y, FILE *f)
505 struct move m;
506 m.color = S_BLACK; m.coord = coord_xy(board, x, y);
508 board_play(board, &m);
509 /* Simulate white passing; otherwise, UCT search can get confused since
510 * tree depth parity won't match the color to move. */
511 board->moves++;
513 char *str = coord2str(m.coord, board);
514 if (DEBUGL(1))
515 fprintf(stderr, "choosing handicap %s (%d,%d)\n", str, x, y);
516 fprintf(f, "%s ", str);
517 free(str);
520 void
521 board_handicap(struct board *board, int stones, FILE *f)
523 int margin = 3 + (board_size(board) >= 13);
524 int min = margin;
525 int mid = board_size(board) / 2;
526 int max = board_size(board) - 1 - margin;
527 const int places[][2] = {
528 { min, min }, { max, max }, { max, min }, { min, max },
529 { min, mid }, { max, mid },
530 { mid, min }, { mid, max },
531 { mid, mid },
534 board->handicap = stones;
536 if (stones == 5 || stones == 7) {
537 board_handicap_stone(board, mid, mid, f);
538 stones--;
541 int i;
542 for (i = 0; i < stones; i++)
543 board_handicap_stone(board, places[i][0], places[i][1], f);
547 static void __attribute__((noinline))
548 check_libs_consistency(struct board *board, group_t g)
550 #ifdef DEBUG
551 if (!g) return;
552 struct group *gi = &board_group_info(board, g);
553 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
554 if (gi->lib[i] && board_at(board, gi->lib[i]) != S_NONE) {
555 fprintf(stderr, "BOGUS LIBERTY %s of group %d[%s]\n", coord2sstr(gi->lib[i], board), g, coord2sstr(group_base(g), board));
556 assert(0);
558 #endif
561 static void
562 board_capturable_add(struct board *board, group_t group)
564 #ifdef WANT_BOARD_C
565 //fprintf(stderr, "add of group %d (%d)\n", group_base(group), board->clen);
566 assert(group);
567 assert(board->clen < board_size2(board));
568 board->c[board->clen++] = group;
569 #endif
571 static void
572 board_capturable_rm(struct board *board, group_t group)
574 #ifdef WANT_BOARD_C
575 //fprintf(stderr, "rm of group %d\n", group_base(group));
576 for (int i = 0; i < board->clen; i++) {
577 if (unlikely(board->c[i] == group)) {
578 board->c[i] = board->c[--board->clen];
579 return;
582 fprintf(stderr, "rm of bad group %d\n", group_base(group));
583 assert(0);
584 #endif
587 static void
588 board_group_addlib(struct board *board, group_t group, coord_t coord)
590 if (DEBUGL(7)) {
591 fprintf(stderr, "Group %d[%s] %d: Adding liberty %s\n",
592 group_base(group), coord2sstr(group_base(group), board),
593 board_group_info(board, group).libs, coord2sstr(coord, board));
596 check_libs_consistency(board, group);
598 struct group *gi = &board_group_info(board, group);
599 if (gi->libs < GROUP_KEEP_LIBS) {
600 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
601 #if 0
602 /* Seems extra branch just slows it down */
603 if (!gi->lib[i])
604 break;
605 #endif
606 if (unlikely(gi->lib[i] == coord))
607 return;
609 if (gi->libs == 0)
610 board_capturable_add(board, group);
611 else if (gi->libs == 1)
612 board_capturable_rm(board, group);
613 gi->lib[gi->libs++] = coord;
616 check_libs_consistency(board, group);
619 static void
620 board_group_find_extra_libs(struct board *board, group_t group, struct group *gi, coord_t avoid)
622 /* Add extra liberty from the board to our liberty list. */
623 unsigned char watermark[board_size2(board) / 8];
624 memset(watermark, 0, sizeof(watermark));
625 #define watermark_get(c) (watermark[coord_raw(c) >> 3] & (1 << (coord_raw(c) & 7)))
626 #define watermark_set(c) watermark[coord_raw(c) >> 3] |= (1 << (coord_raw(c) & 7))
628 for (int i = 0; i < GROUP_KEEP_LIBS - 1; i++)
629 watermark_set(gi->lib[i]);
630 watermark_set(avoid);
632 foreach_in_group(board, group) {
633 coord_t coord2 = c;
634 foreach_neighbor(board, coord2, {
635 if (board_at(board, c) + watermark_get(c) != S_NONE)
636 continue;
637 watermark_set(c);
638 gi->lib[gi->libs++] = c;
639 if (unlikely(gi->libs >= GROUP_KEEP_LIBS))
640 return;
641 } );
642 } foreach_in_group_end;
643 #undef watermark_get
644 #undef watermark_set
647 static void
648 board_group_rmlib(struct board *board, group_t group, coord_t coord)
650 if (DEBUGL(7)) {
651 fprintf(stderr, "Group %d[%s] %d: Removing liberty %s\n",
652 group_base(group), coord2sstr(group_base(group), board),
653 board_group_info(board, group).libs, coord2sstr(coord, board));
656 struct group *gi = &board_group_info(board, group);
657 for (int i = 0; i < GROUP_KEEP_LIBS; i++) {
658 #if 0
659 /* Seems extra branch just slows it down */
660 if (!gi->lib[i])
661 break;
662 #endif
663 if (likely(gi->lib[i] != coord))
664 continue;
666 gi->lib[i] = gi->lib[--gi->libs];
667 gi->lib[gi->libs] = 0;
669 check_libs_consistency(board, group);
671 /* Postpone refilling lib[] until we need to. */
672 assert(GROUP_REFILL_LIBS > 1);
673 if (gi->libs > GROUP_REFILL_LIBS)
674 return;
675 if (gi->libs == GROUP_REFILL_LIBS)
676 board_group_find_extra_libs(board, group, gi, coord);
678 if (gi->libs == 1)
679 board_capturable_add(board, group);
680 else if (gi->libs == 0)
681 board_capturable_rm(board, group);
682 return;
685 /* This is ok even if gi->libs < GROUP_KEEP_LIBS since we
686 * can call this multiple times per coord. */
687 check_libs_consistency(board, group);
688 return;
692 /* This is a low-level routine that doesn't maintain consistency
693 * of all the board data structures. */
694 static void
695 board_remove_stone(struct board *board, coord_t c)
697 enum stone color = board_at(board, c);
698 board_at(board, c) = S_NONE;
699 group_at(board, c) = 0;
700 board_hash_update(board, c, color);
702 /* Increase liberties of surrounding groups */
703 coord_t coord = c;
704 foreach_neighbor(board, coord, {
705 dec_neighbor_count_at(board, c, color);
706 group_t g = group_at(board, c);
707 if (g)
708 board_group_addlib(board, g, coord);
711 if (DEBUGL(6))
712 fprintf(stderr, "pushing free move [%d]: %d,%d\n", board->flen, coord_x(c, board), coord_y(c, board));
713 board->f[board->flen++] = coord_raw(c);
716 static int profiling_noinline
717 board_group_capture(struct board *board, group_t group)
719 int stones = 0;
721 foreach_in_group(board, group) {
722 board->captures[stone_other(board_at(board, c))]++;
723 board_remove_stone(board, c);
724 stones++;
725 } foreach_in_group_end;
727 if (board_group_info(board, group).libs == 1)
728 board_capturable_rm(board, group);
729 memset(&board_group_info(board, group), 0, sizeof(struct group));
731 return stones;
735 static void profiling_noinline
736 add_to_group(struct board *board, group_t group, coord_t prevstone, coord_t coord)
738 foreach_neighbor(board, coord, {
739 if (board_at(board, c) == S_NONE)
740 board_group_addlib(board, group, c);
743 group_at(board, coord) = group;
744 groupnext_at(board, coord) = groupnext_at(board, prevstone);
745 groupnext_at(board, prevstone) = coord_raw(coord);
747 if (DEBUGL(8))
748 fprintf(stderr, "add_to_group: added (%d,%d ->) %d,%d (-> %d,%d) to group %d\n",
749 coord_x(prevstone, board), coord_y(prevstone, board),
750 coord_x(coord, board), coord_y(coord, board),
751 groupnext_at(board, coord) % board_size(board), groupnext_at(board, coord) / board_size(board),
752 group_base(group));
755 static void profiling_noinline
756 merge_groups(struct board *board, group_t group_to, group_t group_from)
758 if (DEBUGL(7))
759 fprintf(stderr, "board_play_raw: merging groups %d -> %d\n",
760 group_base(group_from), group_base(group_to));
762 coord_t last_in_group;
763 foreach_in_group(board, group_from) {
764 last_in_group = c;
765 group_at(board, c) = group_to;
766 } foreach_in_group_end;
767 groupnext_at(board, last_in_group) = groupnext_at(board, group_base(group_to));
768 groupnext_at(board, group_base(group_to)) = group_base(group_from);
770 struct group *gi_from = &board_group_info(board, group_from);
771 struct group *gi_to = &board_group_info(board, group_to);
772 if (gi_to->libs < GROUP_KEEP_LIBS) {
773 for (int i = 0; i < gi_from->libs; i++) {
774 for (int j = 0; j < gi_to->libs; j++)
775 if (gi_to->lib[j] == gi_from->lib[i])
776 goto next_from_lib;
777 if (gi_to->libs == 0)
778 board_capturable_add(board, group_to);
779 else if (gi_to->libs == 1)
780 board_capturable_rm(board, group_to);
781 gi_to->lib[gi_to->libs++] = gi_from->lib[i];
782 if (gi_to->libs >= GROUP_KEEP_LIBS)
783 break;
784 next_from_lib:;
788 if (gi_from->libs == 1)
789 board_capturable_rm(board, group_from);
790 memset(gi_from, 0, sizeof(struct group));
792 if (DEBUGL(7))
793 fprintf(stderr, "board_play_raw: merged group: %d\n",
794 group_base(group_to));
797 static group_t profiling_noinline
798 new_group(struct board *board, coord_t coord)
800 group_t group = coord_raw(coord);
801 struct group *gi = &board_group_info(board, group);
802 foreach_neighbor(board, coord, {
803 if (board_at(board, c) == S_NONE)
804 /* board_group_addlib is ridiculously expensive for us */
805 #if GROUP_KEEP_LIBS < 4
806 if (gi->libs < GROUP_KEEP_LIBS)
807 #endif
808 gi->lib[gi->libs++] = c;
810 if (gi->libs == 1)
811 board_capturable_add(board, group);
812 check_libs_consistency(board, group);
814 group_at(board, coord) = group;
815 groupnext_at(board, coord) = 0;
817 if (DEBUGL(8))
818 fprintf(stderr, "new_group: added %d,%d to group %d\n",
819 coord_x(coord, board), coord_y(coord, board),
820 group_base(group));
822 return group;
825 static inline group_t
826 play_one_neighbor(struct board *board,
827 coord_t coord, enum stone color, enum stone other_color,
828 coord_t c, group_t group)
830 enum stone ncolor = board_at(board, c);
831 group_t ngroup = group_at(board, c);
833 inc_neighbor_count_at(board, c, color);
835 if (!ngroup)
836 return group;
838 board_group_rmlib(board, ngroup, coord);
839 if (DEBUGL(7))
840 fprintf(stderr, "board_play_raw: reducing libs for group %d (%d:%d,%d)\n",
841 group_base(ngroup), ncolor, color, other_color);
843 if (ncolor == color && ngroup != group) {
844 if (!group) {
845 group = ngroup;
846 add_to_group(board, group, c, coord);
847 } else {
848 merge_groups(board, group, ngroup);
850 } else if (ncolor == other_color) {
851 if (DEBUGL(8)) {
852 struct group *gi = &board_group_info(board, ngroup);
853 fprintf(stderr, "testing captured group %d[%s]: ", group_base(ngroup), coord2sstr(group_base(ngroup), board));
854 for (int i = 0; i < GROUP_KEEP_LIBS; i++)
855 fprintf(stderr, "%s ", coord2sstr(gi->lib[i], board));
856 fprintf(stderr, "\n");
858 if (unlikely(board_group_captured(board, ngroup)))
859 board_group_capture(board, ngroup);
861 return group;
864 /* We played on a place with at least one liberty. We will become a member of
865 * some group for sure. */
866 static group_t profiling_noinline
867 board_play_outside(struct board *board, struct move *m, int f)
869 coord_t coord = m->coord;
870 enum stone color = m->color;
871 enum stone other_color = stone_other(color);
872 group_t group = 0;
874 board->f[f] = board->f[--board->flen];
875 if (DEBUGL(6))
876 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
878 foreach_neighbor(board, coord, {
879 group = play_one_neighbor(board, coord, color, other_color, c, group);
882 if (unlikely(!group))
883 group = new_group(board, coord);
885 board_at(board, coord) = color;
886 board->last_move2 = board->last_move;
887 board->last_move = *m;
888 board->moves++;
889 board_hash_update(board, coord, color);
890 board_symmetry_update(board, &board->symmetry, coord);
891 struct move ko = { pass, S_NONE };
892 board->ko = ko;
894 return group;
897 /* We played in an eye-like shape. Either we capture at least one of the eye
898 * sides in the process of playing, or return -1. */
899 static int profiling_noinline
900 board_play_in_eye(struct board *board, struct move *m, int f)
902 coord_t coord = m->coord;
903 enum stone color = m->color;
904 /* Check ko: Capture at a position of ko capture one move ago */
905 if (unlikely(color == board->ko.color && coord_eq(coord, board->ko.coord))) {
906 if (DEBUGL(5))
907 fprintf(stderr, "board_check: ko at %d,%d color %d\n", coord_x(coord, board), coord_y(coord, board), color);
908 return -1;
909 } else if (DEBUGL(6)) {
910 fprintf(stderr, "board_check: no ko at %d,%d,%d - ko is %d,%d,%d\n",
911 color, coord_x(coord, board), coord_y(coord, board),
912 board->ko.color, coord_x(board->ko.coord, board), coord_y(board->ko.coord, board));
915 struct move ko = { pass, S_NONE };
917 int captured_groups = 0;
919 foreach_neighbor(board, coord, {
920 group_t g = group_at(board, c);
921 if (DEBUGL(7))
922 fprintf(stderr, "board_check: group %d has %d libs\n",
923 g, board_group_info(board, g).libs);
924 captured_groups += (board_group_info(board, g).libs == 1);
927 if (likely(captured_groups == 0)) {
928 if (DEBUGL(5)) {
929 if (DEBUGL(6))
930 board_print(board, stderr);
931 fprintf(stderr, "board_check: one-stone suicide\n");
934 return -1;
937 board->f[f] = board->f[--board->flen];
938 if (DEBUGL(6))
939 fprintf(stderr, "popping free move [%d->%d]: %d\n", board->flen, f, board->f[f]);
941 foreach_neighbor(board, coord, {
942 inc_neighbor_count_at(board, c, color);
944 group_t group = group_at(board, c);
945 if (!group)
946 continue;
948 board_group_rmlib(board, group, coord);
949 if (DEBUGL(7))
950 fprintf(stderr, "board_play_raw: reducing libs for group %d\n",
951 group_base(group));
953 if (board_group_captured(board, group)) {
954 if (board_group_capture(board, group) == 1) {
955 /* If we captured multiple groups at once,
956 * we can't be fighting ko so we don't need
957 * to check for that. */
958 ko.color = stone_other(color);
959 ko.coord = c;
960 board->last_ko = ko;
961 board->last_ko_age = board->moves;
962 if (DEBUGL(5))
963 fprintf(stderr, "guarding ko at %d,%s\n", ko.color, coord2sstr(ko.coord, board));
968 board_at(board, coord) = color;
970 board->last_move2 = board->last_move;
971 board->last_move = *m;
972 board->moves++;
973 board_hash_update(board, coord, color);
974 board_hash_commit(board);
975 board_symmetry_update(board, &board->symmetry, coord);
976 board->ko = ko;
978 return !!new_group(board, coord);
981 static int __attribute__((flatten))
982 board_play_f(struct board *board, struct move *m, int f)
984 if (DEBUGL(7)) {
985 fprintf(stderr, "board_play(): ---- Playing %d,%d\n", coord_x(m->coord, board), coord_y(m->coord, board));
987 if (likely(!board_is_eyelike(board, &m->coord, stone_other(m->color)))) {
988 /* NOT playing in an eye. Thus this move has to succeed. (This
989 * is thanks to New Zealand rules. Otherwise, multi-stone
990 * suicide might fail.) */
991 group_t group = board_play_outside(board, m, f);
992 if (unlikely(board_group_captured(board, group))) {
993 board_group_capture(board, group);
995 board_hash_commit(board);
996 return 0;
997 } else {
998 return board_play_in_eye(board, m, f);
1003 board_play(struct board *board, struct move *m)
1005 if (unlikely(is_pass(m->coord) || is_resign(m->coord))) {
1006 board->last_move2 = board->last_move;
1007 board->last_move = *m;
1008 return 0;
1011 int f;
1012 for (f = 0; f < board->flen; f++)
1013 if (board->f[f] == coord_raw(m->coord))
1014 return board_play_f(board, m, f);
1016 if (DEBUGL(7))
1017 fprintf(stderr, "board_check: stone exists\n");
1018 return -1;
1022 static inline bool
1023 board_try_random_move(struct board *b, enum stone color, coord_t *coord, int f, ppr_permit permit, void *permit_data)
1025 coord_raw(*coord) = b->f[f];
1026 if (unlikely(is_pass(*coord)))
1027 return random_pass;
1028 struct move m = { *coord, color };
1029 if (DEBUGL(6))
1030 fprintf(stderr, "trying random move %d: %d,%d\n", f, coord_x(*coord, b), coord_y(*coord, b));
1031 return (likely(!board_is_one_point_eye(b, coord, color)) /* bad idea to play into one, usually */
1032 && board_is_valid_move(b, &m)
1033 && (!permit || permit(permit_data, b, &m))
1034 && likely(board_play_f(b, &m, f) >= 0));
1037 void
1038 board_play_random(struct board *b, enum stone color, coord_t *coord, ppr_permit permit, void *permit_data)
1040 int base = fast_random(b->flen);
1041 coord_pos(*coord, base, b);
1042 if (likely(board_try_random_move(b, color, coord, base, permit, permit_data)))
1043 return;
1045 int f;
1046 for (f = base + 1; f < b->flen; f++)
1047 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1048 return;
1049 for (f = 0; f < base; f++)
1050 if (board_try_random_move(b, color, coord, f, permit, permit_data))
1051 return;
1053 *coord = pass;
1057 bool
1058 board_is_false_eyelike(struct board *board, coord_t *coord, enum stone eye_color)
1060 enum stone color_diag_libs[S_MAX] = {0, 0, 0, 0};
1062 /* XXX: We attempt false eye detection but we will yield false
1063 * positives in case of http://senseis.xmp.net/?TwoHeadedDragon :-( */
1065 foreach_diag_neighbor(board, *coord) {
1066 color_diag_libs[(enum stone) board_at(board, c)]++;
1067 } foreach_diag_neighbor_end;
1068 /* For false eye, we need two enemy stones diagonally in the
1069 * middle of the board, or just one enemy stone at the edge
1070 * or in the corner. */
1071 color_diag_libs[stone_other(eye_color)] += !!color_diag_libs[S_OFFBOARD];
1072 return color_diag_libs[stone_other(eye_color)] >= 2;
1075 bool
1076 board_is_one_point_eye(struct board *board, coord_t *coord, enum stone eye_color)
1078 return board_is_eyelike(board, coord, eye_color)
1079 && !board_is_false_eyelike(board, coord, eye_color);
1082 enum stone
1083 board_get_one_point_eye(struct board *board, coord_t *coord)
1085 if (board_is_one_point_eye(board, coord, S_WHITE))
1086 return S_WHITE;
1087 else if (board_is_one_point_eye(board, coord, S_BLACK))
1088 return S_BLACK;
1089 else
1090 return S_NONE;
1094 float
1095 board_fast_score(struct board *board)
1097 int scores[S_MAX];
1098 memset(scores, 0, sizeof(scores));
1100 foreach_point(board) {
1101 enum stone color = board_at(board, c);
1102 if (color == S_NONE)
1103 color = board_get_one_point_eye(board, &c);
1104 scores[color]++;
1105 // fprintf(stderr, "%d, %d ++%d = %d\n", coord_x(c, board), coord_y(c, board), color, scores[color]);
1106 } foreach_point_end;
1108 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];
1111 /* Owner map: 0: undecided; 1: black; 2: white; 3: dame */
1113 /* One flood-fill iteration; returns true if next iteration
1114 * is required. */
1115 static bool
1116 board_tromp_taylor_iter(struct board *board, int *ownermap)
1118 bool needs_update = false;
1119 foreach_point(board) {
1120 /* Ignore occupied and already-dame positions. */
1121 if (board_at(board, c) != S_NONE || ownermap[c] == 3)
1122 continue;
1123 /* Count neighbors. */
1124 int nei[4] = {0};
1125 foreach_neighbor(board, c, {
1126 nei[ownermap[c]]++;
1128 /* If we have neighbors of both colors, or dame,
1129 * we are dame too. */
1130 if ((nei[1] && nei[2]) || nei[3]) {
1131 ownermap[c] = 3;
1132 /* Speed up the propagation. */
1133 foreach_neighbor(board, c, {
1134 if (board_at(board, c) == S_NONE)
1135 ownermap[c] = 3;
1137 needs_update = true;
1138 continue;
1140 /* If we have neighbors of one color, we are owned
1141 * by that color, too. */
1142 if (!ownermap[c] && (nei[1] || nei[2])) {
1143 int newowner = nei[1] ? 1 : 2;
1144 ownermap[c] = newowner;
1145 /* Speed up the propagation. */
1146 foreach_neighbor(board, c, {
1147 if (board_at(board, c) == S_NONE && !ownermap[c])
1148 ownermap[c] = newowner;
1150 needs_update = true;
1151 continue;
1153 } foreach_point_end;
1154 return needs_update;
1157 /* Tromp-Taylor Counting */
1158 float
1159 board_official_score(struct board *board, struct move_queue *q)
1162 /* A point P, not colored C, is said to reach C, if there is a path of
1163 * (vertically or horizontally) adjacent points of P's color from P to
1164 * a point of color C.
1166 * A player's score is the number of points of her color, plus the
1167 * number of empty points that reach only her color. */
1169 int ownermap[board_size2(board)];
1170 int s[4] = {0};
1171 const int o[4] = {0, 1, 2, 0};
1172 foreach_point(board) {
1173 ownermap[c] = o[board_at(board, c)];
1174 s[board_at(board, c)]++;
1175 } foreach_point_end;
1177 if (q) {
1178 /* Process dead groups. */
1179 for (int i = 0; i < q->moves; i++) {
1180 foreach_in_group(board, q->move[i]) {
1181 enum stone color = board_at(board, c);
1182 ownermap[c] = o[stone_other(color)];
1183 s[color]--; s[stone_other(color)]++;
1184 } foreach_in_group_end;
1188 /* We need to special-case empty board. */
1189 if (!s[S_BLACK] && !s[S_WHITE])
1190 return board->komi + board->handicap;
1192 while (board_tromp_taylor_iter(board, ownermap))
1193 /* Flood-fill... */;
1195 int scores[S_MAX];
1196 memset(scores, 0, sizeof(scores));
1198 foreach_point(board) {
1199 assert(board_at(board, c) == S_OFFBOARD || ownermap[c] != 0);
1200 if (ownermap[c] == 3)
1201 continue;
1202 scores[ownermap[c]]++;
1203 } foreach_point_end;
1205 return board->komi + board->handicap + scores[S_WHITE] - scores[S_BLACK];