Joseki: Remove global jdict instance
[pachi/ann.git] / gtp.c
blob29620c51ee6cc9a1918ca58d28a0b596a2e0f7b9
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
10 #include "board.h"
11 #include "debug.h"
12 #include "engine.h"
13 #include "gtp.h"
14 #include "mq.h"
15 #include "uct/uct.h"
16 #include "version.h"
17 #include "timeinfo.h"
19 #define NO_REPLY (-2)
21 /* Sleep 5 seconds after a game ends to give time to kill the program. */
22 #define GAME_OVER_SLEEP 5
24 void
25 gtp_prefix(char prefix, int id)
27 if (id == NO_REPLY) return;
28 if (id >= 0)
29 printf("%c%d ", prefix, id);
30 else
31 printf("%c ", prefix);
34 void
35 gtp_flush(void)
37 putchar('\n');
38 fflush(stdout);
41 void
42 gtp_output(char prefix, int id, va_list params)
44 if (id == NO_REPLY) return;
45 gtp_prefix(prefix, id);
46 char *s;
47 while ((s = va_arg(params, char *))) {
48 fputs(s, stdout);
50 putchar('\n');
51 gtp_flush();
54 void
55 gtp_reply(int id, ...)
57 va_list params;
58 va_start(params, id);
59 gtp_output('=', id, params);
60 va_end(params);
63 void
64 gtp_error(int id, ...)
66 va_list params;
67 va_start(params, id);
68 gtp_output('?', id, params);
69 va_end(params);
72 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
73 * it should only be used between master and slaves of the distributed engine. */
74 static char *known_commands =
75 "protocol_version\n"
76 "echo\n"
77 "name\n"
78 "version\n"
79 "list_commands\n"
80 "quit\n"
81 "boardsize\n"
82 "clear_board\n"
83 "kgs-game_over\n"
84 "komi\n"
85 "kgs-rules\n"
86 "play\n"
87 "genmove\n"
88 "kgs-genmove_cleanup\n"
89 "set_free_handicap\n"
90 "place_free_handicap\n"
91 "final_status_list\n"
92 "pachi-result\n"
93 "kgs-chat\n"
94 "time_left\n"
95 "time_settings\n"
96 "kgs-time_settings";
99 /* Return true if cmd is a valid gtp command. */
100 bool
101 gtp_is_valid(char *cmd)
103 if (!cmd || !*cmd) return false;
104 char *s = strcasestr(known_commands, cmd);
105 if (!s) return false;
107 int len = strlen(cmd);
108 return s[len] == '\0' || s[len] == '\n';
111 /* XXX: THIS IS TOTALLY INSECURE!!!!
112 * Even basic input checking is missing. */
114 enum parse_code
115 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
117 #define next_tok(to_) \
118 to_ = next; \
119 next = next + strcspn(next, " \t\r\n"); \
120 if (*next) { \
121 *next = 0; next++; \
122 next += strspn(next, " \t\r\n"); \
125 if (strchr(buf, '#'))
126 *strchr(buf, '#') = 0;
128 char *cmd, *next = buf;
129 next_tok(cmd);
131 int id = -1;
132 if (isdigit(*cmd)) {
133 id = atoi(cmd);
134 next_tok(cmd);
137 if (!*cmd)
138 return P_OK;
140 if (!strcasecmp(cmd, "protocol_version")) {
141 gtp_reply(id, "2", NULL);
142 return P_OK;
144 } else if (!strcasecmp(cmd, "name")) {
145 /* KGS hack */
146 gtp_reply(id, "Pachi ", engine->name, NULL);
147 return P_OK;
149 } else if (!strcasecmp(cmd, "echo")) {
150 gtp_reply(id, next, NULL);
151 return P_OK;
153 } else if (!strcasecmp(cmd, "version")) {
154 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
155 return P_OK;
157 } else if (!strcasecmp(cmd, "list_commands")) {
158 gtp_reply(id, known_commands, NULL);
159 return P_OK;
162 if (engine->notify) {
163 char *reply;
164 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
165 if (c == P_NOREPLY) {
166 id = NO_REPLY;
167 } else if (c == P_DONE_OK) {
168 gtp_reply(id, reply, NULL);
169 return P_OK;
170 } else if (c == P_DONE_ERROR) {
171 gtp_error(id, reply, NULL);
172 /* This is an internal error for the engine, but
173 * it is still OK from main's point of view. */
174 return P_OK;
175 } else if (c != P_OK) {
176 return c;
180 if (!strcasecmp(cmd, "quit")) {
181 gtp_reply(id, NULL);
182 exit(0);
184 } else if (!strcasecmp(cmd, "boardsize")) {
185 char *arg;
186 next_tok(arg);
187 int size = atoi(arg);
188 if (size < 1 || size > BOARD_MAX_SIZE) {
189 gtp_error(id, "illegal board size", NULL);
190 return P_OK;
192 board_resize(board, size);
193 gtp_reply(id, NULL);
195 } else if (!strcasecmp(cmd, "clear_board") || !strcasecmp(cmd, "kgs-game_over")) {
196 board_clear(board);
197 if (DEBUGL(1))
198 board_print(board, stderr);
199 if (!strcasecmp(cmd, "kgs-game_over")) {
200 if (DEBUGL(0))
201 fprintf(stderr, "game is over\n");
202 /* Sleep before replying, so that kgs doesn't
203 * start another game immediately. */
204 sleep(GAME_OVER_SLEEP);
206 gtp_reply(id, NULL);
207 return P_ENGINE_RESET;
209 } else if (!strcasecmp(cmd, "komi")) {
210 char *arg;
211 next_tok(arg);
212 sscanf(arg, "%f", &board->komi);
214 if (DEBUGL(1))
215 board_print(board, stderr);
216 gtp_reply(id, NULL);
218 } else if (!strcasecmp(cmd, "kgs-rules")) {
219 char *arg;
220 next_tok(arg);
221 if (!strcasecmp(arg, "japanese")) {
222 board->rules = RULES_JAPANESE;
223 } else if (!strcasecmp(arg, "chinese")) {
224 board->rules = RULES_CHINESE;
225 } else if (!strcasecmp(arg, "aga")) {
226 board->rules = RULES_AGA;
227 } else if (!strcasecmp(arg, "new_zealand")) {
228 board->rules = RULES_NEW_ZEALAND;
229 } else {
230 gtp_error(id, "unknown rules", NULL);
231 return P_OK;
233 gtp_reply(id, NULL);
235 } else if (!strcasecmp(cmd, "play")) {
236 struct move m;
238 char *arg;
239 next_tok(arg);
240 m.color = str2stone(arg);
241 next_tok(arg);
242 coord_t *c = str2coord(arg, board_size(board));
243 m.coord = *c; coord_done(c);
244 char *reply = NULL;
246 if (DEBUGL(1))
247 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
249 // This is where kgs starts the timer, not at genmove!
250 time_start_timer(&ti[stone_other(m.color)]);
252 if (engine->notify_play)
253 reply = engine->notify_play(engine, board, &m);
254 if (board_play(board, &m) < 0) {
255 if (DEBUGL(0)) {
256 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
257 board_print(board, stderr);
259 gtp_error(id, "illegal move", NULL);
260 } else {
261 if (DEBUGL(1))
262 board_print_custom(board, stderr, engine->printhook);
263 gtp_reply(id, reply, NULL);
266 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
267 char *arg;
268 next_tok(arg);
269 enum stone color = str2stone(arg);
271 coord_t *c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
272 struct move m = { *c, color };
273 if (board_play(board, &m) < 0) {
274 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
275 abort();
277 char *str = coord2str(*c, board);
278 if (DEBUGL(1))
279 fprintf(stderr, "playing move %s\n", str);
280 if (DEBUGL(1)) {
281 board_print_custom(board, stderr, engine->printhook);
283 gtp_reply(id, str, NULL);
284 free(str); coord_done(c);
286 /* Account for spent time. If our GTP peer keeps our clock, this will
287 * be overriden by next time_left GTP command properly. */
288 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
289 * should be absolutely rare situation and we will just spend a little
290 * less time than we could on next few moves.) */
291 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
292 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
294 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
295 char *arg;
296 next_tok(arg);
297 enum stone color = str2stone(arg);
298 void *stats;
299 int stats_size;
301 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
302 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
303 &stats, &stats_size);
304 if (!reply) {
305 gtp_error(id, "genmoves error", NULL);
306 return P_OK;
308 if (DEBUGL(3))
309 fprintf(stderr, "proposing moves %s\n", reply);
310 if (DEBUGL(4))
311 board_print_custom(board, stderr, engine->printhook);
312 gtp_reply(id, reply, NULL);
313 if (stats_size > 0) {
314 double start = time_now();
315 fwrite(stats, 1, stats_size, stdout);
316 fflush(stdout);
317 if (DEBUGVV(2))
318 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
319 stats_size, (time_now() - start)*1000);
322 } else if (!strcasecmp(cmd, "set_free_handicap")) {
323 struct move m;
324 m.color = S_BLACK;
326 char *arg;
327 next_tok(arg);
328 do {
329 coord_t *c = str2coord(arg, board_size(board));
330 m.coord = *c; coord_done(c);
331 if (DEBUGL(1))
332 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
334 if (board_play(board, &m) < 0) {
335 if (DEBUGL(0))
336 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
337 gtp_error(id, "illegal move", NULL);
339 board->handicap++;
340 next_tok(arg);
341 } while (*arg);
342 if (DEBUGL(1))
343 board_print(board, stderr);
344 gtp_reply(id, NULL);
346 /* TODO: Engine should choose free handicap; however, it tends to take
347 * overly long to think it all out, and unless it's clever its
348 * handicap stones won't be of much help. ;-) */
349 } else if (!strcasecmp(cmd, "place_free_handicap")
350 || !strcasecmp(cmd, "fixed_handicap")) {
351 char *arg;
352 next_tok(arg);
353 int stones = atoi(arg);
355 gtp_prefix('=', id);
356 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
357 if (DEBUGL(1))
358 board_print(board, stderr);
359 if (id == NO_REPLY) return P_OK;
360 putchar('\n');
361 gtp_flush();
363 } else if (!strcasecmp(cmd, "final_score")) {
364 struct move_queue q = { .moves = 0 };
365 if (engine->dead_group_list)
366 engine->dead_group_list(engine, board, &q);
367 float score = board_official_score(board, &q);
368 char str[64];
369 if (DEBUGL(1))
370 fprintf(stderr, "counted score %.1f\n", score);
371 if (score == 0) {
372 gtp_reply(id, "0", NULL);
373 } else if (score > 0) {
374 snprintf(str, 64, "W+%.1f", score);
375 gtp_reply(id, str, NULL);
376 } else {
377 snprintf(str, 64, "B+%.1f", -score);
378 gtp_reply(id, str, NULL);
381 /* XXX: This is a huge hack. */
382 } else if (!strcasecmp(cmd, "final_status_list")) {
383 if (id == NO_REPLY) return P_OK;
384 char *arg;
385 next_tok(arg);
386 struct move_queue q = { .moves = 0 };
387 if (engine->dead_group_list)
388 engine->dead_group_list(engine, board, &q);
389 /* else we return empty list - i.e. engine not supporting
390 * this assumes all stones alive at the game end. */
391 if (!strcasecmp(arg, "dead")) {
392 gtp_prefix('=', id);
393 for (unsigned int i = 0; i < q.moves; i++) {
394 foreach_in_group(board, q.move[i]) {
395 printf("%s ", coord2sstr(c, board));
396 } foreach_in_group_end;
397 putchar('\n');
399 if (!q.moves)
400 putchar('\n');
401 gtp_flush();
402 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
403 gtp_prefix('=', id);
404 bool printed_group = false;
405 foreach_point(board) { // foreach_group, effectively
406 group_t g = group_at(board, c);
407 if (!g || g != c) continue;
409 for (unsigned int i = 0; i < q.moves; i++) {
410 if (q.move[i] == g)
411 goto next_group;
413 foreach_in_group(board, g) {
414 printf("%s ", coord2sstr(c, board));
415 } foreach_in_group_end;
416 putchar('\n');
417 printed_group = true;
418 next_group:;
419 } foreach_point_end;
420 if (!printed_group)
421 putchar('\n');
422 gtp_flush();
423 } else {
424 gtp_error(id, "illegal status specifier", NULL);
427 /* Custom commands for handling UCT opening book */
428 } else if (!strcasecmp(cmd, "uct_genbook")) {
429 /* Board must be initialized properly, as if for genmove;
430 * makes sense only as 'uct_genbook b'. */
431 char *arg;
432 next_tok(arg);
433 enum stone color = str2stone(arg);
434 if (uct_genbook(engine, board, &ti[color], color))
435 gtp_reply(id, NULL);
436 else
437 gtp_error(id, "error generating book", NULL);
439 } else if (!strcasecmp(cmd, "uct_dumpbook")) {
440 char *arg;
441 next_tok(arg);
442 enum stone color = str2stone(arg);
443 uct_dumpbook(engine, board, color);
444 gtp_reply(id, NULL);
446 } else if (!strcasecmp(cmd, "pachi-result")) {
447 /* More detailed result of the last genmove. */
448 /* For UCT, the output format is: = color move playouts winrate dynkomi */
449 char *reply = NULL;
450 if (engine->result)
451 reply = engine->result(engine, board);
452 if (reply)
453 gtp_reply(id, reply, NULL);
454 else
455 gtp_error(id, "unknown pachi-result command", NULL);
457 } else if (!strcasecmp(cmd, "kgs-chat")) {
458 char *loc;
459 next_tok(loc);
460 char *src;
461 next_tok(src);
462 char *msg;
463 next_tok(msg);
464 char *reply = NULL;
465 if (engine->chat)
466 reply = engine->chat(engine, board, msg);
467 if (reply)
468 gtp_reply(id, reply, NULL);
469 else
470 gtp_error(id, "unknown kgs-chat command", NULL);
472 } else if (!strcasecmp(cmd, "time_left")) {
473 char *arg;
474 next_tok(arg);
475 enum stone color = str2stone(arg);
476 next_tok(arg);
477 int time = atoi(arg);
478 next_tok(arg);
479 int stones = atoi(arg);
480 if (!ti[color].ignore_gtp) {
481 time_left(&ti[color], time, stones);
482 } else {
483 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
486 gtp_reply(id, NULL);
488 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
489 char *time_system;
490 char *arg;
491 if (!strcasecmp(cmd, "kgs-time_settings")) {
492 next_tok(time_system);
493 } else {
494 time_system = "canadian";
497 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
498 if (!strcasecmp(time_system, "none")) {
499 main_time = -1;
500 } else if (!strcasecmp(time_system, "absolute")) {
501 next_tok(arg);
502 main_time = atoi(arg);
503 } else if (!strcasecmp(time_system, "byoyomi")) {
504 next_tok(arg);
505 main_time = atoi(arg);
506 next_tok(arg);
507 byoyomi_time = atoi(arg);
508 next_tok(arg);
509 byoyomi_periods = atoi(arg);
510 } else if (!strcasecmp(time_system, "canadian")) {
511 next_tok(arg);
512 main_time = atoi(arg);
513 next_tok(arg);
514 byoyomi_time = atoi(arg);
515 next_tok(arg);
516 byoyomi_stones = atoi(arg);
519 if (DEBUGL(1))
520 fprintf(stderr, "time_settings %d %d/%d*%d\n",
521 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
522 if (!ti[S_BLACK].ignore_gtp) {
523 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
524 ti[S_WHITE] = ti[S_BLACK];
525 } else {
526 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
529 gtp_reply(id, NULL);
531 } else {
532 gtp_error(id, "unknown command", NULL);
533 return P_UNKNOWN_COMMAND;
535 return P_OK;
537 #undef next_tok