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";
70 umask 0022; # analysis.json should not be served to users.
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_calculating, $pos_calculating_second_engine);
79 setoptions($engine, \%remoteglotconf::engine_config);
80 uciprint($engine, "ucinewgame");
82 if (defined($engine2)) {
83 setoptions($engine2, \%remoteglotconf::engine2_config);
84 uciprint($engine2, "setoption name MultiPV value 500");
85 uciprint($engine2, "ucinewgame");
88 print "Chess engine ready.\n";
92 if (defined($remoteglotconf::server)) {
93 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
94 $t->input_log(\*FICSLOG);
95 $t->open($remoteglotconf::server);
96 $t->print($remoteglotconf::nick);
97 $t->waitfor('/Press return to enter the server/');
101 $t->cmd("set shout 0");
102 $t->cmd("set seek 0");
103 $t->cmd("set style 12");
108 cb => sub { # what callback to execute
110 my $line = $t->getline(Timeout => 0, errmode => 'return');
111 return if (!defined($line));
120 if (defined($remoteglotconf::target)) {
121 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
122 fetch_pgn($remoteglotconf::target);
123 } elsif (defined($t)) {
124 $t->cmd("observe $remoteglotconf::target");
128 print "FICS ready.\n";
131 # Engine events have already been set up by Engine.pm.
135 my ($engine, $line, $primary) = @_;
137 return if $line =~ /(upper|lower)bound/;
139 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
140 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142 # If we've sent a stop command, gobble up lines until we see bestmove.
143 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
144 $engine->{'stopping'} = 0;
146 if ($line =~ /^info/) {
147 my (@infos) = split / /, $line;
150 parse_infos($engine, @infos);
152 if ($line =~ /^id/) {
153 my (@ids) = split / /, $line;
156 parse_ids($engine, @ids);
161 my $getting_movelist = 0;
162 my $pos_for_movelist = undef;
163 my @uci_movelist = ();
164 my @pretty_movelist = ();
168 if ($line =~ /^<12> /) {
169 handle_position(Position->new($line));
172 if ($line =~ /^Movelist for game /) {
173 my $pos = $pos_calculating;
176 @pretty_movelist = ();
177 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
178 $getting_movelist = 1;
181 if ($getting_movelist &&
182 $line =~ /^\s* \d+\. \s+ # move number
183 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
184 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
188 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
189 push @uci_movelist, $uci_move;
190 push @pretty_movelist, $1;
193 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
194 push @uci_movelist, $uci_move;
195 push @pretty_movelist, $2;
199 warn "Error when getting FICS move history: $@";
200 $getting_movelist = 0;
203 if ($getting_movelist &&
204 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
206 if (defined($pos_calculating)) {
207 if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
208 $pos_calculating->{'history'} = \@pretty_movelist;
211 $getting_movelist = 0;
213 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
214 my ($who, $msg) = ($1, $2);
216 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
218 if ($msg =~ /^fics (.*?)$/) {
219 $t->cmd("tell $who Executing '$1' on FICS.");
221 } elsif ($msg =~ /^uci (.*?)$/) {
222 $t->cmd("tell $who Sending '$1' to the engine.");
223 print { $engine->{'write'} } "$1\n";
224 } elsif ($msg =~ /^pgn (.*?)$/) {
226 $t->cmd("tell $who Starting to poll '$url'.");
228 } elsif ($msg =~ /^stoppgn$/) {
229 $t->cmd("tell $who Stopping poll.");
232 } elsif ($msg =~ /^quit$/) {
233 $t->cmd("tell $who Bye bye.");
236 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
239 #print "FICS: [$line]\n";
242 # Starts periodic fetching of PGNs from the given URL.
245 if ($url =~ m#^/#) { # Local file.
248 open my $fh, "<", $url
252 handle_pgn($pgn, '', $url);
256 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
261 AnyEvent::HTTP::http_get($url, sub {
262 handle_pgn(@_, $url);
267 my ($last_pgn_white, $last_pgn_black);
268 my @last_pgn_uci_moves = ();
269 my $pgn_hysteresis_counter = 0;
272 my ($body, $header, $url) = @_;
274 if ($stop_pgn_fetch) {
280 my $pgn = Chess::PGN::Parse->new(undef, $body);
281 if (!defined($pgn)) {
282 warn "Error in parsing PGN from $url [body='$body']\n";
283 } elsif (!$pgn->read_game()) {
284 warn "Error in reading PGN game from $url [body='$body']\n";
285 } elsif ($body !~ /^\[/) {
286 warn "Malformed PGN from $url [body='$body']\n";
289 # Skip to the right game.
290 while (defined($remoteglotconf::pgn_filter) &&
291 !&$remoteglotconf::pgn_filter($pgn)) {
292 $pgn->read_game() or die "Out of games during filtering";
295 $pgn->parse_game({ save_comments => 'yes' });
296 my $white = $pgn->white;
297 my $black = $pgn->black;
298 $white =~ s/,.*//; # Remove first name.
299 $black =~ s/,.*//; # Remove first name.
300 my $tags = $pgn->tags();
302 if (exists($tags->{'FEN'})) {
303 $pos = Position->from_fen($tags->{'FEN'});
304 $pos->{'last_move'} = 'none';
305 $pos->{'player_w'} = $white;
306 $pos->{'player_b'} = $black;
307 $pos->{'start_fen'} = $tags->{'FEN'};
309 $pos = Position->start_pos($white, $black);
311 if (exists($tags->{'Variant'}) &&
312 $tags->{'Variant'} =~ /960|fischer/i) {
313 $pos->{'chess960'} = 1;
315 $pos->{'chess960'} = 0;
317 my $moves = $pgn->moves;
319 my @repretty_moves = ();
320 for my $move (@$moves) {
321 my ($npos, $uci_move) = $pos->make_pretty_move($move);
322 push @uci_moves, $uci_move;
324 # Re-prettyprint the move.
325 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
326 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
327 push @repretty_moves, $pretty;
330 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
331 $pos->{'result'} = $pgn->result;
333 $pos->{'history'} = \@repretty_moves;
335 extract_clock($pgn, $pos);
337 # Sometimes, PGNs lose a move or two for a short while,
338 # or people push out new ones non-atomically.
339 # Thus, if we PGN doesn't change names but becomes
340 # shorter, we mistrust it for a few seconds.
342 if (defined($last_pgn_white) && defined($last_pgn_black) &&
343 $last_pgn_white eq $pgn->white &&
344 $last_pgn_black eq $pgn->black &&
345 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
346 if (++$pgn_hysteresis_counter < 3) {
351 $last_pgn_white = $pgn->white;
352 $last_pgn_black = $pgn->black;
353 @last_pgn_uci_moves = @uci_moves;
354 $pgn_hysteresis_counter = 0;
355 handle_position($pos);
359 warn "Error in parsing moves from $url: $@\n";
363 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
368 sub handle_position {
370 find_clock_start($pos, $pos_calculating);
372 # If we're already chewing on this and there's nothing else in the queue,
374 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
375 $pos_calculating->{'result'} = $pos->{'result'};
376 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
377 $pos_calculating->{$key} //= $pos->{$key};
382 # If we're already thinking on something, stop and wait for the engine
384 if (defined($pos_calculating)) {
385 # Store the final data we have for this position in the history,
386 # with the precise clock information we just got from the new
387 # position. (Historic positions store the clock at the end of
390 # Do not output anything new to the main analysis; that's
391 # going to be obsolete really soon.
392 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
393 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
394 delete $pos_calculating->{'white_clock_target'};
395 delete $pos_calculating->{'black_clock_target'};
398 # Ask the engine to stop; we will throw away its data until it
399 # sends us "bestmove", signaling the end of it.
400 $engine->{'stopping'} = 1;
401 uciprint($engine, "stop");
404 # It's wrong to just give the FEN (the move history is useful,
405 # and per the UCI spec, we should really have sent "ucinewgame"),
406 # but it's easier, and it works around a Stockfish repetition issue.
407 if ($engine->{'chess960'} != $pos->{'chess960'}) {
408 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
409 $engine->{'chess960'} = $pos->{'chess960'};
411 uciprint($engine, "position fen " . $pos->fen());
412 uciprint($engine, "go infinite");
413 $pos_calculating = $pos;
415 if (defined($engine2)) {
416 if (defined($pos_calculating_second_engine)) {
417 $engine2->{'stopping'} = 1;
418 uciprint($engine2, "stop");
420 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
421 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
422 $engine2->{'chess960'} = $pos->{'chess960'};
424 uciprint($engine2, "position fen " . $pos->fen());
425 uciprint($engine2, "go infinite");
426 $pos_calculating_second_engine = $pos;
427 $engine2->{'info'} = {};
430 $engine->{'info'} = {};
433 schedule_tb_lookup();
436 # Output a command every move to note that we're
437 # still paying attention -- this is a good tradeoff,
438 # since if no move has happened in the last half
439 # hour, the analysis/relay has most likely stopped
440 # and we should stop hogging server resources.
448 my ($engine, @x) = @_;
451 my $info = $engine->{'info'};
453 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
454 for my $i (0..$#x - 1) {
455 if ($x[$i] eq 'multipv') {
461 while (scalar @x > 0) {
462 if ($x[0] eq 'multipv') {
468 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
470 my $value = shift @x;
471 $info->{$key} = $value;
474 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
475 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
478 my $value = shift @x;
479 $info->{$key . $mpv} = $value;
482 if ($x[0] eq 'score') {
485 delete $info->{'score_cp' . $mpv};
486 delete $info->{'score_mate' . $mpv};
488 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
491 $info->{'score_cp' . $mpv} = shift @x;
492 } elsif ($x[0] eq 'mate') {
494 $info->{'score_mate' . $mpv} = shift @x;
502 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
505 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
509 #print "unknown info '$x[0]', trying to recover...\n";
511 die "Unknown info '" . join(',', @x) . "'";
517 my ($engine, @x) = @_;
519 while (scalar @x > 0) {
520 if ($x[0] eq 'name') {
521 my $value = join(' ', @x);
522 $engine->{'id'}{'author'} = $value;
531 sub prettyprint_pv_no_cache {
532 my ($board, @pvs) = @_;
534 if (scalar @pvs == 0 || !defined($pvs[0])) {
539 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
540 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
541 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
545 my ($pos, @pvs) = @_;
547 my $cachekey = join('', @pvs);
548 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
549 return @{$pos->{'prettyprint_cache'}{$cachekey}};
551 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
552 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
557 my %tbprobe_cache = ();
559 sub complete_using_tbprobe {
560 my ($pos, $info, $mpv) = @_;
562 # We need Fathom installed to do standalone TB probes.
563 return if (!defined($remoteglotconf::fathom_cmdline));
565 # If we already have a mate, don't bother; in some cases, it would even be
566 # better than a tablebase score.
567 return if defined($info->{'score_mate' . $mpv});
569 # If we have a draw or near-draw score, there's also not much interesting
570 # we could add from a tablebase. We only really want mates.
571 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
573 # Run through the PV until we are at a 6-man position.
574 # TODO: We could in theory only have 5-man data.
575 my @pv = @{$info->{'pv' . $mpv}};
576 my $key = $pos->fen() . " " . join('', @pv);
578 if (exists($tbprobe_cache{$key})) {
579 @moves = @{$tbprobe_cache{$key}};
582 # Force doing at least one move of the PV.
583 my $move = shift @pv;
585 $pos = $pos->make_move(parse_uci_move($move));
588 while ($pos->num_pieces() > 7 && $#pv > -1) {
589 my $move = shift @pv;
591 $pos = $pos->make_move(parse_uci_move($move));
594 return if ($pos->num_pieces() > 7);
596 my $fen = $pos->fen();
597 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
598 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
599 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
600 $pgn->quick_parse_game;
601 $info->{'pv' . $mpv} = \@moves;
603 # Splice the PV from the tablebase onto what we have so far.
604 for my $move (@{$pgn->moves}) {
605 last if $move eq '#';
606 last if $move eq '1-0';
607 last if $move eq '0-1';
608 last if $move eq '1/2-1/2';
610 ($pos, $uci_move) = $pos->make_pretty_move($move);
611 push @moves, $uci_move;
614 $tbprobe_cache{$key} = \@moves;
617 $info->{'pv' . $mpv} = \@moves;
619 my $matelen = int((1 + scalar @moves) / 2);
620 if ((scalar @moves) % 2 == 0) {
621 $info->{'score_mate' . $mpv} = -$matelen;
623 $info->{'score_mate' . $mpv} = $matelen;
630 return if (!defined($pos_calculating));
632 # Don't update too often.
633 my $age = Time::HiRes::tv_interval($latest_update);
634 if ($age < $remoteglotconf::update_max_interval) {
635 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
636 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
640 my $info = $engine->{'info'};
643 # If we have tablebase data from a previous lookup, replace the
644 # engine data with the data from the tablebase.
646 my $fen = $pos_calculating->fen();
647 if (exists($tb_cache{$fen})) {
648 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
649 delete $info->{$key . '1'};
650 delete $info->{$key};
652 $info->{'nodes'} = 0;
654 $info->{'depth'} = 0;
655 $info->{'seldepth'} = 0;
656 $info->{'tbhits'} = 0;
658 my $t = $tb_cache{$fen};
660 my $matelen = int((1 + $t->{'score'}) / 2);
661 if ($t->{'result'} eq '1/2-1/2') {
662 $info->{'score_cp'} = 0;
663 } elsif ($t->{'result'} eq '1-0') {
664 if ($pos_calculating->{'toplay'} eq 'B') {
665 $info->{'score_mate'} = -$matelen;
667 $info->{'score_mate'} = $matelen;
670 if ($pos_calculating->{'toplay'} eq 'B') {
671 $info->{'score_mate'} = $matelen;
673 $info->{'score_mate'} = -$matelen;
677 $info->{'tablebase'} = 1;
679 $info->{'tablebase'} = 0;
683 # Some programs _always_ report MultiPV, even with only one PV.
684 # In this case, we simply use that data as if MultiPV was never
687 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
688 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
689 if (exists($info->{$key . '1'})) {
690 $info->{$key} = $info->{$key . '1'};
692 delete $info->{$key};
698 # Check the PVs first. if they're invalid, just wait, as our data
699 # is most likely out of sync. This isn't a very good solution, as
700 # it can frequently miss stuff, but it's good enough for most users.
704 if (exists($info->{'pv'})) {
705 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
709 while (exists($info->{'pv' . $mpv})) {
710 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
715 $engine->{'info'} = {};
719 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
720 if (exists($info->{'pv'})) {
721 complete_using_tbprobe($pos_calculating, $info, '');
725 while (exists($info->{'pv' . $mpv})) {
726 complete_using_tbprobe($pos_calculating, $info, $mpv);
732 $latest_update = [Time::HiRes::gettimeofday];
736 my $info = $engine->{'info'};
737 my $id = $engine->{'id'};
739 my $text = 'Analysis';
740 if ($pos_calculating->{'last_move'} ne 'none') {
741 if ($pos_calculating->{'toplay'} eq 'W') {
742 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
744 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
746 if (exists($id->{'name'})) {
751 if (exists($id->{'name'})) {
752 $text .= " by $id->{'name'}:\n\n";
757 return unless (exists($pos_calculating->{'board'}));
759 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
762 while (exists($info->{'pv' . $mpv})) {
763 $text .= sprintf " PV%2u", $mpv;
764 my $score = short_score($info, $pos_calculating, $mpv);
765 $text .= " ($score)" if (defined($score));
768 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
769 if ($info->{'tbhits' . $mpv} == 1) {
770 $tbhits = ", 1 tbhit";
772 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
776 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
777 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
778 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
782 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
788 my $score = long_score($info, $pos_calculating, '');
789 $text .= " $score\n" if defined($score);
790 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
793 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
794 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
795 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
797 if (exists($info->{'seldepth'})) {
798 $text .= sprintf " (%u selective)", $info->{'seldepth'};
800 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
801 if ($info->{'tbhits'} == 1) {
802 $text .= ", one Syzygy hit";
804 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
810 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
812 my @refutation_lines = ();
813 if (defined($engine2)) {
814 for (my $mpv = 1; $mpv < 500; ++$mpv) {
815 my $info = $engine2->{'info'};
816 last if (!exists($info->{'pv' . $mpv}));
818 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
819 my $pv = $info->{'pv' . $mpv};
820 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
821 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
822 if (scalar @pretty_pv > 5) {
823 @pretty_pv = @pretty_pv[0..4];
824 push @pretty_pv, "...";
826 my $key = $pretty_move;
827 my $line = sprintf(" %-6s %6s %3s %s",
829 short_score($info, $pos_calculating_second_engine, $mpv),
830 "d" . $info->{'depth' . $mpv},
831 join(', ', @pretty_pv));
832 push @refutation_lines, [ $key, $line ];
837 if ($#refutation_lines >= 0) {
838 $text .= "Shallow search of all legal moves:\n\n";
839 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
840 $text .= $line->[1] . "\n";
845 if ($last_text ne $text) {
846 print "
\e[H
\e[2J"; # clear the screen
853 my $historic_json_only = shift;
854 my $info = $engine->{'info'};
857 $json->{'position'} = $pos_calculating->to_json_hash();
858 $json->{'engine'} = $engine->{'id'};
859 if (defined($remoteglotconf::engine_url)) {
860 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
862 if (defined($remoteglotconf::engine_details)) {
863 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
865 my @grpc_backends = ();
866 if (defined($remoteglotconf::engine_grpc_backend)) {
867 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
869 if (defined($remoteglotconf::engine2_grpc_backend)) {
870 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
872 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
873 if (defined($remoteglotconf::move_source)) {
874 $json->{'move_source'} = $remoteglotconf::move_source;
876 if (defined($remoteglotconf::move_source_url)) {
877 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
879 $json->{'score'} = score_digest($info, $pos_calculating, '');
880 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
882 $json->{'nodes'} = $info->{'nodes'};
883 $json->{'nps'} = $info->{'nps'};
884 $json->{'depth'} = $info->{'depth'};
885 $json->{'tbhits'} = $info->{'tbhits'};
886 $json->{'seldepth'} = $info->{'seldepth'};
887 $json->{'tablebase'} = $info->{'tablebase'};
888 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
890 my %refutation_lines = ();
891 my @refutation_lines = ();
892 if (defined($engine2)) {
893 for (my $mpv = 1; $mpv < 500; ++$mpv) {
894 my $info = $engine2->{'info'};
895 my $pretty_move = "";
897 last if (!exists($info->{'pv' . $mpv}));
900 complete_using_tbprobe($pos_calculating, $info, $mpv);
901 my $pv = $info->{'pv' . $mpv};
902 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
903 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
904 $refutation_lines{$pretty_move} = {
905 depth => $info->{'depth' . $mpv},
906 score => score_digest($info, $pos_calculating, $mpv),
907 move => $pretty_move,
913 $json->{'refutation_lines'} = \%refutation_lines;
915 # Piece together historic score information, to the degree we have it.
916 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
917 my %score_history = ();
919 local $dbh->{AutoCommit} = 0;
920 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
922 if (exists($pos_calculating->{'start_fen'})) {
923 $pos = Position->from_fen($pos_calculating->{'start_fen'});
925 $pos = Position->start_pos('white', 'black');
927 $pos->{'chess960'} = $pos_calculating->{'chess960'};
928 my $halfmove_num = 0;
929 for my $move (@{$pos_calculating->{'history'}}) {
930 my $id = id_for_pos($pos, $halfmove_num);
931 my $ref = $dbh->selectrow_hashref($q, undef, $id);
933 $score_history{$halfmove_num} = [
934 $ref->{'score_type'},
935 $ref->{'score_value'}
939 ($pos) = $pos->make_pretty_move($move);
944 # If at any point we are missing 10 consecutive moves,
945 # truncate the history there. This is so we don't get into
946 # a situation where we e.g. start analyzing at move 45,
947 # but we have analysis for 1. e4 from some completely different game
948 # and thus show a huge hole.
949 my $consecutive_missing = 0;
950 my $truncate_until = 0;
951 for (my $i = $halfmove_num; $i --> 0; ) {
952 if ($consecutive_missing >= 10) {
953 delete $score_history{$i};
956 if (exists($score_history{$i})) {
957 $consecutive_missing = 0;
959 ++$consecutive_missing;
963 $json->{'score_history'} = \%score_history;
966 # Give out a list of other games going on. (Empty is fine.)
967 # TODO: Don't bother reading our own file, the data will be stale anyway.
968 if (!$historic_json_only) {
971 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
973 while (my $ref = $q->fetchrow_hashref) {
975 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
976 my $other_game_json = JSON::XS::decode_json($other_game_contents);
978 die "Missing position" if (!exists($other_game_json->{'position'}));
979 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
980 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
984 name => "$white–$black",
985 url => $ref->{'url'},
986 hashurl => $ref->{'hash_url'},
988 if (defined($other_game_json->{'position'}{'result'})) {
989 $game->{'result'} = $other_game_json->{'position'}{'result'};
991 $game->{'score'} = $other_game_json->{'score'};
996 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1000 if (scalar @games > 0) {
1001 $json->{'games'} = \@games;
1005 my $json_enc = JSON::XS->new;
1006 $json_enc->canonical(1);
1007 my $encoded = $json_enc->encode($json);
1008 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1009 (defined($last_written_json) && $last_written_json eq $encoded)) {
1010 atomic_set_contents($remoteglotconf::json_output, $encoded);
1011 $last_written_json = $encoded;
1014 if (exists($pos_calculating->{'history'}) &&
1015 defined($remoteglotconf::json_history_dir)) {
1016 my $id = id_for_pos($pos_calculating);
1017 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1019 # Overwrite old analysis (assuming it exists at all) if we're
1020 # using a different engine, or if we've calculated deeper.
1021 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1022 # data; it's not that important.
1023 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1024 my $new_depth = $json->{'depth'} // 0;
1025 my $new_nodes = $json->{'nodes'} // 0;
1026 if (!defined($old_engine) ||
1027 $old_engine ne $json->{'engine'}{'name'} ||
1028 $new_depth > $old_depth ||
1029 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1030 atomic_set_contents($filename, $encoded);
1031 if (defined($json->{'score'})) {
1032 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1033 ' ON CONFLICT (id) DO UPDATE SET ' .
1034 ' score_type=EXCLUDED.score_type, ' .
1035 ' score_value=EXCLUDED.score_value, ' .
1036 ' engine=EXCLUDED.engine, ' .
1037 ' depth=EXCLUDED.depth, ' .
1038 ' nodes=EXCLUDED.nodes',
1040 $id, $json->{'score'}[0], $json->{'score'}[1],
1041 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1047 sub atomic_set_contents {
1048 my ($filename, $contents) = @_;
1050 open my $fh, ">", $filename . ".tmp"
1052 print $fh $contents;
1054 rename($filename . ".tmp", $filename);
1058 my ($pos, $halfmove_num) = @_;
1060 $halfmove_num //= scalar @{$pos->{'history'}};
1061 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1062 return "move$halfmove_num-$fen";
1065 sub get_json_analysis_stats {
1067 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1068 if (defined($ref)) {
1069 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1076 my ($engine, $msg) = @_;
1077 $engine->print($msg);
1078 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1082 my ($info, $pos, $mpv) = @_;
1084 my $invert = ($pos->{'toplay'} eq 'B');
1085 if (defined($info->{'score_mate' . $mpv})) {
1087 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1089 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1092 if (exists($info->{'score_cp' . $mpv})) {
1093 my $score = $info->{'score_cp' . $mpv} * 0.01;
1095 if ($info->{'tablebase'}) {
1104 return sprintf "%+5.2f", $score;
1111 # Sufficient for computing long_score, short_score, plot_score and
1112 # (with side-to-play information) score_sort_key.
1114 my ($info, $pos, $mpv) = @_;
1116 if (defined($info->{'score_mate' . $mpv})) {
1117 my $mate = $info->{'score_mate' . $mpv};
1118 if ($pos->{'toplay'} eq 'B') {
1121 return ['m', $mate];
1123 if (exists($info->{'score_cp' . $mpv})) {
1124 my $score = $info->{'score_cp' . $mpv};
1125 if ($pos->{'toplay'} eq 'B') {
1128 if ($score == 0 && $info->{'tablebase'}) {
1129 return ['d', undef];
1131 return ['cp', int($score)];
1140 my ($info, $pos, $mpv) = @_;
1142 if (defined($info->{'score_mate' . $mpv})) {
1143 my $mate = $info->{'score_mate' . $mpv};
1144 if ($pos->{'toplay'} eq 'B') {
1148 return sprintf "White mates in %u", $mate;
1150 return sprintf "Black mates in %u", -$mate;
1153 if (exists($info->{'score_cp' . $mpv})) {
1154 my $score = $info->{'score_cp' . $mpv} * 0.01;
1156 if ($info->{'tablebase'}) {
1157 return "Theoretical draw";
1159 return "Score: 0.00";
1162 if ($pos->{'toplay'} eq 'B') {
1165 return sprintf "Score: %+5.2f", $score;
1172 # For graphs; a single number in centipawns, capped at +/- 500.
1174 my ($info, $pos, $mpv) = @_;
1176 my $invert = ($pos->{'toplay'} eq 'B');
1177 if (defined($info->{'score_mate' . $mpv})) {
1178 my $mate = $info->{'score_mate' . $mpv};
1188 if (exists($info->{'score_cp' . $mpv})) {
1189 my $score = $info->{'score_cp' . $mpv};
1193 $score = 500 if ($score > 500);
1194 $score = -500 if ($score < -500);
1202 my %book_cache = ();
1204 my ($fen, $board, $toplay) = @_;
1206 if (exists($book_cache{$fen})) {
1207 return $book_cache{$fen};
1210 my $ret = `./booklook $fen`;
1211 return "" if ($ret =~ /Not found/ || $ret eq '');
1215 for my $m (split /\n/, $ret) {
1216 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1220 $pmove = '(current)';
1222 ($pmove) = prettyprint_pv_no_cache($board, $move);
1223 $pmove .= $annotation;
1227 if ($toplay eq 'W') {
1228 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1230 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1232 my $n = $win + $draw + $lose;
1238 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1241 push @moves, [ $pmove, $n, $percent, $rating ];
1244 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1246 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1247 for my $m (@moves) {
1248 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1255 my ($pgn, $pos) = @_;
1257 # Look for extended PGN clock tags.
1258 my $tags = $pgn->tags;
1259 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1260 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1261 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1265 # Look for TCEC-style time comments.
1266 my $moves = $pgn->moves;
1267 my $comments = $pgn->comments;
1268 my $last_black_move = int((scalar @$moves) / 2);
1269 my $last_white_move = int((1 + scalar @$moves) / 2);
1271 my $black_key = $last_black_move . "b";
1272 my $white_key = $last_white_move . "w";
1274 if (exists($comments->{$white_key}) &&
1275 exists($comments->{$black_key}) &&
1276 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1277 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1278 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1279 $pos->{'white_clock'} = hms_to_sec($1);
1280 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1281 $pos->{'black_clock'} = hms_to_sec($1);
1285 delete $pos->{'white_clock'};
1286 delete $pos->{'black_clock'};
1291 return undef if (!defined($hms));
1292 $hms =~ /(\d+):(\d+):(\d+)/;
1293 return $1 * 3600 + $2 * 60 + $3;
1296 sub find_clock_start {
1297 my ($pos, $prev_pos) = @_;
1299 # If the game is over, the clock is stopped.
1300 if (exists($pos->{'result'}) &&
1301 ($pos->{'result'} eq '1-0' ||
1302 $pos->{'result'} eq '1/2-1/2' ||
1303 $pos->{'result'} eq '0-1')) {
1307 # When we don't have any moves, we assume the clock hasn't started yet.
1308 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1309 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1310 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1315 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1316 # The history is needed for id_for_pos.
1317 if (!exists($pos->{'history'})) {
1321 my $id = id_for_pos($pos);
1322 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=? AND COALESCE(white_clock_target, black_clock_target) >= EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - INTERVAL \'1 day\'));', undef, $id);
1323 if (defined($clock_info)) {
1324 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1325 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1326 if ($pos->{'toplay'} eq 'W') {
1327 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1329 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1334 # OK, we haven't seen this position before, so we assume the move
1335 # happened right now.
1337 # See if we should do our own clock management (ie., clock information
1338 # is spurious or non-existent).
1339 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1340 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1341 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1342 if (defined($prev_pos->{'white_clock_target'})) {
1343 $wc = $prev_pos->{'white_clock_target'} - time;
1345 if (defined($prev_pos->{'black_clock_target'})) {
1346 $bc = $prev_pos->{'black_clock_target'} - time;
1348 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1349 $pos->{'white_clock'} = $wc;
1350 $pos->{'black_clock'} = $bc;
1353 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1354 if (!exists($pos->{$key})) {
1355 # No clock information.
1358 my $time_left = $pos->{$key};
1359 my ($white_clock_target, $black_clock_target);
1360 if ($pos->{'toplay'} eq 'W') {
1361 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1363 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1365 local $dbh->{AutoCommit} = 0;
1366 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1367 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1368 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1372 sub schedule_tb_lookup {
1373 return if (!defined($remoteglotconf::tb_serial_key));
1374 my $pos = $pos_calculating;
1375 return if (exists($tb_cache{$pos->fen()}));
1377 # If there's more than seven pieces, there's not going to be an answer,
1379 return if ($pos->num_pieces() > 7);
1381 # Max one at a time. If it's still relevant when it returns,
1382 # schedule_tb_lookup() will be called again.
1383 return if ($tb_lookup_running);
1385 $tb_lookup_running = 1;
1386 my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1387 $remoteglotconf::tb_serial_key .
1388 '&auth.password=aquarium&type=0&fen=' .
1389 URI::Escape::uri_escape($pos->fen());
1390 print TBLOG "Downloading $url...\n";
1391 AnyEvent::HTTP::http_get($url, sub {
1392 handle_tb_lookup_return(@_, $pos, $pos->fen());
1396 sub handle_tb_lookup_return {
1397 my ($body, $header, $pos, $fen) = @_;
1398 print TBLOG "Response for [$fen]:\n";
1399 print TBLOG $header . "\n\n";
1400 print TBLOG $body . "\n\n";
1402 my $response = JSON::XS::decode_json($body);
1403 if ($response->{'ErrorCode'} != 0) {
1404 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1406 my $state = $response->{'Response'}{'StateString'};
1407 if ($state eq 'COMPLETE') {
1408 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1409 if (!defined($pgn) || !$pgn->read_game()) {
1410 warn "Error in parsing PGN\n";
1412 $pgn->quick_parse_game;
1414 my $moves = $pgn->moves;
1416 for my $move (@$moves) {
1418 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1419 push @uci_moves, $uci_move;
1422 result => $pgn->result,
1424 score => $response->{'Response'}{'Score'},
1428 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1429 # Try again in a second. Note that if we have changed
1430 # position in the meantime, we might query a completely
1431 # different position! But that's fine.
1433 die "Unknown response state " . $state;
1436 # Wait a second before we schedule another one.
1437 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1438 $tb_lookup_running = 0;
1439 schedule_tb_lookup();
1443 warn "Error in tablebase lookup: $@";
1445 # Don't try this one again, but don't block new lookups either.
1446 $tb_lookup_running = 0;
1451 my ($cmdline, $tag, $cb) = @_;
1452 return undef if (!defined($cmdline));
1453 return Engine->open($cmdline, $tag, $cb);
1456 sub col_letter_to_num {
1457 return ord(shift) - ord('a');
1460 sub row_letter_to_num {
1461 return 7 - (ord(shift) - ord('1'));
1464 sub parse_uci_move {
1466 my $from_col = col_letter_to_num(substr($move, 0, 1));
1467 my $from_row = row_letter_to_num(substr($move, 1, 1));
1468 my $to_col = col_letter_to_num(substr($move, 2, 1));
1469 my $to_row = row_letter_to_num(substr($move, 3, 1));
1470 my $promo = substr($move, 4, 1);
1471 return ($from_row, $from_col, $to_row, $to_col, $promo);
1475 my ($engine, $config) = @_;
1476 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1477 uciprint($engine, "setoption name Analysis Contempt value Off");
1478 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1479 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1481 while (my ($key, $value) = each %$config) {
1482 next if $key eq 'Threads';
1483 uciprint($engine, "setoption name $key value $value");