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)) {
279 warn "Error in parsing PGN from $url [body='$body']\n";
280 } elsif (!$pgn->read_game()) {
281 warn "Error in reading PGN game from $url [body='$body']\n";
282 } elsif ($body !~ /^\[/) {
283 warn "Malformed PGN from $url [body='$body']\n";
286 # Skip to the right game.
287 while (defined($remoteglotconf::pgn_filter) &&
288 !&$remoteglotconf::pgn_filter($pgn)) {
289 $pgn->read_game() or die "Out of games during filtering";
292 $pgn->parse_game({ save_comments => 'yes' });
293 my $pos = Position->start_pos($pgn->white, $pgn->black);
294 my $moves = $pgn->moves;
296 my @repretty_moves = ();
297 for my $move (@$moves) {
298 my ($npos, $uci_move) = $pos->make_pretty_move($move);
299 push @uci_moves, $uci_move;
301 # Re-prettyprint the move.
302 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($uci_move);
303 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
304 push @repretty_moves, $pretty;
307 $pos->{'result'} = $pgn->result;
308 $pos->{'pretty_history'} = \@repretty_moves;
310 extract_clock($pgn, $pos);
312 # Sometimes, PGNs lose a move or two for a short while,
313 # or people push out new ones non-atomically.
314 # Thus, if we PGN doesn't change names but becomes
315 # shorter, we mistrust it for a few seconds.
317 if (defined($last_pgn_white) && defined($last_pgn_black) &&
318 $last_pgn_white eq $pgn->white &&
319 $last_pgn_black eq $pgn->black &&
320 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
321 if (++$pgn_hysteresis_counter < 3) {
326 $last_pgn_white = $pgn->white;
327 $last_pgn_black = $pgn->black;
328 @last_pgn_uci_moves = @uci_moves;
329 $pgn_hysteresis_counter = 0;
330 handle_position($pos);
334 warn "Error in parsing moves from $url: $@\n";
338 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
343 sub handle_position {
345 find_clock_start($pos, $pos_calculating);
347 # if this is already in the queue, ignore it (just update the result)
348 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
349 $pos_waiting->{'result'} = $pos->{'result'};
353 # if we're already chewing on this and there's nothing else in the queue,
355 if (!defined($pos_waiting) && defined($pos_calculating) &&
356 $pos->fen() eq $pos_calculating->fen()) {
357 $pos_calculating->{'result'} = $pos->{'result'};
361 # if we're already thinking on something, stop and wait for the engine
363 if (defined($pos_calculating)) {
364 # Store the final data we have for this position in the history,
365 # with the precise clock information we just got from the new
366 # position. (Historic positions store the clock at the end of
369 # Do not output anything new to the main analysis; that's
370 # going to be obsolete really soon.
371 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
372 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
373 delete $pos_calculating->{'white_clock_target'};
374 delete $pos_calculating->{'black_clock_target'};
377 if (!defined($pos_waiting)) {
378 uciprint($engine, "stop");
380 if ($remoteglotconf::uci_assume_full_compliance) {
383 uciprint($engine, "position fen " . $pos->fen());
384 uciprint($engine, "go infinite");
385 $pos_calculating = $pos;
388 # it's wrong just to give the FEN (the move history is useful,
389 # and per the UCI spec, we should really have sent "ucinewgame"),
391 uciprint($engine, "position fen " . $pos->fen());
392 uciprint($engine, "go infinite");
393 $pos_calculating = $pos;
396 if (defined($engine2)) {
397 if (defined($pos_calculating_second_engine)) {
398 uciprint($engine2, "stop");
400 uciprint($engine2, "position fen " . $pos->fen());
401 uciprint($engine2, "go infinite");
402 $pos_calculating_second_engine = $pos;
404 $engine2->{'info'} = {};
407 $engine->{'info'} = {};
410 schedule_tb_lookup();
413 # Output a command every move to note that we're
414 # still paying attention -- this is a good tradeoff,
415 # since if no move has happened in the last half
416 # hour, the analysis/relay has most likely stopped
417 # and we should stop hogging server resources.
423 my ($engine, @x) = @_;
426 my $info = $engine->{'info'};
428 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
429 for my $i (0..$#x - 1) {
430 if ($x[$i] eq 'multipv') {
436 while (scalar @x > 0) {
437 if ($x[0] eq 'multipv') {
443 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
445 my $value = shift @x;
446 $info->{$key} = $value;
449 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
450 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
453 my $value = shift @x;
454 $info->{$key . $mpv} = $value;
457 if ($x[0] eq 'score') {
460 delete $info->{'score_cp' . $mpv};
461 delete $info->{'score_mate' . $mpv};
463 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
466 $info->{'score_cp' . $mpv} = shift @x;
467 } elsif ($x[0] eq 'mate') {
469 $info->{'score_mate' . $mpv} = shift @x;
477 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
480 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
484 #print "unknown info '$x[0]', trying to recover...\n";
486 die "Unknown info '" . join(',', @x) . "'";
492 my ($engine, @x) = @_;
494 while (scalar @x > 0) {
495 if ($x[0] eq 'name') {
496 my $value = join(' ', @x);
497 $engine->{'id'}{'author'} = $value;
506 sub prettyprint_pv_no_cache {
507 my ($board, @pvs) = @_;
509 if (scalar @pvs == 0 || !defined($pvs[0])) {
514 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
515 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
516 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
520 my ($pos, @pvs) = @_;
522 my $cachekey = join('', @pvs);
523 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
524 return @{$pos->{'prettyprint_cache'}{$cachekey}};
526 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
527 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
535 return if (!defined($pos_calculating));
537 # Don't update too often.
538 my $age = Time::HiRes::tv_interval($latest_update);
539 if ($age < $remoteglotconf::update_max_interval) {
540 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
541 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
545 my $info = $engine->{'info'};
548 # If we have tablebase data from a previous lookup, replace the
549 # engine data with the data from the tablebase.
551 my $fen = $pos_calculating->fen();
552 if (exists($tb_cache{$fen})) {
553 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
554 delete $info->{$key . '1'};
555 delete $info->{$key};
557 $info->{'nodes'} = 0;
559 $info->{'depth'} = 0;
560 $info->{'seldepth'} = 0;
561 $info->{'tbhits'} = 0;
563 my $t = $tb_cache{$fen};
565 my $matelen = int((1 + $t->{'score'}) / 2);
566 if ($t->{'result'} eq '1/2-1/2') {
567 $info->{'score_cp'} = 0;
568 } elsif ($t->{'result'} eq '1-0') {
569 if ($pos_calculating->{'toplay'} eq 'B') {
570 $info->{'score_mate'} = -$matelen;
572 $info->{'score_mate'} = $matelen;
575 if ($pos_calculating->{'toplay'} eq 'B') {
576 $info->{'score_mate'} = $matelen;
578 $info->{'score_mate'} = -$matelen;
582 $info->{'tablebase'} = 1;
584 $info->{'tablebase'} = 0;
588 # Some programs _always_ report MultiPV, even with only one PV.
589 # In this case, we simply use that data as if MultiPV was never
592 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
593 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
594 if (exists($info->{$key . '1'})) {
595 $info->{$key} = $info->{$key . '1'};
601 # Check the PVs first. if they're invalid, just wait, as our data
602 # is most likely out of sync. This isn't a very good solution, as
603 # it can frequently miss stuff, but it's good enough for most users.
607 if (exists($info->{'pv'})) {
608 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
612 while (exists($info->{'pv' . $mpv})) {
613 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
618 $engine->{'info'} = {};
624 $latest_update = [Time::HiRes::gettimeofday];
628 my $info = $engine->{'info'};
629 my $id = $engine->{'id'};
631 my $text = 'Analysis';
632 if ($pos_calculating->{'last_move'} ne 'none') {
633 if ($pos_calculating->{'toplay'} eq 'W') {
634 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
636 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
638 if (exists($id->{'name'})) {
643 if (exists($id->{'name'})) {
644 $text .= " by $id->{'name'}:\n\n";
649 return unless (exists($pos_calculating->{'board'}));
651 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
654 while (exists($info->{'pv' . $mpv})) {
655 $text .= sprintf " PV%2u", $mpv;
656 my $score = short_score($info, $pos_calculating, $mpv);
657 $text .= " ($score)" if (defined($score));
660 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
661 if ($info->{'tbhits' . $mpv} == 1) {
662 $tbhits = ", 1 tbhit";
664 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
668 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
669 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
670 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
674 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
680 my $score = long_score($info, $pos_calculating, '');
681 $text .= " $score\n" if defined($score);
682 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
685 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
686 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
687 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
689 if (exists($info->{'seldepth'})) {
690 $text .= sprintf " (%u selective)", $info->{'seldepth'};
692 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
693 if ($info->{'tbhits'} == 1) {
694 $text .= ", one Syzygy hit";
696 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
702 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
704 my @refutation_lines = ();
705 if (defined($engine2)) {
706 for (my $mpv = 1; $mpv < 500; ++$mpv) {
707 my $info = $engine2->{'info'};
708 last if (!exists($info->{'pv' . $mpv}));
710 my $pv = $info->{'pv' . $mpv};
712 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
713 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
714 if (scalar @pretty_pv > 5) {
715 @pretty_pv = @pretty_pv[0..4];
716 push @pretty_pv, "...";
718 my $key = $pretty_move;
719 my $line = sprintf(" %-6s %6s %3s %s",
721 short_score($info, $pos_calculating_second_engine, $mpv),
722 "d" . $info->{'depth' . $mpv},
723 join(', ', @pretty_pv));
724 push @refutation_lines, [ $key, $line ];
729 if ($#refutation_lines >= 0) {
730 $text .= "Shallow search of all legal moves:\n\n";
731 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
732 $text .= $line->[1] . "\n";
737 if ($last_text ne $text) {
738 print "
\e[H
\e[2J"; # clear the screen
745 my $historic_json_only = shift;
746 my $info = $engine->{'info'};
749 $json->{'position'} = $pos_calculating->to_json_hash();
750 $json->{'engine'} = $engine->{'id'};
751 if (defined($remoteglotconf::engine_url)) {
752 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
754 if (defined($remoteglotconf::engine_details)) {
755 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
757 if (defined($remoteglotconf::move_source)) {
758 $json->{'move_source'} = $remoteglotconf::move_source;
760 if (defined($remoteglotconf::move_source_url)) {
761 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
763 $json->{'score'} = long_score($info, $pos_calculating, '');
764 $json->{'short_score'} = short_score($info, $pos_calculating, '');
765 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
766 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
768 $json->{'nodes'} = $info->{'nodes'};
769 $json->{'nps'} = $info->{'nps'};
770 $json->{'depth'} = $info->{'depth'};
771 $json->{'tbhits'} = $info->{'tbhits'};
772 $json->{'seldepth'} = $info->{'seldepth'};
773 $json->{'tablebase'} = $info->{'tablebase'};
775 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
776 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
778 my %refutation_lines = ();
779 my @refutation_lines = ();
780 if (defined($engine2)) {
781 for (my $mpv = 1; $mpv < 500; ++$mpv) {
782 my $info = $engine2->{'info'};
783 my $pretty_move = "";
785 last if (!exists($info->{'pv' . $mpv}));
788 my $pv = $info->{'pv' . $mpv};
789 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
790 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
791 $refutation_lines{$pv->[0]} = {
792 sort_key => $pretty_move,
793 depth => $info->{'depth' . $mpv},
794 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
795 pretty_score => short_score($info, $pos_calculating, $mpv),
796 pretty_move => $pretty_move,
797 pv_pretty => \@pretty_pv,
802 $json->{'refutation_lines'} = \%refutation_lines;
804 # Piece together historic score information, to the degree we have it.
805 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
806 my %score_history = ();
808 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
809 my $pos = Position->start_pos('white', 'black');
810 my $halfmove_num = 0;
811 for my $move (@{$pos_calculating->{'pretty_history'}}) {
812 my $id = id_for_pos($pos, $halfmove_num);
813 my $ref = $dbh->selectrow_hashref($q, undef, $id);
815 $score_history{$halfmove_num} = [
816 $ref->{'plot_score'},
817 $ref->{'short_score'}
821 ($pos) = $pos->make_pretty_move($move);
825 # If at any point we are missing 10 consecutive moves,
826 # truncate the history there. This is so we don't get into
827 # a situation where we e.g. start analyzing at move 45,
828 # but we have analysis for 1. e4 from some completely different game
829 # and thus show a huge hole.
830 my $consecutive_missing = 0;
831 my $truncate_until = 0;
832 for (my $i = $halfmove_num; $i --> 0; ) {
833 if ($consecutive_missing >= 10) {
834 delete $score_history{$i};
837 if (exists($score_history{$i})) {
838 $consecutive_missing = 0;
840 ++$consecutive_missing;
844 $json->{'score_history'} = \%score_history;
847 # Give out a list of other games going on. (Empty is fine.)
848 if (!$historic_json_only) {
851 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
853 while (my $ref = $q->fetchrow_hashref) {
855 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
856 my $other_game_json = JSON::XS::decode_json($other_game_contents);
858 die "Missing position" if (!exists($other_game_json->{'position'}));
859 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
860 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
864 name => "$white–$black",
869 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
873 if (scalar @games > 0) {
874 $json->{'games'} = \@games;
878 my $json_enc = JSON::XS->new;
879 $json_enc->canonical(1);
880 my $encoded = $json_enc->encode($json);
881 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
882 (defined($last_written_json) && $last_written_json eq $encoded)) {
883 atomic_set_contents($remoteglotconf::json_output, $encoded);
884 $last_written_json = $encoded;
887 if (exists($pos_calculating->{'pretty_history'}) &&
888 defined($remoteglotconf::json_history_dir)) {
889 my $id = id_for_pos($pos_calculating);
890 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
892 # Overwrite old analysis (assuming it exists at all) if we're
893 # using a different engine, or if we've calculated deeper.
894 # nodes is used as a tiebreaker. Don't bother about Multi-PV
895 # data; it's not that important.
896 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
897 my $new_depth = $json->{'depth'} // 0;
898 my $new_nodes = $json->{'nodes'} // 0;
899 if (!defined($old_engine) ||
900 $old_engine ne $json->{'engine'}{'name'} ||
901 $new_depth > $old_depth ||
902 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
903 atomic_set_contents($filename, $encoded);
904 if (defined($json->{'plot_score'})) {
905 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
906 ' ON CONFLICT (id) DO UPDATE SET ' .
907 ' plot_score=EXCLUDED.plot_score, ' .
908 ' short_score=EXCLUDED.short_score, ' .
909 ' engine=EXCLUDED.engine, ' .
910 ' depth=EXCLUDED.depth, ' .
911 ' nodes=EXCLUDED.nodes',
913 $id, $json->{'plot_score'}, $json->{'short_score'},
914 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
920 sub atomic_set_contents {
921 my ($filename, $contents) = @_;
923 open my $fh, ">", $filename . ".tmp"
927 rename($filename . ".tmp", $filename);
931 my ($pos, $halfmove_num) = @_;
933 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
934 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
935 return "move$halfmove_num-$fen";
938 sub get_json_analysis_stats {
940 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
942 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
949 my ($engine, $msg) = @_;
950 $engine->print($msg);
951 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
955 my ($info, $pos, $mpv) = @_;
957 my $invert = ($pos->{'toplay'} eq 'B');
958 if (defined($info->{'score_mate' . $mpv})) {
960 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
962 return sprintf "M%3d", $info->{'score_mate' . $mpv};
965 if (exists($info->{'score_cp' . $mpv})) {
966 my $score = $info->{'score_cp' . $mpv} * 0.01;
968 if ($info->{'tablebase'}) {
977 return sprintf "%+5.2f", $score;
985 my ($info, $pos, $mpv, $invert) = @_;
987 if (defined($info->{'score_mate' . $mpv})) {
988 my $mate = $info->{'score_mate' . $mpv};
992 $score = 99999 - $mate;
994 # Side to move is getting mated (note the double negative for $mate)
995 $score = -99999 - $mate;
1002 if (exists($info->{'score_cp' . $mpv})) {
1003 my $score = $info->{'score_cp' . $mpv};
1015 my ($info, $pos, $mpv) = @_;
1017 if (defined($info->{'score_mate' . $mpv})) {
1018 my $mate = $info->{'score_mate' . $mpv};
1019 if ($pos->{'toplay'} eq 'B') {
1023 return sprintf "White mates in %u", $mate;
1025 return sprintf "Black mates in %u", -$mate;
1028 if (exists($info->{'score_cp' . $mpv})) {
1029 my $score = $info->{'score_cp' . $mpv} * 0.01;
1031 if ($info->{'tablebase'}) {
1032 return "Theoretical draw";
1034 return "Score: 0.00";
1037 if ($pos->{'toplay'} eq 'B') {
1040 return sprintf "Score: %+5.2f", $score;
1047 # For graphs; a single number in centipawns, capped at +/- 500.
1049 my ($info, $pos, $mpv) = @_;
1051 my $invert = ($pos->{'toplay'} eq 'B');
1052 if (defined($info->{'score_mate' . $mpv})) {
1053 my $mate = $info->{'score_mate' . $mpv};
1063 if (exists($info->{'score_cp' . $mpv})) {
1064 my $score = $info->{'score_cp' . $mpv};
1068 $score = 500 if ($score > 500);
1069 $score = -500 if ($score < -500);
1077 my %book_cache = ();
1079 my ($fen, $board, $toplay) = @_;
1081 if (exists($book_cache{$fen})) {
1082 return $book_cache{$fen};
1085 my $ret = `./booklook $fen`;
1086 return "" if ($ret =~ /Not found/ || $ret eq '');
1090 for my $m (split /\n/, $ret) {
1091 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1095 $pmove = '(current)';
1097 ($pmove) = prettyprint_pv_no_cache($board, $move);
1098 $pmove .= $annotation;
1102 if ($toplay eq 'W') {
1103 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1105 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1107 my $n = $win + $draw + $lose;
1113 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1116 push @moves, [ $pmove, $n, $percent, $rating ];
1119 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1121 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1122 for my $m (@moves) {
1123 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1130 my ($pgn, $pos) = @_;
1132 # Look for extended PGN clock tags.
1133 my $tags = $pgn->tags;
1134 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1135 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1136 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1140 # Look for TCEC-style time comments.
1141 my $moves = $pgn->moves;
1142 my $comments = $pgn->comments;
1143 my $last_black_move = int((scalar @$moves) / 2);
1144 my $last_white_move = int((1 + scalar @$moves) / 2);
1146 my $black_key = $last_black_move . "b";
1147 my $white_key = $last_white_move . "w";
1149 if (exists($comments->{$white_key}) &&
1150 exists($comments->{$black_key}) &&
1151 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1152 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1153 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1154 $pos->{'white_clock'} = hms_to_sec($1);
1155 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1156 $pos->{'black_clock'} = hms_to_sec($1);
1160 delete $pos->{'white_clock'};
1161 delete $pos->{'black_clock'};
1166 return undef if (!defined($hms));
1167 $hms =~ /(\d+):(\d+):(\d+)/;
1168 return $1 * 3600 + $2 * 60 + $3;
1171 sub find_clock_start {
1172 my ($pos, $prev_pos) = @_;
1174 # If the game is over, the clock is stopped.
1175 if (exists($pos->{'result'}) &&
1176 ($pos->{'result'} eq '1-0' ||
1177 $pos->{'result'} eq '1/2-1/2' ||
1178 $pos->{'result'} eq '0-1')) {
1182 # When we don't have any moves, we assume the clock hasn't started yet.
1183 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1184 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1185 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1190 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1191 # The history is needed for id_for_pos.
1192 if (!exists($pos->{'pretty_history'})) {
1196 my $id = id_for_pos($pos);
1197 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1198 if (defined($clock_info)) {
1199 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1200 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1201 if ($pos->{'toplay'} eq 'W') {
1202 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1204 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1209 # OK, we haven't seen this position before, so we assume the move
1210 # happened right now.
1212 # See if we should do our own clock management (ie., clock information
1213 # is spurious or non-existent).
1214 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1215 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1216 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1217 if (defined($prev_pos->{'white_clock_target'})) {
1218 $wc = $prev_pos->{'white_clock_target'} - time;
1220 if (defined($prev_pos->{'black_clock_target'})) {
1221 $bc = $prev_pos->{'black_clock_target'} - time;
1223 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1224 $pos->{'white_clock'} = $wc;
1225 $pos->{'black_clock'} = $bc;
1228 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1229 if (!exists($pos->{$key})) {
1230 # No clock information.
1233 my $time_left = $pos->{$key};
1234 my ($white_clock_target, $black_clock_target);
1235 if ($pos->{'toplay'} eq 'W') {
1236 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1238 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1240 local $dbh->{AutoCommit} = 0;
1241 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1242 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1243 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1247 sub schedule_tb_lookup {
1248 return if (!defined($remoteglotconf::tb_serial_key));
1249 my $pos = $pos_waiting // $pos_calculating;
1250 return if (exists($tb_cache{$pos->fen()}));
1252 # If there's more than seven pieces, there's not going to be an answer,
1254 return if ($pos->num_pieces() > 7);
1256 # Max one at a time. If it's still relevant when it returns,
1257 # schedule_tb_lookup() will be called again.
1258 return if ($tb_lookup_running);
1260 $tb_lookup_running = 1;
1261 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1262 $remoteglotconf::tb_serial_key .
1263 '&auth.password=aquarium&type=0&fen=' .
1264 URI::Escape::uri_escape($pos->fen());
1265 print TBLOG "Downloading $url...\n";
1266 AnyEvent::HTTP::http_get($url, sub {
1267 handle_tb_lookup_return(@_, $pos, $pos->fen());
1271 sub handle_tb_lookup_return {
1272 my ($body, $header, $pos, $fen) = @_;
1273 print TBLOG "Response for [$fen]:\n";
1274 print TBLOG $header . "\n\n";
1275 print TBLOG $body . "\n\n";
1277 my $response = JSON::XS::decode_json($body);
1278 if ($response->{'ErrorCode'} != 0) {
1279 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1281 my $state = $response->{'Response'}{'StateString'};
1282 if ($state eq 'COMPLETE') {
1283 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1284 if (!defined($pgn) || !$pgn->read_game()) {
1285 warn "Error in parsing PGN\n";
1287 $pgn->quick_parse_game;
1289 my $moves = $pgn->moves;
1291 for my $move (@$moves) {
1293 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1294 push @uci_moves, $uci_move;
1297 result => $pgn->result,
1299 score => $response->{'Response'}{'Score'},
1303 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1304 # Try again in a second. Note that if we have changed
1305 # position in the meantime, we might query a completely
1306 # different position! But that's fine.
1308 die "Unknown response state " . $state;
1311 # Wait a second before we schedule another one.
1312 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1313 $tb_lookup_running = 0;
1314 schedule_tb_lookup();
1318 warn "Error in tablebase lookup: $@";
1320 # Don't try this one again, but don't block new lookups either.
1321 $tb_lookup_running = 0;
1326 my ($cmdline, $tag, $cb) = @_;
1327 return undef if (!defined($cmdline));
1328 return Engine->open($cmdline, $tag, $cb);
1331 sub col_letter_to_num {
1332 return ord(shift) - ord('a');
1335 sub row_letter_to_num {
1336 return 7 - (ord(shift) - ord('1'));
1339 sub parse_uci_move {
1341 my $from_col = col_letter_to_num(substr($move, 0, 1));
1342 my $from_row = row_letter_to_num(substr($move, 1, 1));
1343 my $to_col = col_letter_to_num(substr($move, 2, 1));
1344 my $to_row = row_letter_to_num(substr($move, 3, 1));
1345 my $promo = substr($move, 4, 1);
1346 return ($from_col, $from_row, $to_col, $to_row, $promo);