4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 # analysis, or for live analysis of relayed games. (Do not use for
6 # cheating! Cheating is bad for your karma, and your abuser flag.)
8 # Copyright 2007 Steinar H. Gunderson <steinar+remoteglot@gunderson.no>
9 # Licensed under the GNU General Public License, version 2.
15 use Chess::PGN::Parse;
25 require 'Position.pm';
33 my $latest_update = undef;
34 my $output_timer = undef;
35 my $http_timer = undef;
36 my $stop_pgn_fetch = 0;
37 my $tb_retry_timer = undef;
39 my $tb_lookup_running = 0;
40 my $last_written_json = undef;
42 # Persisted so we can restart.
43 # TODO: Figure out an appropriate way to deal with database restarts
44 # and/or Postgres going away entirely.
45 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
47 $dbh->{RaiseError} = 1;
51 open(FICSLOG, ">ficslog.txt")
52 or die "ficslog.txt: $!";
53 print FICSLOG "Log starting.\n";
57 open(UCILOG, ">ucilog.txt")
58 or die "ucilog.txt: $!";
59 print UCILOG "Log starting.\n";
63 open(TBLOG, ">tblog.txt")
64 or die "tblog.txt: $!";
65 print TBLOG "Log starting.\n";
72 # open the chess engine
73 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
74 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
77 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
79 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81 uciprint($engine, "setoption name $key value $value");
83 uciprint($engine, "ucinewgame");
85 if (defined($engine2)) {
86 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88 uciprint($engine2, "setoption name $key value $value");
90 uciprint($engine2, "setoption name MultiPV value 500");
91 uciprint($engine2, "ucinewgame");
94 print "Chess engine ready.\n";
97 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
109 my $ev1 = AnyEvent->io(
112 cb => sub { # what callback to execute
114 my $line = $t->getline(Timeout => 0, errmode => 'return');
115 return if (!defined($line));
123 if (defined($remoteglotconf::target)) {
124 if ($remoteglotconf::target =~ /^http:/) {
125 fetch_pgn($remoteglotconf::target);
127 $t->cmd("observe $remoteglotconf::target");
130 print "FICS ready.\n";
132 # Engine events have already been set up by Engine.pm.
136 my ($engine, $line, $primary) = @_;
138 return if $line =~ /(upper|lower)bound/;
140 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
141 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142 if ($line =~ /^info/) {
143 my (@infos) = split / /, $line;
146 parse_infos($engine, @infos);
148 if ($line =~ /^id/) {
149 my (@ids) = split / /, $line;
152 parse_ids($engine, @ids);
154 if ($line =~ /^bestmove/) {
156 return if (!$remoteglotconf::uci_assume_full_compliance);
157 if (defined($pos_waiting)) {
158 uciprint($engine, "position fen " . $pos_waiting->fen());
159 uciprint($engine, "go infinite");
161 $pos_calculating = $pos_waiting;
162 $pos_waiting = undef;
165 $engine2->{'info'} = {};
166 my $pos = $pos_waiting // $pos_calculating;
167 uciprint($engine2, "position fen " . $pos->fen());
168 uciprint($engine2, "go infinite");
169 $pos_calculating_second_engine = $pos;
175 my $getting_movelist = 0;
176 my $pos_for_movelist = undef;
177 my @uci_movelist = ();
178 my @pretty_movelist = ();
182 if ($line =~ /^<12> /) {
183 handle_position(Position->new($line));
186 if ($line =~ /^Movelist for game /) {
187 my $pos = $pos_waiting // $pos_calculating;
190 @pretty_movelist = ();
191 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
192 $getting_movelist = 1;
195 if ($getting_movelist &&
196 $line =~ /^\s* \d+\. \s+ # move number
197 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
198 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
202 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
203 push @uci_movelist, $uci_move;
204 push @pretty_movelist, $1;
207 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
208 push @uci_movelist, $uci_move;
209 push @pretty_movelist, $2;
213 warn "Error when getting FICS move history: $@";
214 $getting_movelist = 0;
217 if ($getting_movelist &&
218 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
220 for my $pos ($pos_waiting, $pos_calculating) {
221 next if (!defined($pos));
222 if ($pos->fen() eq $pos_for_movelist->fen()) {
223 $pos->{'pretty_history'} = \@pretty_movelist;
226 $getting_movelist = 0;
228 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
229 my ($who, $msg) = ($1, $2);
231 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
233 if ($msg =~ /^fics (.*?)$/) {
234 $t->cmd("tell $who Executing '$1' on FICS.");
236 } elsif ($msg =~ /^uci (.*?)$/) {
237 $t->cmd("tell $who Sending '$1' to the engine.");
238 print { $engine->{'write'} } "$1\n";
239 } elsif ($msg =~ /^pgn (.*?)$/) {
241 $t->cmd("tell $who Starting to poll '$url'.");
243 } elsif ($msg =~ /^stoppgn$/) {
244 $t->cmd("tell $who Stopping poll.");
247 } elsif ($msg =~ /^quit$/) {
248 $t->cmd("tell $who Bye bye.");
251 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
254 #print "FICS: [$line]\n";
257 # Starts periodic fetching of PGNs from the given URL.
260 AnyEvent::HTTP::http_get($url, sub {
261 handle_pgn(@_, $url);
265 my ($last_pgn_white, $last_pgn_black);
266 my @last_pgn_uci_moves = ();
267 my $pgn_hysteresis_counter = 0;
270 my ($body, $header, $url) = @_;
272 if ($stop_pgn_fetch) {
278 my $pgn = Chess::PGN::Parse->new(undef, $body);
279 if (!defined($pgn)) {
280 warn "Error in parsing PGN from $url [body='$body']\n";
281 } elsif (!$pgn->read_game()) {
282 warn "Error in reading PGN game from $url [body='$body']\n";
283 } elsif ($body !~ /^\[/) {
284 warn "Malformed PGN from $url [body='$body']\n";
287 # Skip to the right game.
288 while (defined($remoteglotconf::pgn_filter) &&
289 !&$remoteglotconf::pgn_filter($pgn)) {
290 $pgn->read_game() or die "Out of games during filtering";
293 $pgn->parse_game({ save_comments => 'yes' });
294 my $white = $pgn->white;
295 my $black = $pgn->black;
296 $white =~ s/,.*//; # Remove first name.
297 $black =~ s/,.*//; # Remove first name.
298 my $pos = Position->start_pos($white, $black);
299 my $moves = $pgn->moves;
301 my @repretty_moves = ();
302 for my $move (@$moves) {
303 my ($npos, $uci_move) = $pos->make_pretty_move($move);
304 push @uci_moves, $uci_move;
306 # Re-prettyprint the move.
307 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
308 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
309 push @repretty_moves, $pretty;
312 $pos->{'result'} = $pgn->result;
313 $pos->{'pretty_history'} = \@repretty_moves;
315 extract_clock($pgn, $pos);
317 # Sometimes, PGNs lose a move or two for a short while,
318 # or people push out new ones non-atomically.
319 # Thus, if we PGN doesn't change names but becomes
320 # shorter, we mistrust it for a few seconds.
322 if (defined($last_pgn_white) && defined($last_pgn_black) &&
323 $last_pgn_white eq $pgn->white &&
324 $last_pgn_black eq $pgn->black &&
325 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
326 if (++$pgn_hysteresis_counter < 3) {
331 $last_pgn_white = $pgn->white;
332 $last_pgn_black = $pgn->black;
333 @last_pgn_uci_moves = @uci_moves;
334 $pgn_hysteresis_counter = 0;
335 handle_position($pos);
339 warn "Error in parsing moves from $url: $@\n";
343 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
348 sub handle_position {
350 find_clock_start($pos, $pos_calculating);
352 # if this is already in the queue, ignore it (just update the result)
353 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
354 $pos_waiting->{'result'} = $pos->{'result'};
358 # if we're already chewing on this and there's nothing else in the queue,
360 if (!defined($pos_waiting) && defined($pos_calculating) &&
361 $pos->fen() eq $pos_calculating->fen()) {
362 $pos_calculating->{'result'} = $pos->{'result'};
366 # if we're already thinking on something, stop and wait for the engine
368 if (defined($pos_calculating)) {
369 # Store the final data we have for this position in the history,
370 # with the precise clock information we just got from the new
371 # position. (Historic positions store the clock at the end of
374 # Do not output anything new to the main analysis; that's
375 # going to be obsolete really soon.
376 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
377 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
378 delete $pos_calculating->{'white_clock_target'};
379 delete $pos_calculating->{'black_clock_target'};
382 if (!defined($pos_waiting)) {
383 uciprint($engine, "stop");
385 if ($remoteglotconf::uci_assume_full_compliance) {
388 uciprint($engine, "position fen " . $pos->fen());
389 uciprint($engine, "go infinite");
390 $pos_calculating = $pos;
393 # it's wrong just to give the FEN (the move history is useful,
394 # and per the UCI spec, we should really have sent "ucinewgame"),
396 uciprint($engine, "position fen " . $pos->fen());
397 uciprint($engine, "go infinite");
398 $pos_calculating = $pos;
401 if (defined($engine2)) {
402 if (defined($pos_calculating_second_engine)) {
403 uciprint($engine2, "stop");
405 uciprint($engine2, "position fen " . $pos->fen());
406 uciprint($engine2, "go infinite");
407 $pos_calculating_second_engine = $pos;
409 $engine2->{'info'} = {};
412 $engine->{'info'} = {};
415 schedule_tb_lookup();
418 # Output a command every move to note that we're
419 # still paying attention -- this is a good tradeoff,
420 # since if no move has happened in the last half
421 # hour, the analysis/relay has most likely stopped
422 # and we should stop hogging server resources.
428 my ($engine, @x) = @_;
431 my $info = $engine->{'info'};
433 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
434 for my $i (0..$#x - 1) {
435 if ($x[$i] eq 'multipv') {
441 while (scalar @x > 0) {
442 if ($x[0] eq 'multipv') {
448 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
450 my $value = shift @x;
451 $info->{$key} = $value;
454 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
455 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
458 my $value = shift @x;
459 $info->{$key . $mpv} = $value;
462 if ($x[0] eq 'score') {
465 delete $info->{'score_cp' . $mpv};
466 delete $info->{'score_mate' . $mpv};
468 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
471 $info->{'score_cp' . $mpv} = shift @x;
472 } elsif ($x[0] eq 'mate') {
474 $info->{'score_mate' . $mpv} = shift @x;
482 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
485 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
489 #print "unknown info '$x[0]', trying to recover...\n";
491 die "Unknown info '" . join(',', @x) . "'";
497 my ($engine, @x) = @_;
499 while (scalar @x > 0) {
500 if ($x[0] eq 'name') {
501 my $value = join(' ', @x);
502 $engine->{'id'}{'author'} = $value;
511 sub prettyprint_pv_no_cache {
512 my ($board, @pvs) = @_;
514 if (scalar @pvs == 0 || !defined($pvs[0])) {
519 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
520 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
521 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
525 my ($pos, @pvs) = @_;
527 my $cachekey = join('', @pvs);
528 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
529 return @{$pos->{'prettyprint_cache'}{$cachekey}};
531 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
532 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
537 sub complete_using_tbprobe {
538 my ($pos, $info, $mpv) = @_;
540 # We need Fathom installed to do standalone TB probes.
541 return if (!defined($remoteglotconf::fathom_cmdline));
543 # If we already have a mate, don't bother; in some cases, it would even be
544 # better than a tablebase score.
545 return if defined($info->{'score_mate' . $mpv});
547 # If we have a draw or near-draw score, there's also not much interesting
548 # we could add from a tablebase. We only really want mates.
549 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
551 # Run through the PV until we are at a 6-man position.
552 # TODO: We could in theory only have 5-man data.
553 my @pv = @{$info->{'pv' . $mpv}};
554 my $key = join('', @pv);
556 if (exists($pos->{'tbprobe_cache'}{$key})) {
557 @moves = $pos->{'tbprobe_cache'}{$key};
559 while ($pos->num_pieces() > 6 && $#pv > -1) {
560 my $move = shift @pv;
562 $pos = $pos->make_move(parse_uci_move($move));
565 return if ($pos->num_pieces() > 6);
567 my $fen = $pos->fen();
568 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
569 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
570 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
571 $pgn->quick_parse_game;
572 $info->{'pv' . $mpv} = \@moves;
574 # Splice the PV from the tablebase onto what we have so far.
575 for my $move (@{$pgn->moves}) {
577 ($pos, $uci_move) = $pos->make_pretty_move($move);
578 push @moves, $uci_move;
582 $info->{'pv' . $mpv} = \@moves;
584 my $matelen = int((1 + scalar @moves) / 2);
585 if ((scalar @moves) % 2 == 0) {
586 $info->{'score_mate' . $mpv} = -$matelen;
588 $info->{'score_mate' . $mpv} = $matelen;
595 return if (!defined($pos_calculating));
597 # Don't update too often.
598 my $age = Time::HiRes::tv_interval($latest_update);
599 if ($age < $remoteglotconf::update_max_interval) {
600 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
601 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
605 my $info = $engine->{'info'};
608 # If we have tablebase data from a previous lookup, replace the
609 # engine data with the data from the tablebase.
611 my $fen = $pos_calculating->fen();
612 if (exists($tb_cache{$fen})) {
613 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
614 delete $info->{$key . '1'};
615 delete $info->{$key};
617 $info->{'nodes'} = 0;
619 $info->{'depth'} = 0;
620 $info->{'seldepth'} = 0;
621 $info->{'tbhits'} = 0;
623 my $t = $tb_cache{$fen};
625 my $matelen = int((1 + $t->{'score'}) / 2);
626 if ($t->{'result'} eq '1/2-1/2') {
627 $info->{'score_cp'} = 0;
628 } elsif ($t->{'result'} eq '1-0') {
629 if ($pos_calculating->{'toplay'} eq 'B') {
630 $info->{'score_mate'} = -$matelen;
632 $info->{'score_mate'} = $matelen;
635 if ($pos_calculating->{'toplay'} eq 'B') {
636 $info->{'score_mate'} = $matelen;
638 $info->{'score_mate'} = -$matelen;
642 $info->{'tablebase'} = 1;
644 $info->{'tablebase'} = 0;
648 # Some programs _always_ report MultiPV, even with only one PV.
649 # In this case, we simply use that data as if MultiPV was never
652 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
653 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
654 if (exists($info->{$key . '1'})) {
655 $info->{$key} = $info->{$key . '1'};
657 delete $info->{$key};
663 # Check the PVs first. if they're invalid, just wait, as our data
664 # is most likely out of sync. This isn't a very good solution, as
665 # it can frequently miss stuff, but it's good enough for most users.
669 if (exists($info->{'pv'})) {
670 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
674 while (exists($info->{'pv' . $mpv})) {
675 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
680 $engine->{'info'} = {};
684 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
685 if (exists($info->{'pv'})) {
686 complete_using_tbprobe($pos_calculating, $info, '');
690 while (exists($info->{'pv' . $mpv})) {
691 complete_using_tbprobe($pos_calculating, $info, $mpv);
697 $latest_update = [Time::HiRes::gettimeofday];
701 my $info = $engine->{'info'};
702 my $id = $engine->{'id'};
704 my $text = 'Analysis';
705 if ($pos_calculating->{'last_move'} ne 'none') {
706 if ($pos_calculating->{'toplay'} eq 'W') {
707 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
709 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
711 if (exists($id->{'name'})) {
716 if (exists($id->{'name'})) {
717 $text .= " by $id->{'name'}:\n\n";
722 return unless (exists($pos_calculating->{'board'}));
724 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
727 while (exists($info->{'pv' . $mpv})) {
728 $text .= sprintf " PV%2u", $mpv;
729 my $score = short_score($info, $pos_calculating, $mpv);
730 $text .= " ($score)" if (defined($score));
733 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
734 if ($info->{'tbhits' . $mpv} == 1) {
735 $tbhits = ", 1 tbhit";
737 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
741 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
742 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
743 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
747 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
753 my $score = long_score($info, $pos_calculating, '');
754 $text .= " $score\n" if defined($score);
755 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
758 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
759 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
760 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
762 if (exists($info->{'seldepth'})) {
763 $text .= sprintf " (%u selective)", $info->{'seldepth'};
765 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
766 if ($info->{'tbhits'} == 1) {
767 $text .= ", one Syzygy hit";
769 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
775 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
777 my @refutation_lines = ();
778 if (defined($engine2)) {
779 for (my $mpv = 1; $mpv < 500; ++$mpv) {
780 my $info = $engine2->{'info'};
781 last if (!exists($info->{'pv' . $mpv}));
783 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
784 my $pv = $info->{'pv' . $mpv};
785 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
786 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
787 if (scalar @pretty_pv > 5) {
788 @pretty_pv = @pretty_pv[0..4];
789 push @pretty_pv, "...";
791 my $key = $pretty_move;
792 my $line = sprintf(" %-6s %6s %3s %s",
794 short_score($info, $pos_calculating_second_engine, $mpv),
795 "d" . $info->{'depth' . $mpv},
796 join(', ', @pretty_pv));
797 push @refutation_lines, [ $key, $line ];
802 if ($#refutation_lines >= 0) {
803 $text .= "Shallow search of all legal moves:\n\n";
804 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
805 $text .= $line->[1] . "\n";
810 if ($last_text ne $text) {
811 print "
\e[H
\e[2J"; # clear the screen
818 my $historic_json_only = shift;
819 my $info = $engine->{'info'};
822 $json->{'position'} = $pos_calculating->to_json_hash();
823 $json->{'engine'} = $engine->{'id'};
824 if (defined($remoteglotconf::engine_url)) {
825 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
827 if (defined($remoteglotconf::engine_details)) {
828 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
830 if (defined($remoteglotconf::move_source)) {
831 $json->{'move_source'} = $remoteglotconf::move_source;
833 if (defined($remoteglotconf::move_source_url)) {
834 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
836 $json->{'score'} = score_digest($info, $pos_calculating, '');
837 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
839 $json->{'nodes'} = $info->{'nodes'};
840 $json->{'nps'} = $info->{'nps'};
841 $json->{'depth'} = $info->{'depth'};
842 $json->{'tbhits'} = $info->{'tbhits'};
843 $json->{'seldepth'} = $info->{'seldepth'};
844 $json->{'tablebase'} = $info->{'tablebase'};
846 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
847 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
849 my %refutation_lines = ();
850 my @refutation_lines = ();
851 if (defined($engine2)) {
852 for (my $mpv = 1; $mpv < 500; ++$mpv) {
853 my $info = $engine2->{'info'};
854 my $pretty_move = "";
856 last if (!exists($info->{'pv' . $mpv}));
859 complete_using_tbprobe($pos_calculating, $info, $mpv);
860 my $pv = $info->{'pv' . $mpv};
861 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
862 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
863 $refutation_lines{$pv->[0]} = {
864 sort_key => $pretty_move,
865 depth => $info->{'depth' . $mpv},
866 score => score_digest($info, $pos_calculating, $mpv),
867 pretty_move => $pretty_move,
868 pv_pretty => \@pretty_pv,
873 $json->{'refutation_lines'} = \%refutation_lines;
875 # Piece together historic score information, to the degree we have it.
876 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
877 my %score_history = ();
879 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
880 my $pos = Position->start_pos('white', 'black');
881 my $halfmove_num = 0;
882 for my $move (@{$pos_calculating->{'pretty_history'}}) {
883 my $id = id_for_pos($pos, $halfmove_num);
884 my $ref = $dbh->selectrow_hashref($q, undef, $id);
886 $score_history{$halfmove_num} = [
887 $ref->{'score_type'},
888 $ref->{'score_value'}
892 ($pos) = $pos->make_pretty_move($move);
896 # If at any point we are missing 10 consecutive moves,
897 # truncate the history there. This is so we don't get into
898 # a situation where we e.g. start analyzing at move 45,
899 # but we have analysis for 1. e4 from some completely different game
900 # and thus show a huge hole.
901 my $consecutive_missing = 0;
902 my $truncate_until = 0;
903 for (my $i = $halfmove_num; $i --> 0; ) {
904 if ($consecutive_missing >= 10) {
905 delete $score_history{$i};
908 if (exists($score_history{$i})) {
909 $consecutive_missing = 0;
911 ++$consecutive_missing;
915 $json->{'score_history'} = \%score_history;
918 # Give out a list of other games going on. (Empty is fine.)
919 if (!$historic_json_only) {
922 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
924 while (my $ref = $q->fetchrow_hashref) {
926 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
927 my $other_game_json = JSON::XS::decode_json($other_game_contents);
929 die "Missing position" if (!exists($other_game_json->{'position'}));
930 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
931 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
935 name => "$white–$black",
936 url => $ref->{'url'},
937 hashurl => $ref->{'hash_url'},
941 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
945 if (scalar @games > 0) {
946 $json->{'games'} = \@games;
950 my $json_enc = JSON::XS->new;
951 $json_enc->canonical(1);
952 my $encoded = $json_enc->encode($json);
953 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
954 (defined($last_written_json) && $last_written_json eq $encoded)) {
955 atomic_set_contents($remoteglotconf::json_output, $encoded);
956 $last_written_json = $encoded;
959 if (exists($pos_calculating->{'pretty_history'}) &&
960 defined($remoteglotconf::json_history_dir)) {
961 my $id = id_for_pos($pos_calculating);
962 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
964 # Overwrite old analysis (assuming it exists at all) if we're
965 # using a different engine, or if we've calculated deeper.
966 # nodes is used as a tiebreaker. Don't bother about Multi-PV
967 # data; it's not that important.
968 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
969 my $new_depth = $json->{'depth'} // 0;
970 my $new_nodes = $json->{'nodes'} // 0;
971 if (!defined($old_engine) ||
972 $old_engine ne $json->{'engine'}{'name'} ||
973 $new_depth > $old_depth ||
974 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
975 atomic_set_contents($filename, $encoded);
976 if (defined($json->{'score'})) {
977 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
978 ' ON CONFLICT (id) DO UPDATE SET ' .
979 ' score_type=EXCLUDED.score_type, ' .
980 ' score_value=EXCLUDED.score_value, ' .
981 ' engine=EXCLUDED.engine, ' .
982 ' depth=EXCLUDED.depth, ' .
983 ' nodes=EXCLUDED.nodes',
985 $id, $json->{'score'}[0], $json->{'score'}[1],
986 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
992 sub atomic_set_contents {
993 my ($filename, $contents) = @_;
995 open my $fh, ">", $filename . ".tmp"
999 rename($filename . ".tmp", $filename);
1003 my ($pos, $halfmove_num) = @_;
1005 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
1006 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1007 return "move$halfmove_num-$fen";
1010 sub get_json_analysis_stats {
1012 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1013 if (defined($ref)) {
1014 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1021 my ($engine, $msg) = @_;
1022 $engine->print($msg);
1023 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1027 my ($info, $pos, $mpv) = @_;
1029 my $invert = ($pos->{'toplay'} eq 'B');
1030 if (defined($info->{'score_mate' . $mpv})) {
1032 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1034 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1037 if (exists($info->{'score_cp' . $mpv})) {
1038 my $score = $info->{'score_cp' . $mpv} * 0.01;
1040 if ($info->{'tablebase'}) {
1049 return sprintf "%+5.2f", $score;
1056 # Sufficient for computing long_score, short_score, plot_score and
1057 # (with side-to-play information) score_sort_key.
1059 my ($info, $pos, $mpv) = @_;
1061 if (defined($info->{'score_mate' . $mpv})) {
1062 my $mate = $info->{'score_mate' . $mpv};
1063 if ($pos->{'toplay'} eq 'B') {
1066 return ['m', $mate];
1068 if (exists($info->{'score_cp' . $mpv})) {
1069 my $score = $info->{'score_cp' . $mpv};
1070 if ($pos->{'toplay'} eq 'B') {
1073 if ($score == 0 && $info->{'tablebase'}) {
1074 return ['d', undef];
1076 return ['cp', $score];
1085 my ($info, $pos, $mpv) = @_;
1087 if (defined($info->{'score_mate' . $mpv})) {
1088 my $mate = $info->{'score_mate' . $mpv};
1089 if ($pos->{'toplay'} eq 'B') {
1093 return sprintf "White mates in %u", $mate;
1095 return sprintf "Black mates in %u", -$mate;
1098 if (exists($info->{'score_cp' . $mpv})) {
1099 my $score = $info->{'score_cp' . $mpv} * 0.01;
1101 if ($info->{'tablebase'}) {
1102 return "Theoretical draw";
1104 return "Score: 0.00";
1107 if ($pos->{'toplay'} eq 'B') {
1110 return sprintf "Score: %+5.2f", $score;
1117 # For graphs; a single number in centipawns, capped at +/- 500.
1119 my ($info, $pos, $mpv) = @_;
1121 my $invert = ($pos->{'toplay'} eq 'B');
1122 if (defined($info->{'score_mate' . $mpv})) {
1123 my $mate = $info->{'score_mate' . $mpv};
1133 if (exists($info->{'score_cp' . $mpv})) {
1134 my $score = $info->{'score_cp' . $mpv};
1138 $score = 500 if ($score > 500);
1139 $score = -500 if ($score < -500);
1147 my %book_cache = ();
1149 my ($fen, $board, $toplay) = @_;
1151 if (exists($book_cache{$fen})) {
1152 return $book_cache{$fen};
1155 my $ret = `./booklook $fen`;
1156 return "" if ($ret =~ /Not found/ || $ret eq '');
1160 for my $m (split /\n/, $ret) {
1161 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1165 $pmove = '(current)';
1167 ($pmove) = prettyprint_pv_no_cache($board, $move);
1168 $pmove .= $annotation;
1172 if ($toplay eq 'W') {
1173 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1175 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1177 my $n = $win + $draw + $lose;
1183 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1186 push @moves, [ $pmove, $n, $percent, $rating ];
1189 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1191 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1192 for my $m (@moves) {
1193 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1200 my ($pgn, $pos) = @_;
1202 # Look for extended PGN clock tags.
1203 my $tags = $pgn->tags;
1204 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1205 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1206 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1210 # Look for TCEC-style time comments.
1211 my $moves = $pgn->moves;
1212 my $comments = $pgn->comments;
1213 my $last_black_move = int((scalar @$moves) / 2);
1214 my $last_white_move = int((1 + scalar @$moves) / 2);
1216 my $black_key = $last_black_move . "b";
1217 my $white_key = $last_white_move . "w";
1219 if (exists($comments->{$white_key}) &&
1220 exists($comments->{$black_key}) &&
1221 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1222 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1223 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1224 $pos->{'white_clock'} = hms_to_sec($1);
1225 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1226 $pos->{'black_clock'} = hms_to_sec($1);
1230 delete $pos->{'white_clock'};
1231 delete $pos->{'black_clock'};
1236 return undef if (!defined($hms));
1237 $hms =~ /(\d+):(\d+):(\d+)/;
1238 return $1 * 3600 + $2 * 60 + $3;
1241 sub find_clock_start {
1242 my ($pos, $prev_pos) = @_;
1244 # If the game is over, the clock is stopped.
1245 if (exists($pos->{'result'}) &&
1246 ($pos->{'result'} eq '1-0' ||
1247 $pos->{'result'} eq '1/2-1/2' ||
1248 $pos->{'result'} eq '0-1')) {
1252 # When we don't have any moves, we assume the clock hasn't started yet.
1253 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1254 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1255 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1260 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1261 # The history is needed for id_for_pos.
1262 if (!exists($pos->{'pretty_history'})) {
1266 my $id = id_for_pos($pos);
1267 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1268 if (defined($clock_info)) {
1269 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1270 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1271 if ($pos->{'toplay'} eq 'W') {
1272 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1274 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1279 # OK, we haven't seen this position before, so we assume the move
1280 # happened right now.
1282 # See if we should do our own clock management (ie., clock information
1283 # is spurious or non-existent).
1284 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1285 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1286 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1287 if (defined($prev_pos->{'white_clock_target'})) {
1288 $wc = $prev_pos->{'white_clock_target'} - time;
1290 if (defined($prev_pos->{'black_clock_target'})) {
1291 $bc = $prev_pos->{'black_clock_target'} - time;
1293 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1294 $pos->{'white_clock'} = $wc;
1295 $pos->{'black_clock'} = $bc;
1298 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1299 if (!exists($pos->{$key})) {
1300 # No clock information.
1303 my $time_left = $pos->{$key};
1304 my ($white_clock_target, $black_clock_target);
1305 if ($pos->{'toplay'} eq 'W') {
1306 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1308 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1310 local $dbh->{AutoCommit} = 0;
1311 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1312 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1313 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1317 sub schedule_tb_lookup {
1318 return if (!defined($remoteglotconf::tb_serial_key));
1319 my $pos = $pos_waiting // $pos_calculating;
1320 return if (exists($tb_cache{$pos->fen()}));
1322 # If there's more than seven pieces, there's not going to be an answer,
1324 return if ($pos->num_pieces() > 7);
1326 # Max one at a time. If it's still relevant when it returns,
1327 # schedule_tb_lookup() will be called again.
1328 return if ($tb_lookup_running);
1330 $tb_lookup_running = 1;
1331 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1332 $remoteglotconf::tb_serial_key .
1333 '&auth.password=aquarium&type=0&fen=' .
1334 URI::Escape::uri_escape($pos->fen());
1335 print TBLOG "Downloading $url...\n";
1336 AnyEvent::HTTP::http_get($url, sub {
1337 handle_tb_lookup_return(@_, $pos, $pos->fen());
1341 sub handle_tb_lookup_return {
1342 my ($body, $header, $pos, $fen) = @_;
1343 print TBLOG "Response for [$fen]:\n";
1344 print TBLOG $header . "\n\n";
1345 print TBLOG $body . "\n\n";
1347 my $response = JSON::XS::decode_json($body);
1348 if ($response->{'ErrorCode'} != 0) {
1349 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1351 my $state = $response->{'Response'}{'StateString'};
1352 if ($state eq 'COMPLETE') {
1353 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1354 if (!defined($pgn) || !$pgn->read_game()) {
1355 warn "Error in parsing PGN\n";
1357 $pgn->quick_parse_game;
1359 my $moves = $pgn->moves;
1361 for my $move (@$moves) {
1363 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1364 push @uci_moves, $uci_move;
1367 result => $pgn->result,
1369 score => $response->{'Response'}{'Score'},
1373 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1374 # Try again in a second. Note that if we have changed
1375 # position in the meantime, we might query a completely
1376 # different position! But that's fine.
1378 die "Unknown response state " . $state;
1381 # Wait a second before we schedule another one.
1382 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1383 $tb_lookup_running = 0;
1384 schedule_tb_lookup();
1388 warn "Error in tablebase lookup: $@";
1390 # Don't try this one again, but don't block new lookups either.
1391 $tb_lookup_running = 0;
1396 my ($cmdline, $tag, $cb) = @_;
1397 return undef if (!defined($cmdline));
1398 return Engine->open($cmdline, $tag, $cb);
1401 sub col_letter_to_num {
1402 return ord(shift) - ord('a');
1405 sub row_letter_to_num {
1406 return 7 - (ord(shift) - ord('1'));
1409 sub parse_uci_move {
1411 my $from_col = col_letter_to_num(substr($move, 0, 1));
1412 my $from_row = row_letter_to_num(substr($move, 1, 1));
1413 my $to_col = col_letter_to_num(substr($move, 2, 1));
1414 my $to_row = row_letter_to_num(substr($move, 3, 1));
1415 my $promo = substr($move, 4, 1);
1416 return ($from_row, $from_col, $to_row, $to_col, $promo);