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 <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
15 use Chess::PGN::Parse;
23 require 'Position.pm';
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
37 my $tb_lookup_running = 0;
39 # TODO: Persist (parts of) this so that we can restart.
40 my %clock_target_for_pos = ();
44 open(FICSLOG, ">ficslog.txt")
45 or die "ficslog.txt: $!";
46 print FICSLOG "Log starting.\n";
50 open(UCILOG, ">ucilog.txt")
51 or die "ucilog.txt: $!";
52 print UCILOG "Log starting.\n";
56 open(TBLOG, ">tblog.txt")
57 or die "tblog.txt: $!";
58 print TBLOG "Log starting.\n";
64 # open the chess engine
65 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
66 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
69 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
71 uciprint($engine, "setoption name UCI_AnalyseMode value true");
72 while (my ($key, $value) = each %remoteglotconf::engine_config) {
73 uciprint($engine, "setoption name $key value $value");
75 uciprint($engine, "ucinewgame");
77 if (defined($engine2)) {
78 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
79 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
80 uciprint($engine2, "setoption name $key value $value");
82 uciprint($engine2, "setoption name MultiPV value 500");
83 uciprint($engine2, "ucinewgame");
86 print "Chess engine ready.\n";
89 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
90 $t->input_log(\*FICSLOG);
91 $t->open($remoteglotconf::server);
92 $t->print($remoteglotconf::nick);
93 $t->waitfor('/Press return to enter the server/');
97 $t->cmd("set shout 0");
98 $t->cmd("set seek 0");
99 $t->cmd("set style 12");
101 my $ev1 = AnyEvent->io(
104 cb => sub { # what callback to execute
106 my $line = $t->getline(Timeout => 0, errmode => 'return');
107 return if (!defined($line));
115 if (defined($remoteglotconf::target)) {
116 if ($remoteglotconf::target =~ /^http:/) {
117 fetch_pgn($remoteglotconf::target);
119 $t->cmd("observe $remoteglotconf::target");
122 print "FICS ready.\n";
124 # Engine events have already been set up by Engine.pm.
128 my ($engine, $line, $primary) = @_;
130 return if $line =~ /(upper|lower)bound/;
132 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
133 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
134 if ($line =~ /^info/) {
135 my (@infos) = split / /, $line;
138 parse_infos($engine, @infos);
140 if ($line =~ /^id/) {
141 my (@ids) = split / /, $line;
144 parse_ids($engine, @ids);
146 if ($line =~ /^bestmove/) {
148 return if (!$remoteglotconf::uci_assume_full_compliance);
149 if (defined($pos_waiting)) {
150 uciprint($engine, "position fen " . $pos_waiting->fen());
151 uciprint($engine, "go infinite");
153 $pos_calculating = $pos_waiting;
154 $pos_waiting = undef;
157 $engine2->{'info'} = {};
158 my $pos = $pos_waiting // $pos_calculating;
159 uciprint($engine2, "position fen " . $pos->fen());
160 uciprint($engine2, "go infinite");
161 $pos_calculating_second_engine = $pos;
167 my $getting_movelist = 0;
168 my $pos_for_movelist = undef;
169 my @uci_movelist = ();
170 my @pretty_movelist = ();
174 if ($line =~ /^<12> /) {
175 handle_position(Position->new($line));
178 if ($line =~ /^Movelist for game /) {
179 my $pos = $pos_waiting // $pos_calculating;
182 @pretty_movelist = ();
183 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
184 $getting_movelist = 1;
187 if ($getting_movelist &&
188 $line =~ /^\s* \d+\. \s+ # move number
189 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
190 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
194 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
195 push @uci_movelist, $uci_move;
196 push @pretty_movelist, $1;
199 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
200 push @uci_movelist, $uci_move;
201 push @pretty_movelist, $2;
205 warn "Error when getting FICS move history: $@";
206 $getting_movelist = 0;
209 if ($getting_movelist &&
210 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
212 for my $pos ($pos_waiting, $pos_calculating) {
213 next if (!defined($pos));
214 if ($pos->fen() eq $pos_for_movelist->fen()) {
215 $pos->{'pretty_history'} = \@pretty_movelist;
218 $getting_movelist = 0;
220 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
221 my ($who, $msg) = ($1, $2);
223 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
225 if ($msg =~ /^fics (.*?)$/) {
226 $t->cmd("tell $who Executing '$1' on FICS.");
228 } elsif ($msg =~ /^uci (.*?)$/) {
229 $t->cmd("tell $who Sending '$1' to the engine.");
230 print { $engine->{'write'} } "$1\n";
231 } elsif ($msg =~ /^pgn (.*?)$/) {
233 $t->cmd("tell $who Starting to poll '$url'.");
235 } elsif ($msg =~ /^stoppgn$/) {
236 $t->cmd("tell $who Stopping poll.");
239 } elsif ($msg =~ /^quit$/) {
240 $t->cmd("tell $who Bye bye.");
243 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
246 #print "FICS: [$line]\n";
249 # Starts periodic fetching of PGNs from the given URL.
252 AnyEvent::HTTP::http_get($url, sub {
253 handle_pgn(@_, $url);
257 my ($last_pgn_white, $last_pgn_black);
258 my @last_pgn_uci_moves = ();
259 my $pgn_hysteresis_counter = 0;
262 my ($body, $header, $url) = @_;
264 if ($stop_pgn_fetch) {
270 my $pgn = Chess::PGN::Parse->new(undef, $body);
271 if (!defined($pgn) || !$pgn->read_game()) {
272 warn "Error in parsing PGN from $url\n";
275 $pgn->parse_game({ save_comments => 'yes' });
276 my $pos = Position->start_pos($pgn->white, $pgn->black);
277 my $moves = $pgn->moves;
279 for my $move (@$moves) {
281 ($pos, $uci_move) = $pos->make_pretty_move($move);
282 push @uci_moves, $uci_move;
284 $pos->{'result'} = $pgn->result;
285 $pos->{'pretty_history'} = $moves;
287 extract_clock($pgn, $pos);
289 # Sometimes, PGNs lose a move or two for a short while,
290 # or people push out new ones non-atomically.
291 # Thus, if we PGN doesn't change names but becomes
292 # shorter, we mistrust it for a few seconds.
294 if (defined($last_pgn_white) && defined($last_pgn_black) &&
295 $last_pgn_white eq $pgn->white &&
296 $last_pgn_black eq $pgn->black &&
297 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
298 if (++$pgn_hysteresis_counter < 3) {
303 $last_pgn_white = $pgn->white;
304 $last_pgn_black = $pgn->black;
305 @last_pgn_uci_moves = @uci_moves;
306 $pgn_hysteresis_counter = 0;
307 handle_position($pos);
311 warn "Error in parsing moves from $url\n";
315 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
320 sub handle_position {
322 find_clock_start($pos);
324 # if this is already in the queue, ignore it
325 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
327 # if we're already chewing on this and there's nothing else in the queue,
329 return if (!defined($pos_waiting) && defined($pos_calculating) &&
330 $pos->fen() eq $pos_calculating->fen());
332 # if we're already thinking on something, stop and wait for the engine
334 if (defined($pos_calculating)) {
335 # Store the final data we have for this position in the history,
336 # with the precise clock information we just got from the new
337 # position. (Historic positions store the clock at the end of
340 # Do not output anything new to the main analysis; that's
341 # going to be obsolete really soon.
342 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
343 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
344 delete $pos_calculating->{'white_clock_target'};
345 delete $pos_calculating->{'black_clock_target'};
348 if (!defined($pos_waiting)) {
349 uciprint($engine, "stop");
351 if ($remoteglotconf::uci_assume_full_compliance) {
354 uciprint($engine, "position fen " . $pos->fen());
355 uciprint($engine, "go infinite");
356 $pos_calculating = $pos;
359 # it's wrong just to give the FEN (the move history is useful,
360 # and per the UCI spec, we should really have sent "ucinewgame"),
362 uciprint($engine, "position fen " . $pos->fen());
363 uciprint($engine, "go infinite");
364 $pos_calculating = $pos;
367 if (defined($engine2)) {
368 if (defined($pos_calculating_second_engine)) {
369 uciprint($engine2, "stop");
371 uciprint($engine2, "position fen " . $pos->fen());
372 uciprint($engine2, "go infinite");
373 $pos_calculating_second_engine = $pos;
375 $engine2->{'info'} = {};
378 $engine->{'info'} = {};
381 schedule_tb_lookup();
384 # Output a command every move to note that we're
385 # still paying attention -- this is a good tradeoff,
386 # since if no move has happened in the last half
387 # hour, the analysis/relay has most likely stopped
388 # and we should stop hogging server resources.
394 my ($engine, @x) = @_;
397 my $info = $engine->{'info'};
399 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
400 for my $i (0..$#x - 1) {
401 if ($x[$i] eq 'multipv') {
407 while (scalar @x > 0) {
408 if ($x[0] eq 'multipv') {
414 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
416 my $value = shift @x;
417 $info->{$key} = $value;
420 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
421 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
424 my $value = shift @x;
425 $info->{$key . $mpv} = $value;
428 if ($x[0] eq 'score') {
431 delete $info->{'score_cp' . $mpv};
432 delete $info->{'score_mate' . $mpv};
434 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
437 $info->{'score_cp' . $mpv} = shift @x;
438 } elsif ($x[0] eq 'mate') {
440 $info->{'score_mate' . $mpv} = shift @x;
448 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
451 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
455 #print "unknown info '$x[0]', trying to recover...\n";
457 die "Unknown info '" . join(',', @x) . "'";
463 my ($engine, @x) = @_;
465 while (scalar @x > 0) {
466 if ($x[0] =~ /^(name|author)$/) {
468 my $value = join(' ', @x);
469 $engine->{'id'}{$key} = $value;
478 sub prettyprint_pv_no_cache {
479 my ($board, @pvs) = @_;
481 if (scalar @pvs == 0 || !defined($pvs[0])) {
486 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
487 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
488 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
492 my ($pos, @pvs) = @_;
494 my $cachekey = join('', @pvs);
495 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
496 return @{$pos->{'prettyprint_cache'}{$cachekey}};
498 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
499 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
507 return if (!defined($pos_calculating));
509 # Don't update too often.
510 my $age = Time::HiRes::tv_interval($latest_update);
511 if ($age < $remoteglotconf::update_max_interval) {
512 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
513 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
517 my $info = $engine->{'info'};
520 # If we have tablebase data from a previous lookup, replace the
521 # engine data with the data from the tablebase.
523 my $fen = $pos_calculating->fen();
524 if (exists($tb_cache{$fen})) {
525 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
526 delete $info->{$key . '1'};
527 delete $info->{$key};
529 $info->{'nodes'} = 0;
531 $info->{'depth'} = 0;
532 $info->{'seldepth'} = 0;
533 $info->{'tbhits'} = 0;
535 my $t = $tb_cache{$fen};
537 my $matelen = int((1 + $t->{'score'}) / 2);
538 if ($t->{'result'} eq '1/2-1/2') {
539 $info->{'score_cp'} = 0;
540 } elsif ($t->{'result'} eq '1-0') {
541 if ($pos_calculating->{'toplay'} eq 'B') {
542 $info->{'score_mate'} = -$matelen;
544 $info->{'score_mate'} = $matelen;
547 if ($pos_calculating->{'toplay'} eq 'B') {
548 $info->{'score_mate'} = $matelen;
550 $info->{'score_mate'} = -$matelen;
554 $info->{'tablebase'} = 1;
556 $info->{'tablebase'} = 0;
560 # Some programs _always_ report MultiPV, even with only one PV.
561 # In this case, we simply use that data as if MultiPV was never
564 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
565 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
566 if (exists($info->{$key . '1'})) {
567 $info->{$key} = $info->{$key . '1'};
573 # Check the PVs first. if they're invalid, just wait, as our data
574 # is most likely out of sync. This isn't a very good solution, as
575 # it can frequently miss stuff, but it's good enough for most users.
579 if (exists($info->{'pv'})) {
580 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
584 while (exists($info->{'pv' . $mpv})) {
585 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
590 $engine->{'info'} = {};
596 $latest_update = [Time::HiRes::gettimeofday];
600 my $info = $engine->{'info'};
601 my $id = $engine->{'id'};
603 my $text = 'Analysis';
604 if ($pos_calculating->{'last_move'} ne 'none') {
605 if ($pos_calculating->{'toplay'} eq 'W') {
606 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
608 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
610 if (exists($id->{'name'})) {
615 if (exists($id->{'name'})) {
616 $text .= " by $id->{'name'}:\n\n";
621 return unless (exists($pos_calculating->{'board'}));
623 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
626 while (exists($info->{'pv' . $mpv})) {
627 $text .= sprintf " PV%2u", $mpv;
628 my $score = short_score($info, $pos_calculating, $mpv);
629 $text .= " ($score)" if (defined($score));
632 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
633 if ($info->{'tbhits' . $mpv} == 1) {
634 $tbhits = ", 1 tbhit";
636 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
640 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
641 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
642 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
646 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
652 my $score = long_score($info, $pos_calculating, '');
653 $text .= " $score\n" if defined($score);
654 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
657 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
658 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
659 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
661 if (exists($info->{'seldepth'})) {
662 $text .= sprintf " (%u selective)", $info->{'seldepth'};
664 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
665 if ($info->{'tbhits'} == 1) {
666 $text .= ", one Syzygy hit";
668 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
674 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
676 my @refutation_lines = ();
677 if (defined($engine2)) {
678 for (my $mpv = 1; $mpv < 500; ++$mpv) {
679 my $info = $engine2->{'info'};
680 last if (!exists($info->{'pv' . $mpv}));
682 my $pv = $info->{'pv' . $mpv};
684 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
685 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
686 if (scalar @pretty_pv > 5) {
687 @pretty_pv = @pretty_pv[0..4];
688 push @pretty_pv, "...";
690 my $key = $pretty_move;
691 my $line = sprintf(" %-6s %6s %3s %s",
693 short_score($info, $pos_calculating_second_engine, $mpv),
694 "d" . $info->{'depth' . $mpv},
695 join(', ', @pretty_pv));
696 push @refutation_lines, [ $key, $line ];
701 if ($#refutation_lines >= 0) {
702 $text .= "Shallow search of all legal moves:\n\n";
703 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
704 $text .= $line->[1] . "\n";
709 if ($last_text ne $text) {
710 print "
\e[H
\e[2J"; # clear the screen
717 my $historic_json_only = shift;
718 my $info = $engine->{'info'};
721 $json->{'position'} = $pos_calculating->to_json_hash();
722 $json->{'id'} = $engine->{'id'};
723 $json->{'score'} = long_score($info, $pos_calculating, '');
724 $json->{'short_score'} = short_score($info, $pos_calculating, '');
726 $json->{'nodes'} = $info->{'nodes'};
727 $json->{'nps'} = $info->{'nps'};
728 $json->{'depth'} = $info->{'depth'};
729 $json->{'tbhits'} = $info->{'tbhits'};
730 $json->{'seldepth'} = $info->{'seldepth'};
731 $json->{'tablebase'} = $info->{'tablebase'};
733 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
734 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
736 my %refutation_lines = ();
737 my @refutation_lines = ();
738 if (defined($engine2)) {
739 for (my $mpv = 1; $mpv < 500; ++$mpv) {
740 my $info = $engine2->{'info'};
741 my $pretty_move = "";
743 last if (!exists($info->{'pv' . $mpv}));
746 my $pv = $info->{'pv' . $mpv};
747 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
748 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
749 $refutation_lines{$pv->[0]} = {
750 sort_key => $pretty_move,
751 depth => $info->{'depth' . $mpv},
752 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
753 pretty_score => short_score($info, $pos_calculating, $mpv),
754 pretty_move => $pretty_move,
755 pv_pretty => \@pretty_pv,
760 $json->{'refutation_lines'} = \%refutation_lines;
762 my $encoded = JSON::XS::encode_json($json);
763 unless ($historic_json_only) {
764 atomic_set_contents($remoteglotconf::json_output, $encoded);
767 if (exists($pos_calculating->{'pretty_history'}) &&
768 defined($remoteglotconf::json_history_dir)) {
769 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
771 # Overwrite old analysis (assuming it exists at all) if we're
772 # using a different engine, or if we've calculated deeper.
773 # nodes is used as a tiebreaker. Don't bother about Multi-PV
774 # data; it's not that important.
775 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
776 my $new_depth = $json->{'depth'} // 0;
777 my $new_nodes = $json->{'nodes'} // 0;
778 if (!defined($old_engine) ||
779 $old_engine ne $json->{'id'}{'name'} ||
780 $new_depth > $old_depth ||
781 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
782 atomic_set_contents($filename, $encoded);
787 sub atomic_set_contents {
788 my ($filename, $contents) = @_;
790 open my $fh, ">", $filename . ".tmp"
794 rename($filename . ".tmp", $filename);
800 my $halfmove_num = scalar @{$pos->{'pretty_history'}};
801 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
802 return "move$halfmove_num-$fen";
805 sub get_json_analysis_stats {
806 my $filename = shift;
808 my ($engine, $depth, $nodes);
810 open my $fh, "<", $filename
814 my $json = JSON::XS::decode_json(<$fh>);
815 $engine = $json->{'id'}{'name'} // die;
816 $depth = $json->{'depth'} // 0;
817 $nodes = $json->{'nodes'} // 0;
821 warn "Error in decoding $filename: $@";
824 return ($engine, $depth, $nodes);
828 my ($engine, $msg) = @_;
829 $engine->print($msg);
830 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
834 my ($info, $pos, $mpv) = @_;
836 my $invert = ($pos->{'toplay'} eq 'B');
837 if (defined($info->{'score_mate' . $mpv})) {
839 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
841 return sprintf "M%3d", $info->{'score_mate' . $mpv};
844 if (exists($info->{'score_cp' . $mpv})) {
845 my $score = $info->{'score_cp' . $mpv} * 0.01;
847 if ($info->{'tablebase'}) {
856 return sprintf "%+5.2f", $score;
864 my ($info, $pos, $mpv, $invert) = @_;
866 if (defined($info->{'score_mate' . $mpv})) {
867 my $mate = $info->{'score_mate' . $mpv};
871 $score = 99999 - $mate;
873 # Side to move is getting mated (note the double negative for $mate)
874 $score = -99999 - $mate;
881 if (exists($info->{'score_cp' . $mpv})) {
882 my $score = $info->{'score_cp' . $mpv};
894 my ($info, $pos, $mpv) = @_;
896 if (defined($info->{'score_mate' . $mpv})) {
897 my $mate = $info->{'score_mate' . $mpv};
898 if ($pos->{'toplay'} eq 'B') {
902 return sprintf "White mates in %u", $mate;
904 return sprintf "Black mates in %u", -$mate;
907 if (exists($info->{'score_cp' . $mpv})) {
908 my $score = $info->{'score_cp' . $mpv} * 0.01;
910 if ($info->{'tablebase'}) {
911 return "Theoretical draw";
913 return "Score: 0.00";
916 if ($pos->{'toplay'} eq 'B') {
919 return sprintf "Score: %+5.2f", $score;
928 my ($fen, $board, $toplay) = @_;
930 if (exists($book_cache{$fen})) {
931 return $book_cache{$fen};
934 my $ret = `./booklook $fen`;
935 return "" if ($ret =~ /Not found/ || $ret eq '');
939 for my $m (split /\n/, $ret) {
940 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
944 $pmove = '(current)';
946 ($pmove) = prettyprint_pv_no_cache($board, $move);
947 $pmove .= $annotation;
951 if ($toplay eq 'W') {
952 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
954 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
956 my $n = $win + $draw + $lose;
962 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
965 push @moves, [ $pmove, $n, $percent, $rating ];
968 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
970 my $text = "Book moves:\n\n Perf. N Rating\n\n";
972 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
979 my ($pgn, $pos) = @_;
981 # Look for extended PGN clock tags.
982 my $tags = $pgn->tags;
983 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
984 $pos->{'white_clock'} = $tags->{'WhiteClock'};
985 $pos->{'black_clock'} = $tags->{'BlackClock'};
989 # Look for TCEC-style time comments.
990 my $moves = $pgn->moves;
991 my $comments = $pgn->comments;
992 my $last_black_move = int((scalar @$moves) / 2);
993 my $last_white_move = int((1 + scalar @$moves) / 2);
995 my $black_key = $last_black_move . "b";
996 my $white_key = $last_white_move . "w";
998 if (exists($comments->{$white_key}) &&
999 exists($comments->{$black_key}) &&
1000 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/ &&
1001 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/) {
1002 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/;
1003 $pos->{'white_clock'} = $1;
1004 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/;
1005 $pos->{'black_clock'} = $1;
1010 sub find_clock_start {
1013 # If the game is over, the clock is stopped.
1014 if ($pos->{'result'} eq '1-0' ||
1015 $pos->{'result'} eq '1/2-1/2' ||
1016 $pos->{'result'} eq '0-1') {
1020 # When we don't have any moves, we assume the clock hasn't started yet.
1021 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1025 my $id = id_for_pos($pos);
1026 if (exists($clock_target_for_pos{$id})) {
1027 if ($pos->{'toplay'} eq 'W') {
1028 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1030 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1035 # OK, we haven't seen this position before, so we assume the move
1036 # happened right now.
1037 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1038 if (!exists($pos->{$key})) {
1039 # No clock information.
1042 $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
1043 my $time_left = $1 * 3600 + $2 * 60 + $3;
1044 $clock_target_for_pos{$id} = time + $time_left;
1045 if ($pos->{'toplay'} eq 'W') {
1046 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1048 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1052 sub schedule_tb_lookup {
1053 return if (!defined($remoteglotconf::tb_serial_key));
1054 my $pos = $pos_waiting // $pos_calculating;
1055 return if (exists($tb_cache{$pos->fen()}));
1057 # If there's more than seven pieces, there's not going to be an answer,
1059 return if ($pos->num_pieces() > 7);
1061 # Max one at a time. If it's still relevant when it returns,
1062 # schedule_tb_lookup() will be called again.
1063 return if ($tb_lookup_running);
1065 $tb_lookup_running = 1;
1066 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1067 $remoteglotconf::tb_serial_key .
1068 '&auth.password=aquarium&type=0&fen=' .
1069 URI::Escape::uri_escape($pos->fen());
1070 print TBLOG "Downloading $url...\n";
1071 AnyEvent::HTTP::http_get($url, sub {
1072 handle_tb_lookup_return(@_, $pos, $pos->fen());
1076 sub handle_tb_lookup_return {
1077 my ($body, $header, $pos, $fen) = @_;
1078 print TBLOG "Response for [$fen]:\n";
1079 print TBLOG $header . "\n\n";
1080 print TBLOG $body . "\n\n";
1082 my $response = JSON::XS::decode_json($body);
1083 if ($response->{'ErrorCode'} != 0) {
1084 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1086 my $state = $response->{'Response'}{'StateString'};
1087 if ($state eq 'COMPLETE') {
1088 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1089 if (!defined($pgn) || !$pgn->read_game()) {
1090 warn "Error in parsing PGN\n";
1092 $pgn->quick_parse_game;
1094 my $moves = $pgn->moves;
1096 for my $move (@$moves) {
1098 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1099 push @uci_moves, $uci_move;
1102 result => $pgn->result,
1104 score => $response->{'Response'}{'Score'},
1108 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1109 # Try again in a second. Note that if we have changed
1110 # position in the meantime, we might query a completely
1111 # different position! But that's fine.
1113 die "Unknown response state " . $state;
1116 # Wait a second before we schedule another one.
1117 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1118 $tb_lookup_running = 0;
1119 schedule_tb_lookup();
1123 warn "Error in tablebase lookup: $@";
1125 # Don't try this one again, but don't block new lookups either.
1126 $tb_lookup_running = 0;
1131 my ($cmdline, $tag, $cb) = @_;
1132 return undef if (!defined($cmdline));
1133 return Engine->open($cmdline, $tag, $cb);
1136 sub col_letter_to_num {
1137 return ord(shift) - ord('a');
1140 sub row_letter_to_num {
1141 return 7 - (ord(shift) - ord('1'));
1144 sub parse_uci_move {
1146 my $from_col = col_letter_to_num(substr($move, 0, 1));
1147 my $from_row = row_letter_to_num(substr($move, 1, 1));
1148 my $to_col = col_letter_to_num(substr($move, 2, 1));
1149 my $to_row = row_letter_to_num(substr($move, 3, 1));
1150 my $promo = substr($move, 4, 1);
1151 return ($from_col, $from_row, $to_col, $to_row, $promo);