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;
24 require 'Position.pm';
32 my $latest_update = undef;
33 my $output_timer = undef;
34 my $http_timer = undef;
35 my $stop_pgn_fetch = 0;
36 my $tb_retry_timer = undef;
38 my $tb_lookup_running = 0;
39 my $last_written_json = undef;
41 # Persisted so that we can restart.
42 tie my %clock_info_for_pos, 'Tie::Persistent', 'clock_info.db', 'rw';
43 (tied %clock_info_for_pos)->autosync(1);
45 tie my %json_for_pos, 'Tie::Persistent', 'analysis_info.db', 'rw';
46 (tied %json_for_pos)->autosync(1);
50 open(FICSLOG, ">ficslog.txt")
51 or die "ficslog.txt: $!";
52 print FICSLOG "Log starting.\n";
56 open(UCILOG, ">ucilog.txt")
57 or die "ucilog.txt: $!";
58 print UCILOG "Log starting.\n";
62 open(TBLOG, ">tblog.txt")
63 or die "tblog.txt: $!";
64 print TBLOG "Log starting.\n";
70 # open the chess engine
71 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
72 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
75 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
77 uciprint($engine, "setoption name UCI_AnalyseMode value true");
78 while (my ($key, $value) = each %remoteglotconf::engine_config) {
79 uciprint($engine, "setoption name $key value $value");
81 uciprint($engine, "ucinewgame");
83 if (defined($engine2)) {
84 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
85 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
86 uciprint($engine2, "setoption name $key value $value");
88 uciprint($engine2, "setoption name MultiPV value 500");
89 uciprint($engine2, "ucinewgame");
92 print "Chess engine ready.\n";
95 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
96 $t->input_log(\*FICSLOG);
97 $t->open($remoteglotconf::server);
98 $t->print($remoteglotconf::nick);
99 $t->waitfor('/Press return to enter the server/');
103 $t->cmd("set shout 0");
104 $t->cmd("set seek 0");
105 $t->cmd("set style 12");
107 my $ev1 = AnyEvent->io(
110 cb => sub { # what callback to execute
112 my $line = $t->getline(Timeout => 0, errmode => 'return');
113 return if (!defined($line));
121 if (defined($remoteglotconf::target)) {
122 if ($remoteglotconf::target =~ /^http:/) {
123 fetch_pgn($remoteglotconf::target);
125 $t->cmd("observe $remoteglotconf::target");
128 print "FICS ready.\n";
130 # Engine events have already been set up by Engine.pm.
134 my ($engine, $line, $primary) = @_;
136 return if $line =~ /(upper|lower)bound/;
138 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
139 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
140 if ($line =~ /^info/) {
141 my (@infos) = split / /, $line;
144 parse_infos($engine, @infos);
146 if ($line =~ /^id/) {
147 my (@ids) = split / /, $line;
150 parse_ids($engine, @ids);
152 if ($line =~ /^bestmove/) {
154 return if (!$remoteglotconf::uci_assume_full_compliance);
155 if (defined($pos_waiting)) {
156 uciprint($engine, "position fen " . $pos_waiting->fen());
157 uciprint($engine, "go infinite");
159 $pos_calculating = $pos_waiting;
160 $pos_waiting = undef;
163 $engine2->{'info'} = {};
164 my $pos = $pos_waiting // $pos_calculating;
165 uciprint($engine2, "position fen " . $pos->fen());
166 uciprint($engine2, "go infinite");
167 $pos_calculating_second_engine = $pos;
173 my $getting_movelist = 0;
174 my $pos_for_movelist = undef;
175 my @uci_movelist = ();
176 my @pretty_movelist = ();
180 if ($line =~ /^<12> /) {
181 handle_position(Position->new($line));
184 if ($line =~ /^Movelist for game /) {
185 my $pos = $pos_waiting // $pos_calculating;
188 @pretty_movelist = ();
189 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
190 $getting_movelist = 1;
193 if ($getting_movelist &&
194 $line =~ /^\s* \d+\. \s+ # move number
195 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
196 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
200 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
201 push @uci_movelist, $uci_move;
202 push @pretty_movelist, $1;
205 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
206 push @uci_movelist, $uci_move;
207 push @pretty_movelist, $2;
211 warn "Error when getting FICS move history: $@";
212 $getting_movelist = 0;
215 if ($getting_movelist &&
216 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
218 for my $pos ($pos_waiting, $pos_calculating) {
219 next if (!defined($pos));
220 if ($pos->fen() eq $pos_for_movelist->fen()) {
221 $pos->{'pretty_history'} = \@pretty_movelist;
224 $getting_movelist = 0;
226 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
227 my ($who, $msg) = ($1, $2);
229 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
231 if ($msg =~ /^fics (.*?)$/) {
232 $t->cmd("tell $who Executing '$1' on FICS.");
234 } elsif ($msg =~ /^uci (.*?)$/) {
235 $t->cmd("tell $who Sending '$1' to the engine.");
236 print { $engine->{'write'} } "$1\n";
237 } elsif ($msg =~ /^pgn (.*?)$/) {
239 $t->cmd("tell $who Starting to poll '$url'.");
241 } elsif ($msg =~ /^stoppgn$/) {
242 $t->cmd("tell $who Stopping poll.");
245 } elsif ($msg =~ /^quit$/) {
246 $t->cmd("tell $who Bye bye.");
249 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
252 #print "FICS: [$line]\n";
255 # Starts periodic fetching of PGNs from the given URL.
258 AnyEvent::HTTP::http_get($url, sub {
259 handle_pgn(@_, $url);
263 my ($last_pgn_white, $last_pgn_black);
264 my @last_pgn_uci_moves = ();
265 my $pgn_hysteresis_counter = 0;
268 my ($body, $header, $url) = @_;
270 if ($stop_pgn_fetch) {
276 my $pgn = Chess::PGN::Parse->new(undef, $body);
277 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
278 warn "Error in parsing PGN from $url\n";
281 # Skip to the right game.
282 while (defined($remoteglotconf::pgn_filter) &&
283 !&$remoteglotconf::pgn_filter($pgn)) {
284 $pgn->read_game() or die "Out of games during filtering";
287 $pgn->parse_game({ save_comments => 'yes' });
288 my $pos = Position->start_pos($pgn->white, $pgn->black);
289 my $moves = $pgn->moves;
291 for my $move (@$moves) {
293 ($pos, $uci_move) = $pos->make_pretty_move($move);
294 push @uci_moves, $uci_move;
296 $pos->{'result'} = $pgn->result;
297 $pos->{'pretty_history'} = $moves;
299 extract_clock($pgn, $pos);
301 # Sometimes, PGNs lose a move or two for a short while,
302 # or people push out new ones non-atomically.
303 # Thus, if we PGN doesn't change names but becomes
304 # shorter, we mistrust it for a few seconds.
306 if (defined($last_pgn_white) && defined($last_pgn_black) &&
307 $last_pgn_white eq $pgn->white &&
308 $last_pgn_black eq $pgn->black &&
309 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
310 if (++$pgn_hysteresis_counter < 3) {
315 $last_pgn_white = $pgn->white;
316 $last_pgn_black = $pgn->black;
317 @last_pgn_uci_moves = @uci_moves;
318 $pgn_hysteresis_counter = 0;
319 handle_position($pos);
323 warn "Error in parsing moves from $url: $@\n";
327 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
332 sub handle_position {
334 find_clock_start($pos, $pos_calculating);
336 # if this is already in the queue, ignore it (just update the result)
337 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
338 $pos_waiting->{'result'} = $pos->{'result'};
342 # if we're already chewing on this and there's nothing else in the queue,
344 if (!defined($pos_waiting) && defined($pos_calculating) &&
345 $pos->fen() eq $pos_calculating->fen()) {
346 $pos_calculating->{'result'} = $pos->{'result'};
350 # if we're already thinking on something, stop and wait for the engine
352 if (defined($pos_calculating)) {
353 # Store the final data we have for this position in the history,
354 # with the precise clock information we just got from the new
355 # position. (Historic positions store the clock at the end of
358 # Do not output anything new to the main analysis; that's
359 # going to be obsolete really soon.
360 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
361 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
362 delete $pos_calculating->{'white_clock_target'};
363 delete $pos_calculating->{'black_clock_target'};
366 if (!defined($pos_waiting)) {
367 uciprint($engine, "stop");
369 if ($remoteglotconf::uci_assume_full_compliance) {
372 uciprint($engine, "position fen " . $pos->fen());
373 uciprint($engine, "go infinite");
374 $pos_calculating = $pos;
377 # it's wrong just to give the FEN (the move history is useful,
378 # and per the UCI spec, we should really have sent "ucinewgame"),
380 uciprint($engine, "position fen " . $pos->fen());
381 uciprint($engine, "go infinite");
382 $pos_calculating = $pos;
385 if (defined($engine2)) {
386 if (defined($pos_calculating_second_engine)) {
387 uciprint($engine2, "stop");
389 uciprint($engine2, "position fen " . $pos->fen());
390 uciprint($engine2, "go infinite");
391 $pos_calculating_second_engine = $pos;
393 $engine2->{'info'} = {};
396 $engine->{'info'} = {};
399 schedule_tb_lookup();
402 # Output a command every move to note that we're
403 # still paying attention -- this is a good tradeoff,
404 # since if no move has happened in the last half
405 # hour, the analysis/relay has most likely stopped
406 # and we should stop hogging server resources.
412 my ($engine, @x) = @_;
415 my $info = $engine->{'info'};
417 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
418 for my $i (0..$#x - 1) {
419 if ($x[$i] eq 'multipv') {
425 while (scalar @x > 0) {
426 if ($x[0] eq 'multipv') {
432 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
434 my $value = shift @x;
435 $info->{$key} = $value;
438 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
439 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
442 my $value = shift @x;
443 $info->{$key . $mpv} = $value;
446 if ($x[0] eq 'score') {
449 delete $info->{'score_cp' . $mpv};
450 delete $info->{'score_mate' . $mpv};
452 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
455 $info->{'score_cp' . $mpv} = shift @x;
456 } elsif ($x[0] eq 'mate') {
458 $info->{'score_mate' . $mpv} = shift @x;
466 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
469 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
473 #print "unknown info '$x[0]', trying to recover...\n";
475 die "Unknown info '" . join(',', @x) . "'";
481 my ($engine, @x) = @_;
483 while (scalar @x > 0) {
484 if ($x[0] =~ /^(name|author)$/) {
486 my $value = join(' ', @x);
487 $engine->{'id'}{$key} = $value;
496 sub prettyprint_pv_no_cache {
497 my ($board, @pvs) = @_;
499 if (scalar @pvs == 0 || !defined($pvs[0])) {
504 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
505 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
506 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
510 my ($pos, @pvs) = @_;
512 my $cachekey = join('', @pvs);
513 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
514 return @{$pos->{'prettyprint_cache'}{$cachekey}};
516 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
517 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
525 return if (!defined($pos_calculating));
527 # Don't update too often.
528 my $age = Time::HiRes::tv_interval($latest_update);
529 if ($age < $remoteglotconf::update_max_interval) {
530 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
531 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
535 my $info = $engine->{'info'};
538 # If we have tablebase data from a previous lookup, replace the
539 # engine data with the data from the tablebase.
541 my $fen = $pos_calculating->fen();
542 if (exists($tb_cache{$fen})) {
543 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
544 delete $info->{$key . '1'};
545 delete $info->{$key};
547 $info->{'nodes'} = 0;
549 $info->{'depth'} = 0;
550 $info->{'seldepth'} = 0;
551 $info->{'tbhits'} = 0;
553 my $t = $tb_cache{$fen};
555 my $matelen = int((1 + $t->{'score'}) / 2);
556 if ($t->{'result'} eq '1/2-1/2') {
557 $info->{'score_cp'} = 0;
558 } elsif ($t->{'result'} eq '1-0') {
559 if ($pos_calculating->{'toplay'} eq 'B') {
560 $info->{'score_mate'} = -$matelen;
562 $info->{'score_mate'} = $matelen;
565 if ($pos_calculating->{'toplay'} eq 'B') {
566 $info->{'score_mate'} = $matelen;
568 $info->{'score_mate'} = -$matelen;
572 $info->{'tablebase'} = 1;
574 $info->{'tablebase'} = 0;
578 # Some programs _always_ report MultiPV, even with only one PV.
579 # In this case, we simply use that data as if MultiPV was never
582 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
583 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
584 if (exists($info->{$key . '1'})) {
585 $info->{$key} = $info->{$key . '1'};
591 # Check the PVs first. if they're invalid, just wait, as our data
592 # is most likely out of sync. This isn't a very good solution, as
593 # it can frequently miss stuff, but it's good enough for most users.
597 if (exists($info->{'pv'})) {
598 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
602 while (exists($info->{'pv' . $mpv})) {
603 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
608 $engine->{'info'} = {};
614 $latest_update = [Time::HiRes::gettimeofday];
618 my $info = $engine->{'info'};
619 my $id = $engine->{'id'};
621 my $text = 'Analysis';
622 if ($pos_calculating->{'last_move'} ne 'none') {
623 if ($pos_calculating->{'toplay'} eq 'W') {
624 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
626 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
628 if (exists($id->{'name'})) {
633 if (exists($id->{'name'})) {
634 $text .= " by $id->{'name'}:\n\n";
639 return unless (exists($pos_calculating->{'board'}));
641 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
644 while (exists($info->{'pv' . $mpv})) {
645 $text .= sprintf " PV%2u", $mpv;
646 my $score = short_score($info, $pos_calculating, $mpv);
647 $text .= " ($score)" if (defined($score));
650 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
651 if ($info->{'tbhits' . $mpv} == 1) {
652 $tbhits = ", 1 tbhit";
654 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
658 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
659 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
660 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
664 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
670 my $score = long_score($info, $pos_calculating, '');
671 $text .= " $score\n" if defined($score);
672 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
675 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
676 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
677 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
679 if (exists($info->{'seldepth'})) {
680 $text .= sprintf " (%u selective)", $info->{'seldepth'};
682 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
683 if ($info->{'tbhits'} == 1) {
684 $text .= ", one Syzygy hit";
686 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
692 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
694 my @refutation_lines = ();
695 if (defined($engine2)) {
696 for (my $mpv = 1; $mpv < 500; ++$mpv) {
697 my $info = $engine2->{'info'};
698 last if (!exists($info->{'pv' . $mpv}));
700 my $pv = $info->{'pv' . $mpv};
702 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
703 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
704 if (scalar @pretty_pv > 5) {
705 @pretty_pv = @pretty_pv[0..4];
706 push @pretty_pv, "...";
708 my $key = $pretty_move;
709 my $line = sprintf(" %-6s %6s %3s %s",
711 short_score($info, $pos_calculating_second_engine, $mpv),
712 "d" . $info->{'depth' . $mpv},
713 join(', ', @pretty_pv));
714 push @refutation_lines, [ $key, $line ];
719 if ($#refutation_lines >= 0) {
720 $text .= "Shallow search of all legal moves:\n\n";
721 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
722 $text .= $line->[1] . "\n";
727 if ($last_text ne $text) {
728 print "
\e[H
\e[2J"; # clear the screen
735 my $historic_json_only = shift;
736 my $info = $engine->{'info'};
739 $json->{'position'} = $pos_calculating->to_json_hash();
740 $json->{'id'} = $engine->{'id'};
741 $json->{'score'} = long_score($info, $pos_calculating, '');
742 $json->{'short_score'} = short_score($info, $pos_calculating, '');
743 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
745 $json->{'nodes'} = $info->{'nodes'};
746 $json->{'nps'} = $info->{'nps'};
747 $json->{'depth'} = $info->{'depth'};
748 $json->{'tbhits'} = $info->{'tbhits'};
749 $json->{'seldepth'} = $info->{'seldepth'};
750 $json->{'tablebase'} = $info->{'tablebase'};
752 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
753 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
755 my %refutation_lines = ();
756 my @refutation_lines = ();
757 if (defined($engine2)) {
758 for (my $mpv = 1; $mpv < 500; ++$mpv) {
759 my $info = $engine2->{'info'};
760 my $pretty_move = "";
762 last if (!exists($info->{'pv' . $mpv}));
765 my $pv = $info->{'pv' . $mpv};
766 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
767 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
768 $refutation_lines{$pv->[0]} = {
769 sort_key => $pretty_move,
770 depth => $info->{'depth' . $mpv},
771 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
772 pretty_score => short_score($info, $pos_calculating, $mpv),
773 pretty_move => $pretty_move,
774 pv_pretty => \@pretty_pv,
779 $json->{'refutation_lines'} = \%refutation_lines;
781 # Piece together historic score information, to the degree we have it.
782 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
783 my %score_history = ();
785 my $pos = Position->start_pos('white', 'black');
786 my $halfmove_num = 0;
787 for my $move (@{$pos_calculating->{'pretty_history'}}) {
788 my $id = id_for_pos($pos, $halfmove_num);
789 if (exists($json_for_pos{$id}) && defined($json_for_pos{$id}->{'plot_score'})) {
790 $score_history{$halfmove_num} = [
791 $json_for_pos{$id}->{'plot_score'},
792 $json_for_pos{$id}->{'short_score'}
796 ($pos) = $pos->make_pretty_move($move);
799 # If at any point we are missing 10 consecutive moves,
800 # truncate the history there. This is so we don't get into
801 # a situation where we e.g. start analyzing at move 45,
802 # but we have analysis for 1. e4 from some completely different game
803 # and thus show a huge hole.
804 my $consecutive_missing = 0;
805 my $truncate_until = 0;
806 for (my $i = $halfmove_num; $i --> 0; ) {
807 if ($consecutive_missing >= 10) {
808 delete $score_history{$i};
811 if (exists($score_history{$i})) {
812 $consecutive_missing = 0;
814 ++$consecutive_missing;
818 $json->{'score_history'} = \%score_history;
821 my $json_enc = JSON::XS->new;
822 $json_enc->canonical(1);
823 my $encoded = $json_enc->encode($json);
824 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
825 (defined($last_written_json) && $last_written_json eq $encoded)) {
826 atomic_set_contents($remoteglotconf::json_output, $encoded);
827 $last_written_json = $encoded;
830 if (exists($pos_calculating->{'pretty_history'}) &&
831 defined($remoteglotconf::json_history_dir)) {
832 my $id = id_for_pos($pos_calculating);
833 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
835 # Overwrite old analysis (assuming it exists at all) if we're
836 # using a different engine, or if we've calculated deeper.
837 # nodes is used as a tiebreaker. Don't bother about Multi-PV
838 # data; it's not that important.
839 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
840 my $new_depth = $json->{'depth'} // 0;
841 my $new_nodes = $json->{'nodes'} // 0;
842 if (!defined($old_engine) ||
843 $old_engine ne $json->{'id'}{'name'} ||
844 $new_depth > $old_depth ||
845 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
846 atomic_set_contents($filename, $encoded);
847 $json_for_pos{$id} = $json;
852 sub atomic_set_contents {
853 my ($filename, $contents) = @_;
855 open my $fh, ">", $filename . ".tmp"
859 rename($filename . ".tmp", $filename);
863 my ($pos, $halfmove_num) = @_;
865 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
866 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
867 return "move$halfmove_num-$fen";
870 sub get_json_analysis_stats {
871 my $filename = shift;
873 my ($engine, $depth, $nodes);
875 open my $fh, "<", $filename
879 my $json = JSON::XS::decode_json(<$fh>);
880 $engine = $json->{'id'}{'name'} // die;
881 $depth = $json->{'depth'} // 0;
882 $nodes = $json->{'nodes'} // 0;
886 warn "Error in decoding $filename: $@";
889 return ($engine, $depth, $nodes);
893 my ($engine, $msg) = @_;
894 $engine->print($msg);
895 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
899 my ($info, $pos, $mpv) = @_;
901 my $invert = ($pos->{'toplay'} eq 'B');
902 if (defined($info->{'score_mate' . $mpv})) {
904 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
906 return sprintf "M%3d", $info->{'score_mate' . $mpv};
909 if (exists($info->{'score_cp' . $mpv})) {
910 my $score = $info->{'score_cp' . $mpv} * 0.01;
912 if ($info->{'tablebase'}) {
921 return sprintf "%+5.2f", $score;
929 my ($info, $pos, $mpv, $invert) = @_;
931 if (defined($info->{'score_mate' . $mpv})) {
932 my $mate = $info->{'score_mate' . $mpv};
936 $score = 99999 - $mate;
938 # Side to move is getting mated (note the double negative for $mate)
939 $score = -99999 - $mate;
946 if (exists($info->{'score_cp' . $mpv})) {
947 my $score = $info->{'score_cp' . $mpv};
959 my ($info, $pos, $mpv) = @_;
961 if (defined($info->{'score_mate' . $mpv})) {
962 my $mate = $info->{'score_mate' . $mpv};
963 if ($pos->{'toplay'} eq 'B') {
967 return sprintf "White mates in %u", $mate;
969 return sprintf "Black mates in %u", -$mate;
972 if (exists($info->{'score_cp' . $mpv})) {
973 my $score = $info->{'score_cp' . $mpv} * 0.01;
975 if ($info->{'tablebase'}) {
976 return "Theoretical draw";
978 return "Score: 0.00";
981 if ($pos->{'toplay'} eq 'B') {
984 return sprintf "Score: %+5.2f", $score;
991 # For graphs; a single number in centipawns, capped at +/- 500.
993 my ($info, $pos, $mpv) = @_;
995 my $invert = ($pos->{'toplay'} eq 'B');
996 if (defined($info->{'score_mate' . $mpv})) {
997 my $mate = $info->{'score_mate' . $mpv};
1007 if (exists($info->{'score_cp' . $mpv})) {
1008 my $score = $info->{'score_cp' . $mpv};
1012 $score = 500 if ($score > 500);
1013 $score = -500 if ($score < -500);
1021 my %book_cache = ();
1023 my ($fen, $board, $toplay) = @_;
1025 if (exists($book_cache{$fen})) {
1026 return $book_cache{$fen};
1029 my $ret = `./booklook $fen`;
1030 return "" if ($ret =~ /Not found/ || $ret eq '');
1034 for my $m (split /\n/, $ret) {
1035 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1039 $pmove = '(current)';
1041 ($pmove) = prettyprint_pv_no_cache($board, $move);
1042 $pmove .= $annotation;
1046 if ($toplay eq 'W') {
1047 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1049 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1051 my $n = $win + $draw + $lose;
1057 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1060 push @moves, [ $pmove, $n, $percent, $rating ];
1063 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1065 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1066 for my $m (@moves) {
1067 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1074 my ($pgn, $pos) = @_;
1076 # Look for extended PGN clock tags.
1077 my $tags = $pgn->tags;
1078 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1079 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1080 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1084 # Look for TCEC-style time comments.
1085 my $moves = $pgn->moves;
1086 my $comments = $pgn->comments;
1087 my $last_black_move = int((scalar @$moves) / 2);
1088 my $last_white_move = int((1 + scalar @$moves) / 2);
1090 my $black_key = $last_black_move . "b";
1091 my $white_key = $last_white_move . "w";
1093 if (exists($comments->{$white_key}) &&
1094 exists($comments->{$black_key}) &&
1095 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1096 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1097 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1098 $pos->{'white_clock'} = hms_to_sec($1);
1099 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1100 $pos->{'black_clock'} = hms_to_sec($1);
1104 delete $pos->{'white_clock'};
1105 delete $pos->{'black_clock'};
1110 return undef if (!defined($hms));
1111 $hms =~ /(\d+):(\d+):(\d+)/;
1112 return $1 * 3600 + $2 * 60 + $3;
1115 sub find_clock_start {
1116 my ($pos, $prev_pos) = @_;
1118 # If the game is over, the clock is stopped.
1119 if (exists($pos->{'result'}) &&
1120 ($pos->{'result'} eq '1-0' ||
1121 $pos->{'result'} eq '1/2-1/2' ||
1122 $pos->{'result'} eq '0-1')) {
1126 # When we don't have any moves, we assume the clock hasn't started yet.
1127 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1128 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1129 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1134 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1135 # The history is needed for id_for_pos.
1136 if (!exists($pos->{'pretty_history'})) {
1140 my $id = id_for_pos($pos);
1141 if (exists($clock_info_for_pos{$id})) {
1142 $pos->{'white_clock'} //= $clock_info_for_pos{$id}{'white_clock'};
1143 $pos->{'black_clock'} //= $clock_info_for_pos{$id}{'black_clock'};
1144 if ($pos->{'toplay'} eq 'W') {
1145 $pos->{'white_clock_target'} = $clock_info_for_pos{$id}->{'white_clock_target'};
1147 $pos->{'black_clock_target'} = $clock_info_for_pos{$id}->{'black_clock_target'};
1152 # OK, we haven't seen this position before, so we assume the move
1153 # happened right now.
1155 # See if we should do our own clock management (ie., clock information
1156 # is spurious or non-existent).
1157 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1158 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1159 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1160 if (defined($prev_pos->{'white_clock_target'})) {
1161 $wc = $prev_pos->{'white_clock_target'} - time;
1163 if (defined($prev_pos->{'black_clock_target'})) {
1164 $bc = $prev_pos->{'black_clock_target'} - time;
1166 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1167 $pos->{'white_clock'} = $wc;
1168 $pos->{'black_clock'} = $bc;
1171 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1172 if (!exists($pos->{$key})) {
1173 # No clock information.
1176 my $time_left = $pos->{$key};
1178 white_clock => $pos->{'white_clock'},
1179 black_clock => $pos->{'black_clock'}
1181 if ($pos->{'toplay'} eq 'W') {
1182 $clock_info->{'white_clock_target'} = $pos->{'white_clock_target'} = time + $time_left;
1184 $clock_info->{'black_clock_target'} = $pos->{'black_clock_target'} = time + $time_left;
1186 $clock_info_for_pos{$id} = $clock_info;
1189 sub schedule_tb_lookup {
1190 return if (!defined($remoteglotconf::tb_serial_key));
1191 my $pos = $pos_waiting // $pos_calculating;
1192 return if (exists($tb_cache{$pos->fen()}));
1194 # If there's more than seven pieces, there's not going to be an answer,
1196 return if ($pos->num_pieces() > 7);
1198 # Max one at a time. If it's still relevant when it returns,
1199 # schedule_tb_lookup() will be called again.
1200 return if ($tb_lookup_running);
1202 $tb_lookup_running = 1;
1203 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1204 $remoteglotconf::tb_serial_key .
1205 '&auth.password=aquarium&type=0&fen=' .
1206 URI::Escape::uri_escape($pos->fen());
1207 print TBLOG "Downloading $url...\n";
1208 AnyEvent::HTTP::http_get($url, sub {
1209 handle_tb_lookup_return(@_, $pos, $pos->fen());
1213 sub handle_tb_lookup_return {
1214 my ($body, $header, $pos, $fen) = @_;
1215 print TBLOG "Response for [$fen]:\n";
1216 print TBLOG $header . "\n\n";
1217 print TBLOG $body . "\n\n";
1219 my $response = JSON::XS::decode_json($body);
1220 if ($response->{'ErrorCode'} != 0) {
1221 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1223 my $state = $response->{'Response'}{'StateString'};
1224 if ($state eq 'COMPLETE') {
1225 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1226 if (!defined($pgn) || !$pgn->read_game()) {
1227 warn "Error in parsing PGN\n";
1229 $pgn->quick_parse_game;
1231 my $moves = $pgn->moves;
1233 for my $move (@$moves) {
1235 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1236 push @uci_moves, $uci_move;
1239 result => $pgn->result,
1241 score => $response->{'Response'}{'Score'},
1245 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1246 # Try again in a second. Note that if we have changed
1247 # position in the meantime, we might query a completely
1248 # different position! But that's fine.
1250 die "Unknown response state " . $state;
1253 # Wait a second before we schedule another one.
1254 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1255 $tb_lookup_running = 0;
1256 schedule_tb_lookup();
1260 warn "Error in tablebase lookup: $@";
1262 # Don't try this one again, but don't block new lookups either.
1263 $tb_lookup_running = 0;
1268 my ($cmdline, $tag, $cb) = @_;
1269 return undef if (!defined($cmdline));
1270 return Engine->open($cmdline, $tag, $cb);
1273 sub col_letter_to_num {
1274 return ord(shift) - ord('a');
1277 sub row_letter_to_num {
1278 return 7 - (ord(shift) - ord('1'));
1281 sub parse_uci_move {
1283 my $from_col = col_letter_to_num(substr($move, 0, 1));
1284 my $from_row = row_letter_to_num(substr($move, 1, 1));
1285 my $to_col = col_letter_to_num(substr($move, 2, 1));
1286 my $to_row = row_letter_to_num(substr($move, 3, 1));
1287 my $promo = substr($move, 4, 1);
1288 return ($from_col, $from_row, $to_col, $to_row, $promo);