pthashes_init(): Fix board overflow of the largest patterns
[pachi.git] / gtp.c
blob3c62742749964efaa932888c9bf6bf4c90e95e46
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <math.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
11 #include "board.h"
12 #include "debug.h"
13 #include "engine.h"
14 #include "fbook.h"
15 #include "gtp.h"
16 #include "mq.h"
17 #include "uct/uct.h"
18 #include "version.h"
19 #include "timeinfo.h"
21 #define NO_REPLY (-2)
23 /* Sleep 5 seconds after a game ends to give time to kill the program. */
24 #define GAME_OVER_SLEEP 5
26 void
27 gtp_prefix(char prefix, int id)
29 if (id == NO_REPLY) return;
30 if (id >= 0)
31 printf("%c%d ", prefix, id);
32 else
33 printf("%c ", prefix);
36 void
37 gtp_flush(void)
39 putchar('\n');
40 fflush(stdout);
43 void
44 gtp_output(char prefix, int id, va_list params)
46 if (id == NO_REPLY) return;
47 gtp_prefix(prefix, id);
48 char *s;
49 while ((s = va_arg(params, char *))) {
50 fputs(s, stdout);
52 putchar('\n');
53 gtp_flush();
56 void
57 gtp_reply(int id, ...)
59 va_list params;
60 va_start(params, id);
61 gtp_output('=', id, params);
62 va_end(params);
65 void
66 gtp_error(int id, ...)
68 va_list params;
69 va_start(params, id);
70 gtp_output('?', id, params);
71 va_end(params);
74 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
75 * it should only be used between master and slaves of the distributed engine. */
76 static char *known_commands =
77 "protocol_version\n"
78 "echo\n"
79 "name\n"
80 "version\n"
81 "list_commands\n"
82 "known_command\n"
83 "quit\n"
84 "boardsize\n"
85 "clear_board\n"
86 "kgs-game_over\n"
87 "komi\n"
88 "kgs-rules\n"
89 "play\n"
90 "genmove\n"
91 "kgs-genmove_cleanup\n"
92 "pachi-genmoves\n"
93 "pachi-genmoves_cleanup\n"
94 "set_free_handicap\n"
95 "place_free_handicap\n"
96 "fixed_handicap\n"
97 "final_score\n"
98 "final_status_list\n"
99 "undo\n"
100 "pachi-evaluate\n"
101 "pachi-result\n"
102 "pachi-gentbook\n"
103 "pachi-dumptbook\n"
104 "kgs-chat\n"
105 "time_left\n"
106 "time_settings\n"
107 "kgs-time_settings";
110 /* Return true if cmd is a valid gtp command. */
111 bool
112 gtp_is_valid(char *cmd)
114 if (!cmd || !*cmd) return false;
115 char *s = strcasestr(known_commands, cmd);
116 if (!s) return false;
117 if (s != known_commands && s[-1] != '\n') return false;
119 int len = strlen(cmd);
120 return s[len] == '\0' || s[len] == '\n';
123 /* XXX: THIS IS TOTALLY INSECURE!!!!
124 * Even basic input checking is missing. */
126 enum parse_code
127 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
129 #define next_tok(to_) \
130 to_ = next; \
131 next = next + strcspn(next, " \t\r\n"); \
132 if (*next) { \
133 *next = 0; next++; \
134 next += strspn(next, " \t\r\n"); \
137 if (strchr(buf, '#'))
138 *strchr(buf, '#') = 0;
140 char *cmd, *next = buf;
141 next_tok(cmd);
143 int id = -1;
144 if (isdigit(*cmd)) {
145 id = atoi(cmd);
146 next_tok(cmd);
149 if (!*cmd)
150 return P_OK;
152 if (!strcasecmp(cmd, "protocol_version")) {
153 gtp_reply(id, "2", NULL);
154 return P_OK;
156 } else if (!strcasecmp(cmd, "name")) {
157 /* KGS hack */
158 gtp_reply(id, "Pachi ", engine->name, NULL);
159 return P_OK;
161 } else if (!strcasecmp(cmd, "echo")) {
162 gtp_reply(id, next, NULL);
163 return P_OK;
165 } else if (!strcasecmp(cmd, "version")) {
166 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
167 return P_OK;
169 } else if (!strcasecmp(cmd, "list_commands")) {
170 gtp_reply(id, known_commands, NULL);
171 return P_OK;
173 } else if (!strcasecmp(cmd, "known_command")) {
174 char *arg;
175 next_tok(arg);
176 if (gtp_is_valid(arg)) {
177 gtp_reply(id, "true", NULL);
178 } else {
179 gtp_reply(id, "false", NULL);
181 return P_OK;
184 if (engine->notify && gtp_is_valid(cmd)) {
185 char *reply;
186 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
187 if (c == P_NOREPLY) {
188 id = NO_REPLY;
189 } else if (c == P_DONE_OK) {
190 gtp_reply(id, reply, NULL);
191 return P_OK;
192 } else if (c == P_DONE_ERROR) {
193 gtp_error(id, reply, NULL);
194 /* This is an internal error for the engine, but
195 * it is still OK from main's point of view. */
196 return P_OK;
197 } else if (c != P_OK) {
198 return c;
202 if (!strcasecmp(cmd, "quit")) {
203 gtp_reply(id, NULL);
204 exit(0);
206 } else if (!strcasecmp(cmd, "boardsize")) {
207 char *arg;
208 next_tok(arg);
209 int size = atoi(arg);
210 if (size < 1 || size > BOARD_MAX_SIZE) {
211 gtp_error(id, "illegal board size", NULL);
212 return P_OK;
214 board_resize(board, size);
215 board_clear(board);
216 gtp_reply(id, NULL);
218 } else if (!strcasecmp(cmd, "clear_board")) {
219 board_clear(board);
220 if (DEBUGL(1) && debug_boardprint)
221 board_print(board, stderr);
222 gtp_reply(id, NULL);
223 return P_ENGINE_RESET;
225 } else if (!strcasecmp(cmd, "kgs-game_over")) {
226 /* The game may not be really over, just adjourned.
227 * Do not clear the board to avoid illegal moves
228 * if the game is resumed immediately after. KGS
229 * may start directly with genmove on resumption. */
230 if (DEBUGL(1)) {
231 fprintf(stderr, "game is over\n");
232 fflush(stderr);
234 /* Sleep before replying, so that kgs doesn't
235 * start another game immediately. */
236 sleep(GAME_OVER_SLEEP);
237 gtp_reply(id, NULL);
239 } else if (!strcasecmp(cmd, "komi")) {
240 char *arg;
241 next_tok(arg);
242 sscanf(arg, PRIfloating, &board->komi);
244 if (DEBUGL(1) && debug_boardprint)
245 board_print(board, stderr);
246 gtp_reply(id, NULL);
248 } else if (!strcasecmp(cmd, "kgs-rules")) {
249 char *arg;
250 next_tok(arg);
251 if (!strcasecmp(arg, "japanese")) {
252 board->rules = RULES_JAPANESE;
253 } else if (!strcasecmp(arg, "chinese")) {
254 board->rules = RULES_CHINESE;
255 } else if (!strcasecmp(arg, "aga")) {
256 board->rules = RULES_AGA;
257 } else if (!strcasecmp(arg, "new_zealand")) {
258 board->rules = RULES_NEW_ZEALAND;
259 } else {
260 gtp_error(id, "unknown rules", NULL);
261 return P_OK;
263 gtp_reply(id, NULL);
265 } else if (!strcasecmp(cmd, "play")) {
266 struct move m;
268 char *arg;
269 next_tok(arg);
270 m.color = str2stone(arg);
271 next_tok(arg);
272 coord_t *c = str2coord(arg, board_size(board));
273 m.coord = *c; coord_done(c);
274 char *reply = NULL;
276 if (DEBUGL(1))
277 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
279 // This is where kgs starts the timer, not at genmove!
280 time_start_timer(&ti[stone_other(m.color)]);
282 if (engine->notify_play)
283 reply = engine->notify_play(engine, board, &m);
284 if (board_play(board, &m) < 0) {
285 if (DEBUGL(0)) {
286 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
287 board_print(board, stderr);
289 gtp_error(id, "illegal move", NULL);
290 } else {
291 if (DEBUGL(1) && debug_boardprint)
292 board_print_custom(board, stderr, engine->printhook);
293 gtp_reply(id, reply, NULL);
296 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
297 char *arg;
298 next_tok(arg);
299 enum stone color = str2stone(arg);
300 coord_t *c = NULL;
302 if (!ti[color].len.t.timer_start) {
303 /* First game move. */
304 time_start_timer(&ti[color]);
307 coord_t cf = pass;
308 if (board->fbook)
309 cf = fbook_check(board);
310 if (!is_pass(cf)) {
311 c = coord_copy(cf);
312 } else {
313 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
315 struct move m = { *c, color };
316 if (board_play(board, &m) < 0) {
317 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
318 abort();
320 char *str = coord2str(*c, board);
321 if (DEBUGL(1))
322 fprintf(stderr, "playing move %s\n", str);
323 if (DEBUGL(1) && debug_boardprint) {
324 board_print_custom(board, stderr, engine->printhook);
326 gtp_reply(id, str, NULL);
327 free(str); coord_done(c);
329 /* Account for spent time. If our GTP peer keeps our clock, this will
330 * be overriden by next time_left GTP command properly. */
331 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
332 * should be absolutely rare situation and we will just spend a little
333 * less time than we could on next few moves.) */
334 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
335 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
337 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
338 char *arg;
339 next_tok(arg);
340 enum stone color = str2stone(arg);
341 void *stats;
342 int stats_size;
344 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
345 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
346 &stats, &stats_size);
347 if (!reply) {
348 gtp_error(id, "genmoves error", NULL);
349 return P_OK;
351 if (DEBUGL(3))
352 fprintf(stderr, "proposing moves %s\n", reply);
353 if (DEBUGL(4) && debug_boardprint)
354 board_print_custom(board, stderr, engine->printhook);
355 gtp_reply(id, reply, NULL);
356 if (stats_size > 0) {
357 double start = time_now();
358 fwrite(stats, 1, stats_size, stdout);
359 fflush(stdout);
360 if (DEBUGVV(2))
361 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
362 stats_size, (time_now() - start)*1000);
365 } else if (!strcasecmp(cmd, "set_free_handicap")) {
366 struct move m;
367 m.color = S_BLACK;
369 char *arg;
370 next_tok(arg);
371 do {
372 coord_t *c = str2coord(arg, board_size(board));
373 m.coord = *c; coord_done(c);
374 if (DEBUGL(1))
375 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
377 if (board_play(board, &m) < 0) {
378 if (DEBUGL(0))
379 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
380 gtp_error(id, "illegal move", NULL);
382 board->handicap++;
383 next_tok(arg);
384 } while (*arg);
385 if (DEBUGL(1) && debug_boardprint)
386 board_print(board, stderr);
387 gtp_reply(id, NULL);
389 /* TODO: Engine should choose free handicap; however, it tends to take
390 * overly long to think it all out, and unless it's clever its
391 * handicap stones won't be of much help. ;-) */
392 } else if (!strcasecmp(cmd, "place_free_handicap")
393 || !strcasecmp(cmd, "fixed_handicap")) {
394 char *arg;
395 next_tok(arg);
396 int stones = atoi(arg);
398 gtp_prefix('=', id);
399 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
400 if (DEBUGL(1) && debug_boardprint)
401 board_print(board, stderr);
402 if (id == NO_REPLY) return P_OK;
403 putchar('\n');
404 gtp_flush();
406 } else if (!strcasecmp(cmd, "final_score")) {
407 struct move_queue q = { .moves = 0 };
408 if (engine->dead_group_list)
409 engine->dead_group_list(engine, board, &q);
410 floating_t score = board_official_score(board, &q);
411 char str[64];
412 if (DEBUGL(1))
413 fprintf(stderr, "counted score %.1f\n", score);
414 if (score == 0) {
415 gtp_reply(id, "0", NULL);
416 } else if (score > 0) {
417 snprintf(str, 64, "W+%.1f", score);
418 gtp_reply(id, str, NULL);
419 } else {
420 snprintf(str, 64, "B+%.1f", -score);
421 gtp_reply(id, str, NULL);
424 /* XXX: This is a huge hack. */
425 } else if (!strcasecmp(cmd, "final_status_list")) {
426 if (id == NO_REPLY) return P_OK;
427 char *arg;
428 next_tok(arg);
429 struct move_queue q = { .moves = 0 };
430 if (engine->dead_group_list)
431 engine->dead_group_list(engine, board, &q);
432 /* else we return empty list - i.e. engine not supporting
433 * this assumes all stones alive at the game end. */
434 if (!strcasecmp(arg, "dead")) {
435 gtp_prefix('=', id);
436 for (unsigned int i = 0; i < q.moves; i++) {
437 foreach_in_group(board, q.move[i]) {
438 printf("%s ", coord2sstr(c, board));
439 } foreach_in_group_end;
440 putchar('\n');
442 if (!q.moves)
443 putchar('\n');
444 gtp_flush();
445 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
446 gtp_prefix('=', id);
447 bool printed_group = false;
448 foreach_point(board) { // foreach_group, effectively
449 group_t g = group_at(board, c);
450 if (!g || g != c) continue;
452 for (unsigned int i = 0; i < q.moves; i++) {
453 if (q.move[i] == g)
454 goto next_group;
456 foreach_in_group(board, g) {
457 printf("%s ", coord2sstr(c, board));
458 } foreach_in_group_end;
459 putchar('\n');
460 printed_group = true;
461 next_group:;
462 } foreach_point_end;
463 if (!printed_group)
464 putchar('\n');
465 gtp_flush();
466 } else {
467 gtp_error(id, "illegal status specifier", NULL);
470 } else if (!strcasecmp(cmd, "undo")) {
471 if (board_undo(board) < 0) {
472 if (DEBUGL(1)) {
473 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
474 board_print(board, stderr);
476 gtp_error(id, "cannot undo", NULL);
477 return P_OK;
479 char *reply = NULL;
480 if (engine->undo)
481 reply = engine->undo(engine, board);
482 if (DEBUGL(1) && debug_boardprint)
483 board_print(board, stderr);
484 gtp_reply(id, reply, NULL);
486 /* Custom commands for handling the tree opening tbook */
487 } else if (!strcasecmp(cmd, "pachi-gentbook")) {
488 /* Board must be initialized properly, as if for genmove;
489 * makes sense only as 'uct_gentbook b'. */
490 char *arg;
491 next_tok(arg);
492 enum stone color = str2stone(arg);
493 if (uct_gentbook(engine, board, &ti[color], color))
494 gtp_reply(id, NULL);
495 else
496 gtp_error(id, "error generating tbook", NULL);
498 } else if (!strcasecmp(cmd, "pachi-dumptbook")) {
499 char *arg;
500 next_tok(arg);
501 enum stone color = str2stone(arg);
502 uct_dumptbook(engine, board, color);
503 gtp_reply(id, NULL);
505 } else if (!strcasecmp(cmd, "pachi-evaluate")) {
506 char *arg;
507 next_tok(arg);
508 enum stone color = str2stone(arg);
510 if (!engine->evaluate) {
511 gtp_error(id, "pachi-evaluate not supported by engine", NULL);
512 } else {
513 gtp_prefix('=', id);
514 floating_t vals[board->flen];
515 engine->evaluate(engine, board, &ti[color], vals, color);
516 for (int i = 0; i < board->flen; i++) {
517 if (!board_coord_in_symmetry(board, board->f[i])
518 || isnan(vals[i]) || vals[i] < 0.001)
519 continue;
520 printf("%s %.3f\n", coord2sstr(board->f[i], board), (double) vals[i]);
522 gtp_flush();
525 } else if (!strcasecmp(cmd, "pachi-result")) {
526 /* More detailed result of the last genmove. */
527 /* For UCT, the output format is: = color move playouts winrate dynkomi */
528 char *reply = NULL;
529 if (engine->result)
530 reply = engine->result(engine, board);
531 if (reply)
532 gtp_reply(id, reply, NULL);
533 else
534 gtp_error(id, "unknown pachi-result command", NULL);
536 } else if (!strcasecmp(cmd, "kgs-chat")) {
537 char *loc;
538 next_tok(loc);
539 char *src;
540 next_tok(src);
541 char *msg;
542 next_tok(msg);
543 char *reply = NULL;
544 if (engine->chat)
545 reply = engine->chat(engine, board, msg);
546 if (reply)
547 gtp_reply(id, reply, NULL);
548 else
549 gtp_error(id, "unknown kgs-chat command", NULL);
551 } else if (!strcasecmp(cmd, "time_left")) {
552 char *arg;
553 next_tok(arg);
554 enum stone color = str2stone(arg);
555 next_tok(arg);
556 int time = atoi(arg);
557 next_tok(arg);
558 int stones = atoi(arg);
559 if (!ti[color].ignore_gtp) {
560 time_left(&ti[color], time, stones);
561 } else {
562 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
565 gtp_reply(id, NULL);
567 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
568 char *time_system;
569 char *arg;
570 if (!strcasecmp(cmd, "kgs-time_settings")) {
571 next_tok(time_system);
572 } else {
573 time_system = "canadian";
576 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
577 if (!strcasecmp(time_system, "none")) {
578 main_time = -1;
579 } else if (!strcasecmp(time_system, "absolute")) {
580 next_tok(arg);
581 main_time = atoi(arg);
582 } else if (!strcasecmp(time_system, "byoyomi")) {
583 next_tok(arg);
584 main_time = atoi(arg);
585 next_tok(arg);
586 byoyomi_time = atoi(arg);
587 next_tok(arg);
588 byoyomi_periods = atoi(arg);
589 } else if (!strcasecmp(time_system, "canadian")) {
590 next_tok(arg);
591 main_time = atoi(arg);
592 next_tok(arg);
593 byoyomi_time = atoi(arg);
594 next_tok(arg);
595 byoyomi_stones = atoi(arg);
598 if (DEBUGL(1))
599 fprintf(stderr, "time_settings %d %d/%d*%d\n",
600 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
601 if (!ti[S_BLACK].ignore_gtp) {
602 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
603 ti[S_WHITE] = ti[S_BLACK];
604 } else {
605 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
608 gtp_reply(id, NULL);
610 } else {
611 gtp_error(id, "unknown command", NULL);
612 return P_UNKNOWN_COMMAND;
614 return P_OK;
616 #undef next_tok