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;
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";
71 # open the chess engine
72 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
73 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
76 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
78 uciprint($engine, "setoption name UCI_AnalyseMode value true");
79 while (my ($key, $value) = each %remoteglotconf::engine_config) {
80 uciprint($engine, "setoption name $key value $value");
82 uciprint($engine, "ucinewgame");
84 if (defined($engine2)) {
85 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
86 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
87 uciprint($engine2, "setoption name $key value $value");
89 uciprint($engine2, "setoption name MultiPV value 500");
90 uciprint($engine2, "ucinewgame");
93 print "Chess engine ready.\n";
96 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
97 $t->input_log(\*FICSLOG);
98 $t->open($remoteglotconf::server);
99 $t->print($remoteglotconf::nick);
100 $t->waitfor('/Press return to enter the server/');
104 $t->cmd("set shout 0");
105 $t->cmd("set seek 0");
106 $t->cmd("set style 12");
108 my $ev1 = AnyEvent->io(
111 cb => sub { # what callback to execute
113 my $line = $t->getline(Timeout => 0, errmode => 'return');
114 return if (!defined($line));
122 if (defined($remoteglotconf::target)) {
123 if ($remoteglotconf::target =~ /^http:/) {
124 fetch_pgn($remoteglotconf::target);
126 $t->cmd("observe $remoteglotconf::target");
129 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";
141 if ($line =~ /^info/) {
142 my (@infos) = split / /, $line;
145 parse_infos($engine, @infos);
147 if ($line =~ /^id/) {
148 my (@ids) = split / /, $line;
151 parse_ids($engine, @ids);
153 if ($line =~ /^bestmove/) {
155 return if (!$remoteglotconf::uci_assume_full_compliance);
156 if (defined($pos_waiting)) {
157 uciprint($engine, "position fen " . $pos_waiting->fen());
158 uciprint($engine, "go infinite");
160 $pos_calculating = $pos_waiting;
161 $pos_waiting = undef;
164 $engine2->{'info'} = {};
165 my $pos = $pos_waiting // $pos_calculating;
166 uciprint($engine2, "position fen " . $pos->fen());
167 uciprint($engine2, "go infinite");
168 $pos_calculating_second_engine = $pos;
174 my $getting_movelist = 0;
175 my $pos_for_movelist = undef;
176 my @uci_movelist = ();
177 my @pretty_movelist = ();
181 if ($line =~ /^<12> /) {
182 handle_position(Position->new($line));
185 if ($line =~ /^Movelist for game /) {
186 my $pos = $pos_waiting // $pos_calculating;
189 @pretty_movelist = ();
190 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
191 $getting_movelist = 1;
194 if ($getting_movelist &&
195 $line =~ /^\s* \d+\. \s+ # move number
196 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
197 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
201 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
202 push @uci_movelist, $uci_move;
203 push @pretty_movelist, $1;
206 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
207 push @uci_movelist, $uci_move;
208 push @pretty_movelist, $2;
212 warn "Error when getting FICS move history: $@";
213 $getting_movelist = 0;
216 if ($getting_movelist &&
217 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
219 for my $pos ($pos_waiting, $pos_calculating) {
220 next if (!defined($pos));
221 if ($pos->fen() eq $pos_for_movelist->fen()) {
222 $pos->{'pretty_history'} = \@pretty_movelist;
225 $getting_movelist = 0;
227 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
228 my ($who, $msg) = ($1, $2);
230 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
232 if ($msg =~ /^fics (.*?)$/) {
233 $t->cmd("tell $who Executing '$1' on FICS.");
235 } elsif ($msg =~ /^uci (.*?)$/) {
236 $t->cmd("tell $who Sending '$1' to the engine.");
237 print { $engine->{'write'} } "$1\n";
238 } elsif ($msg =~ /^pgn (.*?)$/) {
240 $t->cmd("tell $who Starting to poll '$url'.");
242 } elsif ($msg =~ /^stoppgn$/) {
243 $t->cmd("tell $who Stopping poll.");
246 } elsif ($msg =~ /^quit$/) {
247 $t->cmd("tell $who Bye bye.");
250 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
253 #print "FICS: [$line]\n";
256 # Starts periodic fetching of PGNs from the given URL.
259 AnyEvent::HTTP::http_get($url, sub {
260 handle_pgn(@_, $url);
264 my ($last_pgn_white, $last_pgn_black);
265 my @last_pgn_uci_moves = ();
266 my $pgn_hysteresis_counter = 0;
269 my ($body, $header, $url) = @_;
271 if ($stop_pgn_fetch) {
277 my $pgn = Chess::PGN::Parse->new(undef, $body);
278 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
279 warn "Error in parsing PGN from $url\n";
282 # Skip to the right game.
283 while (defined($remoteglotconf::pgn_filter) &&
284 !&$remoteglotconf::pgn_filter($pgn)) {
285 $pgn->read_game() or die "Out of games during filtering";
288 $pgn->parse_game({ save_comments => 'yes' });
289 my $pos = Position->start_pos($pgn->white, $pgn->black);
290 my $moves = $pgn->moves;
292 for my $move (@$moves) {
294 ($pos, $uci_move) = $pos->make_pretty_move($move);
295 push @uci_moves, $uci_move;
297 $pos->{'result'} = $pgn->result;
298 $pos->{'pretty_history'} = $moves;
300 extract_clock($pgn, $pos);
302 # Sometimes, PGNs lose a move or two for a short while,
303 # or people push out new ones non-atomically.
304 # Thus, if we PGN doesn't change names but becomes
305 # shorter, we mistrust it for a few seconds.
307 if (defined($last_pgn_white) && defined($last_pgn_black) &&
308 $last_pgn_white eq $pgn->white &&
309 $last_pgn_black eq $pgn->black &&
310 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
311 if (++$pgn_hysteresis_counter < 3) {
316 $last_pgn_white = $pgn->white;
317 $last_pgn_black = $pgn->black;
318 @last_pgn_uci_moves = @uci_moves;
319 $pgn_hysteresis_counter = 0;
320 handle_position($pos);
324 warn "Error in parsing moves from $url: $@\n";
328 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
333 sub handle_position {
335 find_clock_start($pos, $pos_calculating);
337 # if this is already in the queue, ignore it (just update the result)
338 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
339 $pos_waiting->{'result'} = $pos->{'result'};
343 # if we're already chewing on this and there's nothing else in the queue,
345 if (!defined($pos_waiting) && defined($pos_calculating) &&
346 $pos->fen() eq $pos_calculating->fen()) {
347 $pos_calculating->{'result'} = $pos->{'result'};
351 # if we're already thinking on something, stop and wait for the engine
353 if (defined($pos_calculating)) {
354 # Store the final data we have for this position in the history,
355 # with the precise clock information we just got from the new
356 # position. (Historic positions store the clock at the end of
359 # Do not output anything new to the main analysis; that's
360 # going to be obsolete really soon.
361 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
362 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
363 delete $pos_calculating->{'white_clock_target'};
364 delete $pos_calculating->{'black_clock_target'};
367 if (!defined($pos_waiting)) {
368 uciprint($engine, "stop");
370 if ($remoteglotconf::uci_assume_full_compliance) {
373 uciprint($engine, "position fen " . $pos->fen());
374 uciprint($engine, "go infinite");
375 $pos_calculating = $pos;
378 # it's wrong just to give the FEN (the move history is useful,
379 # and per the UCI spec, we should really have sent "ucinewgame"),
381 uciprint($engine, "position fen " . $pos->fen());
382 uciprint($engine, "go infinite");
383 $pos_calculating = $pos;
386 if (defined($engine2)) {
387 if (defined($pos_calculating_second_engine)) {
388 uciprint($engine2, "stop");
390 uciprint($engine2, "position fen " . $pos->fen());
391 uciprint($engine2, "go infinite");
392 $pos_calculating_second_engine = $pos;
394 $engine2->{'info'} = {};
397 $engine->{'info'} = {};
400 schedule_tb_lookup();
403 # Output a command every move to note that we're
404 # still paying attention -- this is a good tradeoff,
405 # since if no move has happened in the last half
406 # hour, the analysis/relay has most likely stopped
407 # and we should stop hogging server resources.
413 my ($engine, @x) = @_;
416 my $info = $engine->{'info'};
418 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
419 for my $i (0..$#x - 1) {
420 if ($x[$i] eq 'multipv') {
426 while (scalar @x > 0) {
427 if ($x[0] eq 'multipv') {
433 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
435 my $value = shift @x;
436 $info->{$key} = $value;
439 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
440 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
443 my $value = shift @x;
444 $info->{$key . $mpv} = $value;
447 if ($x[0] eq 'score') {
450 delete $info->{'score_cp' . $mpv};
451 delete $info->{'score_mate' . $mpv};
453 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
456 $info->{'score_cp' . $mpv} = shift @x;
457 } elsif ($x[0] eq 'mate') {
459 $info->{'score_mate' . $mpv} = shift @x;
467 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
470 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
474 #print "unknown info '$x[0]', trying to recover...\n";
476 die "Unknown info '" . join(',', @x) . "'";
482 my ($engine, @x) = @_;
484 while (scalar @x > 0) {
485 if ($x[0] =~ /^(name|author)$/) {
487 my $value = join(' ', @x);
488 $engine->{'id'}{$key} = $value;
497 sub prettyprint_pv_no_cache {
498 my ($board, @pvs) = @_;
500 if (scalar @pvs == 0 || !defined($pvs[0])) {
505 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
506 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
507 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
511 my ($pos, @pvs) = @_;
513 my $cachekey = join('', @pvs);
514 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
515 return @{$pos->{'prettyprint_cache'}{$cachekey}};
517 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
518 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
526 return if (!defined($pos_calculating));
528 # Don't update too often.
529 my $age = Time::HiRes::tv_interval($latest_update);
530 if ($age < $remoteglotconf::update_max_interval) {
531 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
532 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
536 my $info = $engine->{'info'};
539 # If we have tablebase data from a previous lookup, replace the
540 # engine data with the data from the tablebase.
542 my $fen = $pos_calculating->fen();
543 if (exists($tb_cache{$fen})) {
544 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
545 delete $info->{$key . '1'};
546 delete $info->{$key};
548 $info->{'nodes'} = 0;
550 $info->{'depth'} = 0;
551 $info->{'seldepth'} = 0;
552 $info->{'tbhits'} = 0;
554 my $t = $tb_cache{$fen};
556 my $matelen = int((1 + $t->{'score'}) / 2);
557 if ($t->{'result'} eq '1/2-1/2') {
558 $info->{'score_cp'} = 0;
559 } elsif ($t->{'result'} eq '1-0') {
560 if ($pos_calculating->{'toplay'} eq 'B') {
561 $info->{'score_mate'} = -$matelen;
563 $info->{'score_mate'} = $matelen;
566 if ($pos_calculating->{'toplay'} eq 'B') {
567 $info->{'score_mate'} = $matelen;
569 $info->{'score_mate'} = -$matelen;
573 $info->{'tablebase'} = 1;
575 $info->{'tablebase'} = 0;
579 # Some programs _always_ report MultiPV, even with only one PV.
580 # In this case, we simply use that data as if MultiPV was never
583 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
584 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
585 if (exists($info->{$key . '1'})) {
586 $info->{$key} = $info->{$key . '1'};
592 # Check the PVs first. if they're invalid, just wait, as our data
593 # is most likely out of sync. This isn't a very good solution, as
594 # it can frequently miss stuff, but it's good enough for most users.
598 if (exists($info->{'pv'})) {
599 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
603 while (exists($info->{'pv' . $mpv})) {
604 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
609 $engine->{'info'} = {};
615 $latest_update = [Time::HiRes::gettimeofday];
619 my $info = $engine->{'info'};
620 my $id = $engine->{'id'};
622 my $text = 'Analysis';
623 if ($pos_calculating->{'last_move'} ne 'none') {
624 if ($pos_calculating->{'toplay'} eq 'W') {
625 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
627 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
629 if (exists($id->{'name'})) {
634 if (exists($id->{'name'})) {
635 $text .= " by $id->{'name'}:\n\n";
640 return unless (exists($pos_calculating->{'board'}));
642 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
645 while (exists($info->{'pv' . $mpv})) {
646 $text .= sprintf " PV%2u", $mpv;
647 my $score = short_score($info, $pos_calculating, $mpv);
648 $text .= " ($score)" if (defined($score));
651 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
652 if ($info->{'tbhits' . $mpv} == 1) {
653 $tbhits = ", 1 tbhit";
655 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
659 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
660 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
661 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
665 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
671 my $score = long_score($info, $pos_calculating, '');
672 $text .= " $score\n" if defined($score);
673 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
676 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
677 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
678 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
680 if (exists($info->{'seldepth'})) {
681 $text .= sprintf " (%u selective)", $info->{'seldepth'};
683 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
684 if ($info->{'tbhits'} == 1) {
685 $text .= ", one Syzygy hit";
687 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
693 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
695 my @refutation_lines = ();
696 if (defined($engine2)) {
697 for (my $mpv = 1; $mpv < 500; ++$mpv) {
698 my $info = $engine2->{'info'};
699 last if (!exists($info->{'pv' . $mpv}));
701 my $pv = $info->{'pv' . $mpv};
703 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
704 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
705 if (scalar @pretty_pv > 5) {
706 @pretty_pv = @pretty_pv[0..4];
707 push @pretty_pv, "...";
709 my $key = $pretty_move;
710 my $line = sprintf(" %-6s %6s %3s %s",
712 short_score($info, $pos_calculating_second_engine, $mpv),
713 "d" . $info->{'depth' . $mpv},
714 join(', ', @pretty_pv));
715 push @refutation_lines, [ $key, $line ];
720 if ($#refutation_lines >= 0) {
721 $text .= "Shallow search of all legal moves:\n\n";
722 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
723 $text .= $line->[1] . "\n";
728 if ($last_text ne $text) {
729 print "
\e[H
\e[2J"; # clear the screen
736 my $historic_json_only = shift;
737 my $info = $engine->{'info'};
740 $json->{'position'} = $pos_calculating->to_json_hash();
741 $json->{'id'} = $engine->{'id'};
742 $json->{'score'} = long_score($info, $pos_calculating, '');
743 $json->{'short_score'} = short_score($info, $pos_calculating, '');
744 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
746 $json->{'nodes'} = $info->{'nodes'};
747 $json->{'nps'} = $info->{'nps'};
748 $json->{'depth'} = $info->{'depth'};
749 $json->{'tbhits'} = $info->{'tbhits'};
750 $json->{'seldepth'} = $info->{'seldepth'};
751 $json->{'tablebase'} = $info->{'tablebase'};
753 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
754 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
756 my %refutation_lines = ();
757 my @refutation_lines = ();
758 if (defined($engine2)) {
759 for (my $mpv = 1; $mpv < 500; ++$mpv) {
760 my $info = $engine2->{'info'};
761 my $pretty_move = "";
763 last if (!exists($info->{'pv' . $mpv}));
766 my $pv = $info->{'pv' . $mpv};
767 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
768 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
769 $refutation_lines{$pv->[0]} = {
770 sort_key => $pretty_move,
771 depth => $info->{'depth' . $mpv},
772 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
773 pretty_score => short_score($info, $pos_calculating, $mpv),
774 pretty_move => $pretty_move,
775 pv_pretty => \@pretty_pv,
780 $json->{'refutation_lines'} = \%refutation_lines;
782 # Piece together historic score information, to the degree we have it.
783 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
784 my %score_history = ();
786 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
787 my $pos = Position->start_pos('white', 'black');
788 my $halfmove_num = 0;
789 for my $move (@{$pos_calculating->{'pretty_history'}}) {
790 my $id = id_for_pos($pos, $halfmove_num);
791 my $ref = $dbh->selectrow_hashref($q, undef, $id);
793 $score_history{$halfmove_num} = [
794 $ref->{'plot_score'},
795 $ref->{'short_score'}
799 ($pos) = $pos->make_pretty_move($move);
803 # If at any point we are missing 10 consecutive moves,
804 # truncate the history there. This is so we don't get into
805 # a situation where we e.g. start analyzing at move 45,
806 # but we have analysis for 1. e4 from some completely different game
807 # and thus show a huge hole.
808 my $consecutive_missing = 0;
809 my $truncate_until = 0;
810 for (my $i = $halfmove_num; $i --> 0; ) {
811 if ($consecutive_missing >= 10) {
812 delete $score_history{$i};
815 if (exists($score_history{$i})) {
816 $consecutive_missing = 0;
818 ++$consecutive_missing;
822 $json->{'score_history'} = \%score_history;
825 # Give out a list of other games going on. (Empty is fine.)
826 if (!$historic_json_only) {
829 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
831 while (my $ref = $q->fetchrow_hashref) {
833 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
834 my $other_game_json = JSON::XS::decode_json($other_game_contents);
836 die "Missing position" if (!exists($other_game_json->{'position'}));
837 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
838 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
842 name => "$white–$black",
847 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
851 if (scalar @games > 0) {
852 $json->{'games'} = \@games;
856 my $json_enc = JSON::XS->new;
857 $json_enc->canonical(1);
858 my $encoded = $json_enc->encode($json);
859 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
860 (defined($last_written_json) && $last_written_json eq $encoded)) {
861 atomic_set_contents($remoteglotconf::json_output, $encoded);
862 $last_written_json = $encoded;
865 if (exists($pos_calculating->{'pretty_history'}) &&
866 defined($remoteglotconf::json_history_dir)) {
867 my $id = id_for_pos($pos_calculating);
868 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
870 # Overwrite old analysis (assuming it exists at all) if we're
871 # using a different engine, or if we've calculated deeper.
872 # nodes is used as a tiebreaker. Don't bother about Multi-PV
873 # data; it's not that important.
874 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
875 my $new_depth = $json->{'depth'} // 0;
876 my $new_nodes = $json->{'nodes'} // 0;
877 if (!defined($old_engine) ||
878 $old_engine ne $json->{'id'}{'name'} ||
879 $new_depth > $old_depth ||
880 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
881 atomic_set_contents($filename, $encoded);
882 if (defined($json->{'plot_score'})) {
883 local $dbh->{AutoCommit} = 0;
884 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
885 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?)', undef,
886 $id, $json->{'plot_score'}, $json->{'short_score'},
887 $json->{'id'}{'name'}, $new_depth, $new_nodes);
894 sub atomic_set_contents {
895 my ($filename, $contents) = @_;
897 open my $fh, ">", $filename . ".tmp"
901 rename($filename . ".tmp", $filename);
905 my ($pos, $halfmove_num) = @_;
907 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
908 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
909 return "move$halfmove_num-$fen";
912 sub get_json_analysis_stats {
914 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
916 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
923 my ($engine, $msg) = @_;
924 $engine->print($msg);
925 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
929 my ($info, $pos, $mpv) = @_;
931 my $invert = ($pos->{'toplay'} eq 'B');
932 if (defined($info->{'score_mate' . $mpv})) {
934 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
936 return sprintf "M%3d", $info->{'score_mate' . $mpv};
939 if (exists($info->{'score_cp' . $mpv})) {
940 my $score = $info->{'score_cp' . $mpv} * 0.01;
942 if ($info->{'tablebase'}) {
951 return sprintf "%+5.2f", $score;
959 my ($info, $pos, $mpv, $invert) = @_;
961 if (defined($info->{'score_mate' . $mpv})) {
962 my $mate = $info->{'score_mate' . $mpv};
966 $score = 99999 - $mate;
968 # Side to move is getting mated (note the double negative for $mate)
969 $score = -99999 - $mate;
976 if (exists($info->{'score_cp' . $mpv})) {
977 my $score = $info->{'score_cp' . $mpv};
989 my ($info, $pos, $mpv) = @_;
991 if (defined($info->{'score_mate' . $mpv})) {
992 my $mate = $info->{'score_mate' . $mpv};
993 if ($pos->{'toplay'} eq 'B') {
997 return sprintf "White mates in %u", $mate;
999 return sprintf "Black mates in %u", -$mate;
1002 if (exists($info->{'score_cp' . $mpv})) {
1003 my $score = $info->{'score_cp' . $mpv} * 0.01;
1005 if ($info->{'tablebase'}) {
1006 return "Theoretical draw";
1008 return "Score: 0.00";
1011 if ($pos->{'toplay'} eq 'B') {
1014 return sprintf "Score: %+5.2f", $score;
1021 # For graphs; a single number in centipawns, capped at +/- 500.
1023 my ($info, $pos, $mpv) = @_;
1025 my $invert = ($pos->{'toplay'} eq 'B');
1026 if (defined($info->{'score_mate' . $mpv})) {
1027 my $mate = $info->{'score_mate' . $mpv};
1037 if (exists($info->{'score_cp' . $mpv})) {
1038 my $score = $info->{'score_cp' . $mpv};
1042 $score = 500 if ($score > 500);
1043 $score = -500 if ($score < -500);
1051 my %book_cache = ();
1053 my ($fen, $board, $toplay) = @_;
1055 if (exists($book_cache{$fen})) {
1056 return $book_cache{$fen};
1059 my $ret = `./booklook $fen`;
1060 return "" if ($ret =~ /Not found/ || $ret eq '');
1064 for my $m (split /\n/, $ret) {
1065 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1069 $pmove = '(current)';
1071 ($pmove) = prettyprint_pv_no_cache($board, $move);
1072 $pmove .= $annotation;
1076 if ($toplay eq 'W') {
1077 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1079 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1081 my $n = $win + $draw + $lose;
1087 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1090 push @moves, [ $pmove, $n, $percent, $rating ];
1093 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1095 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1096 for my $m (@moves) {
1097 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1104 my ($pgn, $pos) = @_;
1106 # Look for extended PGN clock tags.
1107 my $tags = $pgn->tags;
1108 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1109 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1110 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1114 # Look for TCEC-style time comments.
1115 my $moves = $pgn->moves;
1116 my $comments = $pgn->comments;
1117 my $last_black_move = int((scalar @$moves) / 2);
1118 my $last_white_move = int((1 + scalar @$moves) / 2);
1120 my $black_key = $last_black_move . "b";
1121 my $white_key = $last_white_move . "w";
1123 if (exists($comments->{$white_key}) &&
1124 exists($comments->{$black_key}) &&
1125 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1126 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1127 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1128 $pos->{'white_clock'} = hms_to_sec($1);
1129 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1130 $pos->{'black_clock'} = hms_to_sec($1);
1134 delete $pos->{'white_clock'};
1135 delete $pos->{'black_clock'};
1140 return undef if (!defined($hms));
1141 $hms =~ /(\d+):(\d+):(\d+)/;
1142 return $1 * 3600 + $2 * 60 + $3;
1145 sub find_clock_start {
1146 my ($pos, $prev_pos) = @_;
1148 # If the game is over, the clock is stopped.
1149 if (exists($pos->{'result'}) &&
1150 ($pos->{'result'} eq '1-0' ||
1151 $pos->{'result'} eq '1/2-1/2' ||
1152 $pos->{'result'} eq '0-1')) {
1156 # When we don't have any moves, we assume the clock hasn't started yet.
1157 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1158 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1159 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1164 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1165 # The history is needed for id_for_pos.
1166 if (!exists($pos->{'pretty_history'})) {
1170 my $id = id_for_pos($pos);
1171 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1172 if (defined($clock_info)) {
1173 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1174 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1175 if ($pos->{'toplay'} eq 'W') {
1176 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1178 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1183 # OK, we haven't seen this position before, so we assume the move
1184 # happened right now.
1186 # See if we should do our own clock management (ie., clock information
1187 # is spurious or non-existent).
1188 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1189 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1190 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1191 if (defined($prev_pos->{'white_clock_target'})) {
1192 $wc = $prev_pos->{'white_clock_target'} - time;
1194 if (defined($prev_pos->{'black_clock_target'})) {
1195 $bc = $prev_pos->{'black_clock_target'} - time;
1197 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1198 $pos->{'white_clock'} = $wc;
1199 $pos->{'black_clock'} = $bc;
1202 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1203 if (!exists($pos->{$key})) {
1204 # No clock information.
1207 my $time_left = $pos->{$key};
1208 my ($white_clock_target, $black_clock_target);
1209 if ($pos->{'toplay'} eq 'W') {
1210 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1212 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1214 local $dbh->{AutoCommit} = 0;
1215 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1216 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1217 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1221 sub schedule_tb_lookup {
1222 return if (!defined($remoteglotconf::tb_serial_key));
1223 my $pos = $pos_waiting // $pos_calculating;
1224 return if (exists($tb_cache{$pos->fen()}));
1226 # If there's more than seven pieces, there's not going to be an answer,
1228 return if ($pos->num_pieces() > 7);
1230 # Max one at a time. If it's still relevant when it returns,
1231 # schedule_tb_lookup() will be called again.
1232 return if ($tb_lookup_running);
1234 $tb_lookup_running = 1;
1235 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1236 $remoteglotconf::tb_serial_key .
1237 '&auth.password=aquarium&type=0&fen=' .
1238 URI::Escape::uri_escape($pos->fen());
1239 print TBLOG "Downloading $url...\n";
1240 AnyEvent::HTTP::http_get($url, sub {
1241 handle_tb_lookup_return(@_, $pos, $pos->fen());
1245 sub handle_tb_lookup_return {
1246 my ($body, $header, $pos, $fen) = @_;
1247 print TBLOG "Response for [$fen]:\n";
1248 print TBLOG $header . "\n\n";
1249 print TBLOG $body . "\n\n";
1251 my $response = JSON::XS::decode_json($body);
1252 if ($response->{'ErrorCode'} != 0) {
1253 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1255 my $state = $response->{'Response'}{'StateString'};
1256 if ($state eq 'COMPLETE') {
1257 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1258 if (!defined($pgn) || !$pgn->read_game()) {
1259 warn "Error in parsing PGN\n";
1261 $pgn->quick_parse_game;
1263 my $moves = $pgn->moves;
1265 for my $move (@$moves) {
1267 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1268 push @uci_moves, $uci_move;
1271 result => $pgn->result,
1273 score => $response->{'Response'}{'Score'},
1277 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1278 # Try again in a second. Note that if we have changed
1279 # position in the meantime, we might query a completely
1280 # different position! But that's fine.
1282 die "Unknown response state " . $state;
1285 # Wait a second before we schedule another one.
1286 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1287 $tb_lookup_running = 0;
1288 schedule_tb_lookup();
1292 warn "Error in tablebase lookup: $@";
1294 # Don't try this one again, but don't block new lookups either.
1295 $tb_lookup_running = 0;
1300 my ($cmdline, $tag, $cb) = @_;
1301 return undef if (!defined($cmdline));
1302 return Engine->open($cmdline, $tag, $cb);
1305 sub col_letter_to_num {
1306 return ord(shift) - ord('a');
1309 sub row_letter_to_num {
1310 return 7 - (ord(shift) - ord('1'));
1313 sub parse_uci_move {
1315 my $from_col = col_letter_to_num(substr($move, 0, 1));
1316 my $from_row = row_letter_to_num(substr($move, 1, 1));
1317 my $to_col = col_letter_to_num(substr($move, 2, 1));
1318 my $to_row = row_letter_to_num(substr($move, 3, 1));
1319 my $promo = substr($move, 4, 1);
1320 return ($from_col, $from_row, $to_col, $to_row, $promo);