UCT book -> tbook (tree book), added short explanation to HACKING
[pachi/derm.git] / gtp.c
bloba4e8dbaf90007299397ef33eb9df8c035033c323
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 "gtp.h"
15 #include "mq.h"
16 #include "uct/uct.h"
17 #include "version.h"
18 #include "timeinfo.h"
20 #define NO_REPLY (-2)
22 /* Sleep 5 seconds after a game ends to give time to kill the program. */
23 #define GAME_OVER_SLEEP 5
25 void
26 gtp_prefix(char prefix, int id)
28 if (id == NO_REPLY) return;
29 if (id >= 0)
30 printf("%c%d ", prefix, id);
31 else
32 printf("%c ", prefix);
35 void
36 gtp_flush(void)
38 putchar('\n');
39 fflush(stdout);
42 void
43 gtp_output(char prefix, int id, va_list params)
45 if (id == NO_REPLY) return;
46 gtp_prefix(prefix, id);
47 char *s;
48 while ((s = va_arg(params, char *))) {
49 fputs(s, stdout);
51 putchar('\n');
52 gtp_flush();
55 void
56 gtp_reply(int id, ...)
58 va_list params;
59 va_start(params, id);
60 gtp_output('=', id, params);
61 va_end(params);
64 void
65 gtp_error(int id, ...)
67 va_list params;
68 va_start(params, id);
69 gtp_output('?', id, params);
70 va_end(params);
73 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
74 * it should only be used between master and slaves of the distributed engine. */
75 static char *known_commands =
76 "protocol_version\n"
77 "echo\n"
78 "name\n"
79 "version\n"
80 "list_commands\n"
81 "quit\n"
82 "boardsize\n"
83 "clear_board\n"
84 "kgs-game_over\n"
85 "komi\n"
86 "kgs-rules\n"
87 "play\n"
88 "genmove\n"
89 "kgs-genmove_cleanup\n"
90 "set_free_handicap\n"
91 "place_free_handicap\n"
92 "final_status_list\n"
93 "pachi-result\n"
94 "kgs-chat\n"
95 "time_left\n"
96 "time_settings\n"
97 "kgs-time_settings";
100 /* Return true if cmd is a valid gtp command. */
101 bool
102 gtp_is_valid(char *cmd)
104 if (!cmd || !*cmd) return false;
105 char *s = strcasestr(known_commands, cmd);
106 if (!s) return false;
108 int len = strlen(cmd);
109 return s[len] == '\0' || s[len] == '\n';
112 /* XXX: THIS IS TOTALLY INSECURE!!!!
113 * Even basic input checking is missing. */
115 enum parse_code
116 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
118 #define next_tok(to_) \
119 to_ = next; \
120 next = next + strcspn(next, " \t\r\n"); \
121 if (*next) { \
122 *next = 0; next++; \
123 next += strspn(next, " \t\r\n"); \
126 if (strchr(buf, '#'))
127 *strchr(buf, '#') = 0;
129 char *cmd, *next = buf;
130 next_tok(cmd);
132 int id = -1;
133 if (isdigit(*cmd)) {
134 id = atoi(cmd);
135 next_tok(cmd);
138 if (!*cmd)
139 return P_OK;
141 if (!strcasecmp(cmd, "protocol_version")) {
142 gtp_reply(id, "2", NULL);
143 return P_OK;
145 } else if (!strcasecmp(cmd, "name")) {
146 /* KGS hack */
147 gtp_reply(id, "Pachi ", engine->name, NULL);
148 return P_OK;
150 } else if (!strcasecmp(cmd, "echo")) {
151 gtp_reply(id, next, NULL);
152 return P_OK;
154 } else if (!strcasecmp(cmd, "version")) {
155 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
156 return P_OK;
158 } else if (!strcasecmp(cmd, "list_commands")) {
159 gtp_reply(id, known_commands, NULL);
160 return P_OK;
163 if (engine->notify) {
164 char *reply;
165 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
166 if (c == P_NOREPLY) {
167 id = NO_REPLY;
168 } else if (c == P_DONE_OK) {
169 gtp_reply(id, reply, NULL);
170 return P_OK;
171 } else if (c == P_DONE_ERROR) {
172 gtp_error(id, reply, NULL);
173 /* This is an internal error for the engine, but
174 * it is still OK from main's point of view. */
175 return P_OK;
176 } else if (c != P_OK) {
177 return c;
181 if (!strcasecmp(cmd, "quit")) {
182 gtp_reply(id, NULL);
183 exit(0);
185 } else if (!strcasecmp(cmd, "boardsize")) {
186 char *arg;
187 next_tok(arg);
188 int size = atoi(arg);
189 if (size < 1 || size > BOARD_MAX_SIZE) {
190 gtp_error(id, "illegal board size", NULL);
191 return P_OK;
193 board_resize(board, size);
194 gtp_reply(id, NULL);
196 } else if (!strcasecmp(cmd, "clear_board") || !strcasecmp(cmd, "kgs-game_over")) {
197 board_clear(board);
198 if (DEBUGL(1))
199 board_print(board, stderr);
200 if (!strcasecmp(cmd, "kgs-game_over")) {
201 if (DEBUGL(0))
202 fprintf(stderr, "game is over\n");
203 /* Sleep before replying, so that kgs doesn't
204 * start another game immediately. */
205 sleep(GAME_OVER_SLEEP);
207 gtp_reply(id, NULL);
208 return P_ENGINE_RESET;
210 } else if (!strcasecmp(cmd, "komi")) {
211 char *arg;
212 next_tok(arg);
213 sscanf(arg, "%f", &board->komi);
215 if (DEBUGL(1))
216 board_print(board, stderr);
217 gtp_reply(id, NULL);
219 } else if (!strcasecmp(cmd, "kgs-rules")) {
220 char *arg;
221 next_tok(arg);
222 if (!strcasecmp(arg, "japanese")) {
223 board->rules = RULES_JAPANESE;
224 } else if (!strcasecmp(arg, "chinese")) {
225 board->rules = RULES_CHINESE;
226 } else if (!strcasecmp(arg, "aga")) {
227 board->rules = RULES_AGA;
228 } else if (!strcasecmp(arg, "new_zealand")) {
229 board->rules = RULES_NEW_ZEALAND;
230 } else {
231 gtp_error(id, "unknown rules", NULL);
232 return P_OK;
234 gtp_reply(id, NULL);
236 } else if (!strcasecmp(cmd, "play")) {
237 struct move m;
239 char *arg;
240 next_tok(arg);
241 m.color = str2stone(arg);
242 next_tok(arg);
243 coord_t *c = str2coord(arg, board_size(board));
244 m.coord = *c; coord_done(c);
245 char *reply = NULL;
247 if (DEBUGL(1))
248 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
250 // This is where kgs starts the timer, not at genmove!
251 time_start_timer(&ti[stone_other(m.color)]);
253 if (engine->notify_play)
254 reply = engine->notify_play(engine, board, &m);
255 if (board_play(board, &m) < 0) {
256 if (DEBUGL(0)) {
257 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
258 board_print(board, stderr);
260 gtp_error(id, "illegal move", NULL);
261 } else {
262 if (DEBUGL(1))
263 board_print_custom(board, stderr, engine->printhook);
264 gtp_reply(id, reply, NULL);
267 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
268 char *arg;
269 next_tok(arg);
270 enum stone color = str2stone(arg);
272 coord_t *c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
273 struct move m = { *c, color };
274 if (board_play(board, &m) < 0) {
275 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
276 abort();
278 char *str = coord2str(*c, board);
279 if (DEBUGL(1))
280 fprintf(stderr, "playing move %s\n", str);
281 if (DEBUGL(1)) {
282 board_print_custom(board, stderr, engine->printhook);
284 gtp_reply(id, str, NULL);
285 free(str); coord_done(c);
287 /* Account for spent time. If our GTP peer keeps our clock, this will
288 * be overriden by next time_left GTP command properly. */
289 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
290 * should be absolutely rare situation and we will just spend a little
291 * less time than we could on next few moves.) */
292 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
293 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
295 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
296 char *arg;
297 next_tok(arg);
298 enum stone color = str2stone(arg);
299 void *stats;
300 int stats_size;
302 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
303 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
304 &stats, &stats_size);
305 if (!reply) {
306 gtp_error(id, "genmoves error", NULL);
307 return P_OK;
309 if (DEBUGL(3))
310 fprintf(stderr, "proposing moves %s\n", reply);
311 if (DEBUGL(4))
312 board_print_custom(board, stderr, engine->printhook);
313 gtp_reply(id, reply, NULL);
314 if (stats_size > 0) {
315 double start = time_now();
316 fwrite(stats, 1, stats_size, stdout);
317 fflush(stdout);
318 if (DEBUGVV(2))
319 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
320 stats_size, (time_now() - start)*1000);
323 } else if (!strcasecmp(cmd, "set_free_handicap")) {
324 struct move m;
325 m.color = S_BLACK;
327 char *arg;
328 next_tok(arg);
329 do {
330 coord_t *c = str2coord(arg, board_size(board));
331 m.coord = *c; coord_done(c);
332 if (DEBUGL(1))
333 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
335 if (board_play(board, &m) < 0) {
336 if (DEBUGL(0))
337 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
338 gtp_error(id, "illegal move", NULL);
340 board->handicap++;
341 next_tok(arg);
342 } while (*arg);
343 if (DEBUGL(1))
344 board_print(board, stderr);
345 gtp_reply(id, NULL);
347 /* TODO: Engine should choose free handicap; however, it tends to take
348 * overly long to think it all out, and unless it's clever its
349 * handicap stones won't be of much help. ;-) */
350 } else if (!strcasecmp(cmd, "place_free_handicap")
351 || !strcasecmp(cmd, "fixed_handicap")) {
352 char *arg;
353 next_tok(arg);
354 int stones = atoi(arg);
356 gtp_prefix('=', id);
357 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
358 if (DEBUGL(1))
359 board_print(board, stderr);
360 if (id == NO_REPLY) return P_OK;
361 putchar('\n');
362 gtp_flush();
364 } else if (!strcasecmp(cmd, "final_score")) {
365 struct move_queue q = { .moves = 0 };
366 if (engine->dead_group_list)
367 engine->dead_group_list(engine, board, &q);
368 float score = board_official_score(board, &q);
369 char str[64];
370 if (DEBUGL(1))
371 fprintf(stderr, "counted score %.1f\n", score);
372 if (score == 0) {
373 gtp_reply(id, "0", NULL);
374 } else if (score > 0) {
375 snprintf(str, 64, "W+%.1f", score);
376 gtp_reply(id, str, NULL);
377 } else {
378 snprintf(str, 64, "B+%.1f", -score);
379 gtp_reply(id, str, NULL);
382 /* XXX: This is a huge hack. */
383 } else if (!strcasecmp(cmd, "final_status_list")) {
384 if (id == NO_REPLY) return P_OK;
385 char *arg;
386 next_tok(arg);
387 struct move_queue q = { .moves = 0 };
388 if (engine->dead_group_list)
389 engine->dead_group_list(engine, board, &q);
390 /* else we return empty list - i.e. engine not supporting
391 * this assumes all stones alive at the game end. */
392 if (!strcasecmp(arg, "dead")) {
393 gtp_prefix('=', id);
394 for (unsigned int i = 0; i < q.moves; i++) {
395 foreach_in_group(board, q.move[i]) {
396 printf("%s ", coord2sstr(c, board));
397 } foreach_in_group_end;
398 putchar('\n');
400 if (!q.moves)
401 putchar('\n');
402 gtp_flush();
403 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
404 gtp_prefix('=', id);
405 bool printed_group = false;
406 foreach_point(board) { // foreach_group, effectively
407 group_t g = group_at(board, c);
408 if (!g || g != c) continue;
410 for (unsigned int i = 0; i < q.moves; i++) {
411 if (q.move[i] == g)
412 goto next_group;
414 foreach_in_group(board, g) {
415 printf("%s ", coord2sstr(c, board));
416 } foreach_in_group_end;
417 putchar('\n');
418 printed_group = true;
419 next_group:;
420 } foreach_point_end;
421 if (!printed_group)
422 putchar('\n');
423 gtp_flush();
424 } else {
425 gtp_error(id, "illegal status specifier", NULL);
428 /* Custom commands for handling UCT opening tbook */
429 } else if (!strcasecmp(cmd, "uct_gentbook")) {
430 /* Board must be initialized properly, as if for genmove;
431 * makes sense only as 'uct_gentbook b'. */
432 char *arg;
433 next_tok(arg);
434 enum stone color = str2stone(arg);
435 if (uct_gentbook(engine, board, &ti[color], color))
436 gtp_reply(id, NULL);
437 else
438 gtp_error(id, "error generating tbook", NULL);
440 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
441 char *arg;
442 next_tok(arg);
443 enum stone color = str2stone(arg);
444 uct_dumptbook(engine, board, color);
445 gtp_reply(id, NULL);
447 } else if (!strcasecmp(cmd, "uct_evaluate")) {
448 char *arg;
449 next_tok(arg);
450 enum stone color = str2stone(arg);
452 gtp_prefix('=', id);
453 /* Iterate through the list of all free coordinates
454 * and call uct_evaluate() for each. uct_evaluate()
455 * will throw NAN in case of invalid moves and such. */
456 for (int i = 0; i < board->flen; i++) {
457 float val = uct_evaluate(engine, board, &ti[color], board->f[i], color);
458 if (isnan(val))
459 continue;
460 printf("%s %1.3f\n", coord2sstr(board->f[i], board), (double) val);
462 gtp_flush();
464 } else if (!strcasecmp(cmd, "pachi-result")) {
465 /* More detailed result of the last genmove. */
466 /* For UCT, the output format is: = color move playouts winrate dynkomi */
467 char *reply = NULL;
468 if (engine->result)
469 reply = engine->result(engine, board);
470 if (reply)
471 gtp_reply(id, reply, NULL);
472 else
473 gtp_error(id, "unknown pachi-result command", NULL);
475 } else if (!strcasecmp(cmd, "kgs-chat")) {
476 char *loc;
477 next_tok(loc);
478 char *src;
479 next_tok(src);
480 char *msg;
481 next_tok(msg);
482 char *reply = NULL;
483 if (engine->chat)
484 reply = engine->chat(engine, board, msg);
485 if (reply)
486 gtp_reply(id, reply, NULL);
487 else
488 gtp_error(id, "unknown kgs-chat command", NULL);
490 } else if (!strcasecmp(cmd, "time_left")) {
491 char *arg;
492 next_tok(arg);
493 enum stone color = str2stone(arg);
494 next_tok(arg);
495 int time = atoi(arg);
496 next_tok(arg);
497 int stones = atoi(arg);
498 if (!ti[color].ignore_gtp) {
499 time_left(&ti[color], time, stones);
500 } else {
501 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
504 gtp_reply(id, NULL);
506 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
507 char *time_system;
508 char *arg;
509 if (!strcasecmp(cmd, "kgs-time_settings")) {
510 next_tok(time_system);
511 } else {
512 time_system = "canadian";
515 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
516 if (!strcasecmp(time_system, "none")) {
517 main_time = -1;
518 } else if (!strcasecmp(time_system, "absolute")) {
519 next_tok(arg);
520 main_time = atoi(arg);
521 } else if (!strcasecmp(time_system, "byoyomi")) {
522 next_tok(arg);
523 main_time = atoi(arg);
524 next_tok(arg);
525 byoyomi_time = atoi(arg);
526 next_tok(arg);
527 byoyomi_periods = atoi(arg);
528 } else if (!strcasecmp(time_system, "canadian")) {
529 next_tok(arg);
530 main_time = atoi(arg);
531 next_tok(arg);
532 byoyomi_time = atoi(arg);
533 next_tok(arg);
534 byoyomi_stones = atoi(arg);
537 if (DEBUGL(1))
538 fprintf(stderr, "time_settings %d %d/%d*%d\n",
539 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
540 if (!ti[S_BLACK].ignore_gtp) {
541 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
542 ti[S_WHITE] = ti[S_BLACK];
543 } else {
544 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
547 gtp_reply(id, NULL);
549 } else {
550 gtp_error(id, "unknown command", NULL);
551 return P_UNKNOWN_COMMAND;
553 return P_OK;
555 #undef next_tok