genmove: Always make sure the timer is running
[pachi/ann.git] / gtp.c
blob15de4ef3f0abc57c00623aab445bff7d8514a170
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 "quit\n"
83 "boardsize\n"
84 "clear_board\n"
85 "kgs-game_over\n"
86 "komi\n"
87 "kgs-rules\n"
88 "play\n"
89 "genmove\n"
90 "kgs-genmove_cleanup\n"
91 "set_free_handicap\n"
92 "place_free_handicap\n"
93 "final_status_list\n"
94 "pachi-result\n"
95 "kgs-chat\n"
96 "time_left\n"
97 "time_settings\n"
98 "kgs-time_settings";
101 /* Return true if cmd is a valid gtp command. */
102 bool
103 gtp_is_valid(char *cmd)
105 if (!cmd || !*cmd) return false;
106 char *s = strcasestr(known_commands, cmd);
107 if (!s) return false;
109 int len = strlen(cmd);
110 return s[len] == '\0' || s[len] == '\n';
113 /* XXX: THIS IS TOTALLY INSECURE!!!!
114 * Even basic input checking is missing. */
116 enum parse_code
117 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
119 #define next_tok(to_) \
120 to_ = next; \
121 next = next + strcspn(next, " \t\r\n"); \
122 if (*next) { \
123 *next = 0; next++; \
124 next += strspn(next, " \t\r\n"); \
127 if (strchr(buf, '#'))
128 *strchr(buf, '#') = 0;
130 char *cmd, *next = buf;
131 next_tok(cmd);
133 int id = -1;
134 if (isdigit(*cmd)) {
135 id = atoi(cmd);
136 next_tok(cmd);
139 if (!*cmd)
140 return P_OK;
142 if (!strcasecmp(cmd, "protocol_version")) {
143 gtp_reply(id, "2", NULL);
144 return P_OK;
146 } else if (!strcasecmp(cmd, "name")) {
147 /* KGS hack */
148 gtp_reply(id, "Pachi ", engine->name, NULL);
149 return P_OK;
151 } else if (!strcasecmp(cmd, "echo")) {
152 gtp_reply(id, next, NULL);
153 return P_OK;
155 } else if (!strcasecmp(cmd, "version")) {
156 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
157 return P_OK;
159 } else if (!strcasecmp(cmd, "list_commands")) {
160 gtp_reply(id, known_commands, NULL);
161 return P_OK;
164 if (engine->notify) {
165 char *reply;
166 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
167 if (c == P_NOREPLY) {
168 id = NO_REPLY;
169 } else if (c == P_DONE_OK) {
170 gtp_reply(id, reply, NULL);
171 return P_OK;
172 } else if (c == P_DONE_ERROR) {
173 gtp_error(id, reply, NULL);
174 /* This is an internal error for the engine, but
175 * it is still OK from main's point of view. */
176 return P_OK;
177 } else if (c != P_OK) {
178 return c;
182 if (!strcasecmp(cmd, "quit")) {
183 gtp_reply(id, NULL);
184 exit(0);
186 } else if (!strcasecmp(cmd, "boardsize")) {
187 char *arg;
188 next_tok(arg);
189 int size = atoi(arg);
190 if (size < 1 || size > BOARD_MAX_SIZE) {
191 gtp_error(id, "illegal board size", NULL);
192 return P_OK;
194 board_resize(board, size);
195 gtp_reply(id, NULL);
197 } else if (!strcasecmp(cmd, "clear_board") || !strcasecmp(cmd, "kgs-game_over")) {
198 board_clear(board);
199 if (DEBUGL(1))
200 board_print(board, stderr);
201 if (!strcasecmp(cmd, "kgs-game_over")) {
202 if (DEBUGL(0))
203 fprintf(stderr, "game is over\n");
204 /* Sleep before replying, so that kgs doesn't
205 * start another game immediately. */
206 sleep(GAME_OVER_SLEEP);
208 gtp_reply(id, NULL);
209 return P_ENGINE_RESET;
211 } else if (!strcasecmp(cmd, "komi")) {
212 char *arg;
213 next_tok(arg);
214 sscanf(arg, "%f", &board->komi);
216 if (DEBUGL(1))
217 board_print(board, stderr);
218 gtp_reply(id, NULL);
220 } else if (!strcasecmp(cmd, "kgs-rules")) {
221 char *arg;
222 next_tok(arg);
223 if (!strcasecmp(arg, "japanese")) {
224 board->rules = RULES_JAPANESE;
225 } else if (!strcasecmp(arg, "chinese")) {
226 board->rules = RULES_CHINESE;
227 } else if (!strcasecmp(arg, "aga")) {
228 board->rules = RULES_AGA;
229 } else if (!strcasecmp(arg, "new_zealand")) {
230 board->rules = RULES_NEW_ZEALAND;
231 } else {
232 gtp_error(id, "unknown rules", NULL);
233 return P_OK;
235 gtp_reply(id, NULL);
237 } else if (!strcasecmp(cmd, "play")) {
238 struct move m;
240 char *arg;
241 next_tok(arg);
242 m.color = str2stone(arg);
243 next_tok(arg);
244 coord_t *c = str2coord(arg, board_size(board));
245 m.coord = *c; coord_done(c);
246 char *reply = NULL;
248 if (DEBUGL(1))
249 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
251 // This is where kgs starts the timer, not at genmove!
252 time_start_timer(&ti[stone_other(m.color)]);
254 if (engine->notify_play)
255 reply = engine->notify_play(engine, board, &m);
256 if (board_play(board, &m) < 0) {
257 if (DEBUGL(0)) {
258 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
259 board_print(board, stderr);
261 gtp_error(id, "illegal move", NULL);
262 } else {
263 if (DEBUGL(1))
264 board_print_custom(board, stderr, engine->printhook);
265 gtp_reply(id, reply, NULL);
268 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
269 char *arg;
270 next_tok(arg);
271 enum stone color = str2stone(arg);
272 coord_t *c = NULL;
274 if (!ti[color].len.t.timer_start) {
275 /* First game move. */
276 time_start_timer(&ti[color]);
279 if (board->fbook) {
280 /* We have an fbook, check if we cannot make
281 * a move along it right away. */
282 coord_t cf = board->fbook->moves[board->hash & fbook_hash_mask];
283 if (!is_pass(cf)) {
284 if (DEBUGL(1))
285 fprintf(stderr, "fbook match\n");
286 c = coord_copy(cf);
287 } else {
288 /* No match, also prevent further fbook usage
289 * until the next clear_board. */
290 fbook_done(board->fbook);
291 board->fbook = NULL;
295 if (!c) c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
297 struct move m = { *c, color };
298 if (board_play(board, &m) < 0) {
299 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
300 abort();
302 char *str = coord2str(*c, board);
303 if (DEBUGL(1))
304 fprintf(stderr, "playing move %s\n", str);
305 if (DEBUGL(1)) {
306 board_print_custom(board, stderr, engine->printhook);
308 gtp_reply(id, str, NULL);
309 free(str); coord_done(c);
311 /* Account for spent time. If our GTP peer keeps our clock, this will
312 * be overriden by next time_left GTP command properly. */
313 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
314 * should be absolutely rare situation and we will just spend a little
315 * less time than we could on next few moves.) */
316 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
317 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
319 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
320 char *arg;
321 next_tok(arg);
322 enum stone color = str2stone(arg);
323 void *stats;
324 int stats_size;
326 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
327 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
328 &stats, &stats_size);
329 if (!reply) {
330 gtp_error(id, "genmoves error", NULL);
331 return P_OK;
333 if (DEBUGL(3))
334 fprintf(stderr, "proposing moves %s\n", reply);
335 if (DEBUGL(4))
336 board_print_custom(board, stderr, engine->printhook);
337 gtp_reply(id, reply, NULL);
338 if (stats_size > 0) {
339 double start = time_now();
340 fwrite(stats, 1, stats_size, stdout);
341 fflush(stdout);
342 if (DEBUGVV(2))
343 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
344 stats_size, (time_now() - start)*1000);
347 } else if (!strcasecmp(cmd, "set_free_handicap")) {
348 struct move m;
349 m.color = S_BLACK;
351 char *arg;
352 next_tok(arg);
353 do {
354 coord_t *c = str2coord(arg, board_size(board));
355 m.coord = *c; coord_done(c);
356 if (DEBUGL(1))
357 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
359 if (board_play(board, &m) < 0) {
360 if (DEBUGL(0))
361 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
362 gtp_error(id, "illegal move", NULL);
364 board->handicap++;
365 next_tok(arg);
366 } while (*arg);
367 if (DEBUGL(1))
368 board_print(board, stderr);
369 gtp_reply(id, NULL);
371 /* TODO: Engine should choose free handicap; however, it tends to take
372 * overly long to think it all out, and unless it's clever its
373 * handicap stones won't be of much help. ;-) */
374 } else if (!strcasecmp(cmd, "place_free_handicap")
375 || !strcasecmp(cmd, "fixed_handicap")) {
376 char *arg;
377 next_tok(arg);
378 int stones = atoi(arg);
380 gtp_prefix('=', id);
381 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
382 if (DEBUGL(1))
383 board_print(board, stderr);
384 if (id == NO_REPLY) return P_OK;
385 putchar('\n');
386 gtp_flush();
388 } else if (!strcasecmp(cmd, "final_score")) {
389 struct move_queue q = { .moves = 0 };
390 if (engine->dead_group_list)
391 engine->dead_group_list(engine, board, &q);
392 float score = board_official_score(board, &q);
393 char str[64];
394 if (DEBUGL(1))
395 fprintf(stderr, "counted score %.1f\n", score);
396 if (score == 0) {
397 gtp_reply(id, "0", NULL);
398 } else if (score > 0) {
399 snprintf(str, 64, "W+%.1f", score);
400 gtp_reply(id, str, NULL);
401 } else {
402 snprintf(str, 64, "B+%.1f", -score);
403 gtp_reply(id, str, NULL);
406 /* XXX: This is a huge hack. */
407 } else if (!strcasecmp(cmd, "final_status_list")) {
408 if (id == NO_REPLY) return P_OK;
409 char *arg;
410 next_tok(arg);
411 struct move_queue q = { .moves = 0 };
412 if (engine->dead_group_list)
413 engine->dead_group_list(engine, board, &q);
414 /* else we return empty list - i.e. engine not supporting
415 * this assumes all stones alive at the game end. */
416 if (!strcasecmp(arg, "dead")) {
417 gtp_prefix('=', id);
418 for (unsigned int i = 0; i < q.moves; i++) {
419 foreach_in_group(board, q.move[i]) {
420 printf("%s ", coord2sstr(c, board));
421 } foreach_in_group_end;
422 putchar('\n');
424 if (!q.moves)
425 putchar('\n');
426 gtp_flush();
427 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
428 gtp_prefix('=', id);
429 bool printed_group = false;
430 foreach_point(board) { // foreach_group, effectively
431 group_t g = group_at(board, c);
432 if (!g || g != c) continue;
434 for (unsigned int i = 0; i < q.moves; i++) {
435 if (q.move[i] == g)
436 goto next_group;
438 foreach_in_group(board, g) {
439 printf("%s ", coord2sstr(c, board));
440 } foreach_in_group_end;
441 putchar('\n');
442 printed_group = true;
443 next_group:;
444 } foreach_point_end;
445 if (!printed_group)
446 putchar('\n');
447 gtp_flush();
448 } else {
449 gtp_error(id, "illegal status specifier", NULL);
452 /* Custom commands for handling UCT opening tbook */
453 } else if (!strcasecmp(cmd, "uct_gentbook")) {
454 /* Board must be initialized properly, as if for genmove;
455 * makes sense only as 'uct_gentbook b'. */
456 char *arg;
457 next_tok(arg);
458 enum stone color = str2stone(arg);
459 if (uct_gentbook(engine, board, &ti[color], color))
460 gtp_reply(id, NULL);
461 else
462 gtp_error(id, "error generating tbook", NULL);
464 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
465 char *arg;
466 next_tok(arg);
467 enum stone color = str2stone(arg);
468 uct_dumptbook(engine, board, color);
469 gtp_reply(id, NULL);
471 } else if (!strcasecmp(cmd, "uct_evaluate")) {
472 char *arg;
473 next_tok(arg);
474 enum stone color = str2stone(arg);
476 gtp_prefix('=', id);
477 /* Iterate through the list of all free coordinates
478 * and call uct_evaluate() for each. uct_evaluate()
479 * will throw NAN in case of invalid moves and such. */
480 for (int i = 0; i < board->flen; i++) {
481 float val = uct_evaluate(engine, board, &ti[color], board->f[i], color);
482 if (isnan(val))
483 continue;
484 printf("%s %1.3f\n", coord2sstr(board->f[i], board), (double) val);
486 gtp_flush();
488 } else if (!strcasecmp(cmd, "pachi-result")) {
489 /* More detailed result of the last genmove. */
490 /* For UCT, the output format is: = color move playouts winrate dynkomi */
491 char *reply = NULL;
492 if (engine->result)
493 reply = engine->result(engine, board);
494 if (reply)
495 gtp_reply(id, reply, NULL);
496 else
497 gtp_error(id, "unknown pachi-result command", NULL);
499 } else if (!strcasecmp(cmd, "kgs-chat")) {
500 char *loc;
501 next_tok(loc);
502 char *src;
503 next_tok(src);
504 char *msg;
505 next_tok(msg);
506 char *reply = NULL;
507 if (engine->chat)
508 reply = engine->chat(engine, board, msg);
509 if (reply)
510 gtp_reply(id, reply, NULL);
511 else
512 gtp_error(id, "unknown kgs-chat command", NULL);
514 } else if (!strcasecmp(cmd, "time_left")) {
515 char *arg;
516 next_tok(arg);
517 enum stone color = str2stone(arg);
518 next_tok(arg);
519 int time = atoi(arg);
520 next_tok(arg);
521 int stones = atoi(arg);
522 if (!ti[color].ignore_gtp) {
523 time_left(&ti[color], time, stones);
524 } else {
525 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
528 gtp_reply(id, NULL);
530 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
531 char *time_system;
532 char *arg;
533 if (!strcasecmp(cmd, "kgs-time_settings")) {
534 next_tok(time_system);
535 } else {
536 time_system = "canadian";
539 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
540 if (!strcasecmp(time_system, "none")) {
541 main_time = -1;
542 } else if (!strcasecmp(time_system, "absolute")) {
543 next_tok(arg);
544 main_time = atoi(arg);
545 } else if (!strcasecmp(time_system, "byoyomi")) {
546 next_tok(arg);
547 main_time = atoi(arg);
548 next_tok(arg);
549 byoyomi_time = atoi(arg);
550 next_tok(arg);
551 byoyomi_periods = atoi(arg);
552 } else if (!strcasecmp(time_system, "canadian")) {
553 next_tok(arg);
554 main_time = atoi(arg);
555 next_tok(arg);
556 byoyomi_time = atoi(arg);
557 next_tok(arg);
558 byoyomi_stones = atoi(arg);
561 if (DEBUGL(1))
562 fprintf(stderr, "time_settings %d %d/%d*%d\n",
563 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
564 if (!ti[S_BLACK].ignore_gtp) {
565 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
566 ti[S_WHITE] = ti[S_BLACK];
567 } else {
568 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
571 gtp_reply(id, NULL);
573 } else {
574 gtp_error(id, "unknown command", NULL);
575 return P_UNKNOWN_COMMAND;
577 return P_OK;
579 #undef next_tok