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;
26 require 'Position.pm';
34 my $latest_update = undef;
35 my $output_timer = undef;
36 my $http_timer = undef;
37 my $stop_pgn_fetch = 0;
38 my $tb_retry_timer = undef;
40 my $tb_lookup_running = 0;
41 my $last_written_json = undef;
43 # Persisted so we can restart.
44 # TODO: Figure out an appropriate way to deal with database restarts
45 # and/or Postgres going away entirely.
46 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
48 $dbh->{RaiseError} = 1;
52 open(FICSLOG, ">ficslog.txt")
53 or die "ficslog.txt: $!";
54 print FICSLOG "Log starting.\n";
58 open(UCILOG, ">ucilog.txt")
59 or die "ucilog.txt: $!";
60 print UCILOG "Log starting.\n";
64 open(TBLOG, ">tblog.txt")
65 or die "tblog.txt: $!";
66 print TBLOG "Log starting.\n";
72 # open the chess engine
73 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
74 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
77 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
79 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81 uciprint($engine, "setoption name $key value $value");
83 uciprint($engine, "ucinewgame");
85 if (defined($engine2)) {
86 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88 uciprint($engine2, "setoption name $key value $value");
90 uciprint($engine2, "setoption name MultiPV value 500");
91 uciprint($engine2, "ucinewgame");
94 print "Chess engine ready.\n";
97 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
109 my $ev1 = AnyEvent->io(
112 cb => sub { # what callback to execute
114 my $line = $t->getline(Timeout => 0, errmode => 'return');
115 return if (!defined($line));
123 if (defined($remoteglotconf::target)) {
124 if ($remoteglotconf::target =~ /^http:/) {
125 fetch_pgn($remoteglotconf::target);
127 $t->cmd("observe $remoteglotconf::target");
130 print "FICS ready.\n";
132 # Engine events have already been set up by Engine.pm.
136 my ($engine, $line, $primary) = @_;
138 return if $line =~ /(upper|lower)bound/;
140 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
141 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142 if ($line =~ /^info/) {
143 my (@infos) = split / /, $line;
146 parse_infos($engine, @infos);
148 if ($line =~ /^id/) {
149 my (@ids) = split / /, $line;
152 parse_ids($engine, @ids);
154 if ($line =~ /^bestmove/) {
156 return if (!$remoteglotconf::uci_assume_full_compliance);
157 if (defined($pos_waiting)) {
158 uciprint($engine, "position fen " . $pos_waiting->fen());
159 uciprint($engine, "go infinite");
161 $pos_calculating = $pos_waiting;
162 $pos_waiting = undef;
165 $engine2->{'info'} = {};
166 my $pos = $pos_waiting // $pos_calculating;
167 uciprint($engine2, "position fen " . $pos->fen());
168 uciprint($engine2, "go infinite");
169 $pos_calculating_second_engine = $pos;
175 my $getting_movelist = 0;
176 my $pos_for_movelist = undef;
177 my @uci_movelist = ();
178 my @pretty_movelist = ();
182 if ($line =~ /^<12> /) {
183 handle_position(Position->new($line));
186 if ($line =~ /^Movelist for game /) {
187 my $pos = $pos_waiting // $pos_calculating;
190 @pretty_movelist = ();
191 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
192 $getting_movelist = 1;
195 if ($getting_movelist &&
196 $line =~ /^\s* \d+\. \s+ # move number
197 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
198 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
202 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
203 push @uci_movelist, $uci_move;
204 push @pretty_movelist, $1;
207 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
208 push @uci_movelist, $uci_move;
209 push @pretty_movelist, $2;
213 warn "Error when getting FICS move history: $@";
214 $getting_movelist = 0;
217 if ($getting_movelist &&
218 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
220 for my $pos ($pos_waiting, $pos_calculating) {
221 next if (!defined($pos));
222 if ($pos->fen() eq $pos_for_movelist->fen()) {
223 $pos->{'pretty_history'} = \@pretty_movelist;
226 $getting_movelist = 0;
228 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
229 my ($who, $msg) = ($1, $2);
231 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
233 if ($msg =~ /^fics (.*?)$/) {
234 $t->cmd("tell $who Executing '$1' on FICS.");
236 } elsif ($msg =~ /^uci (.*?)$/) {
237 $t->cmd("tell $who Sending '$1' to the engine.");
238 print { $engine->{'write'} } "$1\n";
239 } elsif ($msg =~ /^pgn (.*?)$/) {
241 $t->cmd("tell $who Starting to poll '$url'.");
243 } elsif ($msg =~ /^stoppgn$/) {
244 $t->cmd("tell $who Stopping poll.");
247 } elsif ($msg =~ /^quit$/) {
248 $t->cmd("tell $who Bye bye.");
251 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
254 #print "FICS: [$line]\n";
257 # Starts periodic fetching of PGNs from the given URL.
260 AnyEvent::HTTP::http_get($url, sub {
261 handle_pgn(@_, $url);
265 my ($last_pgn_white, $last_pgn_black);
266 my @last_pgn_uci_moves = ();
267 my $pgn_hysteresis_counter = 0;
270 my ($body, $header, $url) = @_;
272 if ($stop_pgn_fetch) {
278 my $pgn = Chess::PGN::Parse->new(undef, $body);
279 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
280 warn "Error in parsing PGN from $url\n";
283 # Skip to the right game.
284 while (defined($remoteglotconf::pgn_filter) &&
285 !&$remoteglotconf::pgn_filter($pgn)) {
286 $pgn->read_game() or die "Out of games during filtering";
289 $pgn->parse_game({ save_comments => 'yes' });
290 my $pos = Position->start_pos($pgn->white, $pgn->black);
291 my $moves = $pgn->moves;
293 for my $move (@$moves) {
295 ($pos, $uci_move) = $pos->make_pretty_move($move);
296 push @uci_moves, $uci_move;
298 $pos->{'result'} = $pgn->result;
299 $pos->{'pretty_history'} = $moves;
301 extract_clock($pgn, $pos);
303 # Sometimes, PGNs lose a move or two for a short while,
304 # or people push out new ones non-atomically.
305 # Thus, if we PGN doesn't change names but becomes
306 # shorter, we mistrust it for a few seconds.
308 if (defined($last_pgn_white) && defined($last_pgn_black) &&
309 $last_pgn_white eq $pgn->white &&
310 $last_pgn_black eq $pgn->black &&
311 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
312 if (++$pgn_hysteresis_counter < 3) {
317 $last_pgn_white = $pgn->white;
318 $last_pgn_black = $pgn->black;
319 @last_pgn_uci_moves = @uci_moves;
320 $pgn_hysteresis_counter = 0;
321 handle_position($pos);
325 warn "Error in parsing moves from $url: $@\n";
329 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
334 sub handle_position {
336 find_clock_start($pos, $pos_calculating);
338 # if this is already in the queue, ignore it (just update the result)
339 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
340 $pos_waiting->{'result'} = $pos->{'result'};
344 # if we're already chewing on this and there's nothing else in the queue,
346 if (!defined($pos_waiting) && defined($pos_calculating) &&
347 $pos->fen() eq $pos_calculating->fen()) {
348 $pos_calculating->{'result'} = $pos->{'result'};
352 # if we're already thinking on something, stop and wait for the engine
354 if (defined($pos_calculating)) {
355 # Store the final data we have for this position in the history,
356 # with the precise clock information we just got from the new
357 # position. (Historic positions store the clock at the end of
360 # Do not output anything new to the main analysis; that's
361 # going to be obsolete really soon.
362 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
363 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
364 delete $pos_calculating->{'white_clock_target'};
365 delete $pos_calculating->{'black_clock_target'};
368 if (!defined($pos_waiting)) {
369 uciprint($engine, "stop");
371 if ($remoteglotconf::uci_assume_full_compliance) {
374 uciprint($engine, "position fen " . $pos->fen());
375 uciprint($engine, "go infinite");
376 $pos_calculating = $pos;
379 # it's wrong just to give the FEN (the move history is useful,
380 # and per the UCI spec, we should really have sent "ucinewgame"),
382 uciprint($engine, "position fen " . $pos->fen());
383 uciprint($engine, "go infinite");
384 $pos_calculating = $pos;
387 if (defined($engine2)) {
388 if (defined($pos_calculating_second_engine)) {
389 uciprint($engine2, "stop");
391 uciprint($engine2, "position fen " . $pos->fen());
392 uciprint($engine2, "go infinite");
393 $pos_calculating_second_engine = $pos;
395 $engine2->{'info'} = {};
398 $engine->{'info'} = {};
401 schedule_tb_lookup();
404 # Output a command every move to note that we're
405 # still paying attention -- this is a good tradeoff,
406 # since if no move has happened in the last half
407 # hour, the analysis/relay has most likely stopped
408 # and we should stop hogging server resources.
414 my ($engine, @x) = @_;
417 my $info = $engine->{'info'};
419 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
420 for my $i (0..$#x - 1) {
421 if ($x[$i] eq 'multipv') {
427 while (scalar @x > 0) {
428 if ($x[0] eq 'multipv') {
434 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
436 my $value = shift @x;
437 $info->{$key} = $value;
440 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
441 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
444 my $value = shift @x;
445 $info->{$key . $mpv} = $value;
448 if ($x[0] eq 'score') {
451 delete $info->{'score_cp' . $mpv};
452 delete $info->{'score_mate' . $mpv};
454 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
457 $info->{'score_cp' . $mpv} = shift @x;
458 } elsif ($x[0] eq 'mate') {
460 $info->{'score_mate' . $mpv} = shift @x;
468 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
471 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
475 #print "unknown info '$x[0]', trying to recover...\n";
477 die "Unknown info '" . join(',', @x) . "'";
483 my ($engine, @x) = @_;
485 while (scalar @x > 0) {
486 if ($x[0] =~ /^(name|author)$/) {
488 my $value = join(' ', @x);
489 $engine->{'id'}{$key} = $value;
498 sub prettyprint_pv_no_cache {
499 my ($board, @pvs) = @_;
501 if (scalar @pvs == 0 || !defined($pvs[0])) {
506 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
507 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
508 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
512 my ($pos, @pvs) = @_;
514 my $cachekey = join('', @pvs);
515 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
516 return @{$pos->{'prettyprint_cache'}{$cachekey}};
518 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
519 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
527 return if (!defined($pos_calculating));
529 # Don't update too often.
530 my $age = Time::HiRes::tv_interval($latest_update);
531 if ($age < $remoteglotconf::update_max_interval) {
532 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
533 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
537 my $info = $engine->{'info'};
540 # If we have tablebase data from a previous lookup, replace the
541 # engine data with the data from the tablebase.
543 my $fen = $pos_calculating->fen();
544 if (exists($tb_cache{$fen})) {
545 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
546 delete $info->{$key . '1'};
547 delete $info->{$key};
549 $info->{'nodes'} = 0;
551 $info->{'depth'} = 0;
552 $info->{'seldepth'} = 0;
553 $info->{'tbhits'} = 0;
555 my $t = $tb_cache{$fen};
557 my $matelen = int((1 + $t->{'score'}) / 2);
558 if ($t->{'result'} eq '1/2-1/2') {
559 $info->{'score_cp'} = 0;
560 } elsif ($t->{'result'} eq '1-0') {
561 if ($pos_calculating->{'toplay'} eq 'B') {
562 $info->{'score_mate'} = -$matelen;
564 $info->{'score_mate'} = $matelen;
567 if ($pos_calculating->{'toplay'} eq 'B') {
568 $info->{'score_mate'} = $matelen;
570 $info->{'score_mate'} = -$matelen;
574 $info->{'tablebase'} = 1;
576 $info->{'tablebase'} = 0;
580 # Some programs _always_ report MultiPV, even with only one PV.
581 # In this case, we simply use that data as if MultiPV was never
584 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
585 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
586 if (exists($info->{$key . '1'})) {
587 $info->{$key} = $info->{$key . '1'};
593 # Check the PVs first. if they're invalid, just wait, as our data
594 # is most likely out of sync. This isn't a very good solution, as
595 # it can frequently miss stuff, but it's good enough for most users.
599 if (exists($info->{'pv'})) {
600 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
604 while (exists($info->{'pv' . $mpv})) {
605 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
610 $engine->{'info'} = {};
616 $latest_update = [Time::HiRes::gettimeofday];
620 my $info = $engine->{'info'};
621 my $id = $engine->{'id'};
623 my $text = 'Analysis';
624 if ($pos_calculating->{'last_move'} ne 'none') {
625 if ($pos_calculating->{'toplay'} eq 'W') {
626 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
628 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
630 if (exists($id->{'name'})) {
635 if (exists($id->{'name'})) {
636 $text .= " by $id->{'name'}:\n\n";
641 return unless (exists($pos_calculating->{'board'}));
643 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
646 while (exists($info->{'pv' . $mpv})) {
647 $text .= sprintf " PV%2u", $mpv;
648 my $score = short_score($info, $pos_calculating, $mpv);
649 $text .= " ($score)" if (defined($score));
652 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
653 if ($info->{'tbhits' . $mpv} == 1) {
654 $tbhits = ", 1 tbhit";
656 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
660 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
661 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
662 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
666 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
672 my $score = long_score($info, $pos_calculating, '');
673 $text .= " $score\n" if defined($score);
674 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
677 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
678 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
679 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
681 if (exists($info->{'seldepth'})) {
682 $text .= sprintf " (%u selective)", $info->{'seldepth'};
684 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
685 if ($info->{'tbhits'} == 1) {
686 $text .= ", one Syzygy hit";
688 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
694 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
696 my @refutation_lines = ();
697 if (defined($engine2)) {
698 for (my $mpv = 1; $mpv < 500; ++$mpv) {
699 my $info = $engine2->{'info'};
700 last if (!exists($info->{'pv' . $mpv}));
702 my $pv = $info->{'pv' . $mpv};
704 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
705 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
706 if (scalar @pretty_pv > 5) {
707 @pretty_pv = @pretty_pv[0..4];
708 push @pretty_pv, "...";
710 my $key = $pretty_move;
711 my $line = sprintf(" %-6s %6s %3s %s",
713 short_score($info, $pos_calculating_second_engine, $mpv),
714 "d" . $info->{'depth' . $mpv},
715 join(', ', @pretty_pv));
716 push @refutation_lines, [ $key, $line ];
721 if ($#refutation_lines >= 0) {
722 $text .= "Shallow search of all legal moves:\n\n";
723 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
724 $text .= $line->[1] . "\n";
729 if ($last_text ne $text) {
730 print "
\e[H
\e[2J"; # clear the screen
737 my $historic_json_only = shift;
738 my $info = $engine->{'info'};
741 $json->{'position'} = $pos_calculating->to_json_hash();
742 $json->{'id'} = $engine->{'id'};
743 $json->{'score'} = long_score($info, $pos_calculating, '');
744 $json->{'short_score'} = short_score($info, $pos_calculating, '');
745 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
747 $json->{'nodes'} = $info->{'nodes'};
748 $json->{'nps'} = $info->{'nps'};
749 $json->{'depth'} = $info->{'depth'};
750 $json->{'tbhits'} = $info->{'tbhits'};
751 $json->{'seldepth'} = $info->{'seldepth'};
752 $json->{'tablebase'} = $info->{'tablebase'};
754 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
755 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
757 my %refutation_lines = ();
758 my @refutation_lines = ();
759 if (defined($engine2)) {
760 for (my $mpv = 1; $mpv < 500; ++$mpv) {
761 my $info = $engine2->{'info'};
762 my $pretty_move = "";
764 last if (!exists($info->{'pv' . $mpv}));
767 my $pv = $info->{'pv' . $mpv};
768 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
769 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
770 $refutation_lines{$pv->[0]} = {
771 sort_key => $pretty_move,
772 depth => $info->{'depth' . $mpv},
773 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
774 pretty_score => short_score($info, $pos_calculating, $mpv),
775 pretty_move => $pretty_move,
776 pv_pretty => \@pretty_pv,
781 $json->{'refutation_lines'} = \%refutation_lines;
783 # Piece together historic score information, to the degree we have it.
784 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
785 my %score_history = ();
787 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
788 my $pos = Position->start_pos('white', 'black');
789 my $halfmove_num = 0;
790 for my $move (@{$pos_calculating->{'pretty_history'}}) {
791 my $id = id_for_pos($pos, $halfmove_num);
792 my $ref = $dbh->selectrow_hashref($q, undef, $id);
794 $score_history{$halfmove_num} = [
795 $ref->{'plot_score'},
796 $ref->{'short_score'}
800 ($pos) = $pos->make_pretty_move($move);
804 # If at any point we are missing 10 consecutive moves,
805 # truncate the history there. This is so we don't get into
806 # a situation where we e.g. start analyzing at move 45,
807 # but we have analysis for 1. e4 from some completely different game
808 # and thus show a huge hole.
809 my $consecutive_missing = 0;
810 my $truncate_until = 0;
811 for (my $i = $halfmove_num; $i --> 0; ) {
812 if ($consecutive_missing >= 10) {
813 delete $score_history{$i};
816 if (exists($score_history{$i})) {
817 $consecutive_missing = 0;
819 ++$consecutive_missing;
823 $json->{'score_history'} = \%score_history;
826 my $json_enc = JSON::XS->new;
827 $json_enc->canonical(1);
828 my $encoded = $json_enc->encode($json);
829 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
830 (defined($last_written_json) && $last_written_json eq $encoded)) {
831 atomic_set_contents($remoteglotconf::json_output, $encoded);
832 $last_written_json = $encoded;
835 if (exists($pos_calculating->{'pretty_history'}) &&
836 defined($remoteglotconf::json_history_dir)) {
837 my $id = id_for_pos($pos_calculating);
838 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
840 # Overwrite old analysis (assuming it exists at all) if we're
841 # using a different engine, or if we've calculated deeper.
842 # nodes is used as a tiebreaker. Don't bother about Multi-PV
843 # data; it's not that important.
844 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
845 my $new_depth = $json->{'depth'} // 0;
846 my $new_nodes = $json->{'nodes'} // 0;
847 if (!defined($old_engine) ||
848 $old_engine ne $json->{'id'}{'name'} ||
849 $new_depth > $old_depth ||
850 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
851 atomic_set_contents($filename, $encoded);
852 if (defined($json->{'plot_score'})) {
853 local $dbh->{AutoCommit} = 0;
854 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
855 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?)', undef,
856 $id, $json->{'plot_score'}, $json->{'short_score'},
857 $json->{'id'}{'name'}, $new_depth, $new_nodes);
864 sub atomic_set_contents {
865 my ($filename, $contents) = @_;
867 open my $fh, ">", $filename . ".tmp"
871 rename($filename . ".tmp", $filename);
875 my ($pos, $halfmove_num) = @_;
877 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
878 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
879 return "move$halfmove_num-$fen";
882 sub get_json_analysis_stats {
884 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
886 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'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 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1142 if (defined($clock_info)) {
1143 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1144 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1145 if ($pos->{'toplay'} eq 'W') {
1146 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1148 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1153 # OK, we haven't seen this position before, so we assume the move
1154 # happened right now.
1156 # See if we should do our own clock management (ie., clock information
1157 # is spurious or non-existent).
1158 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1159 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1160 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1161 if (defined($prev_pos->{'white_clock_target'})) {
1162 $wc = $prev_pos->{'white_clock_target'} - time;
1164 if (defined($prev_pos->{'black_clock_target'})) {
1165 $bc = $prev_pos->{'black_clock_target'} - time;
1167 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1168 $pos->{'white_clock'} = $wc;
1169 $pos->{'black_clock'} = $bc;
1172 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1173 if (!exists($pos->{$key})) {
1174 # No clock information.
1177 my $time_left = $pos->{$key};
1178 my ($white_clock_target, $black_clock_target);
1179 if ($pos->{'toplay'} eq 'W') {
1180 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1182 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1184 local $dbh->{AutoCommit} = 0;
1185 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1186 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1187 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1191 sub schedule_tb_lookup {
1192 return if (!defined($remoteglotconf::tb_serial_key));
1193 my $pos = $pos_waiting // $pos_calculating;
1194 return if (exists($tb_cache{$pos->fen()}));
1196 # If there's more than seven pieces, there's not going to be an answer,
1198 return if ($pos->num_pieces() > 7);
1200 # Max one at a time. If it's still relevant when it returns,
1201 # schedule_tb_lookup() will be called again.
1202 return if ($tb_lookup_running);
1204 $tb_lookup_running = 1;
1205 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1206 $remoteglotconf::tb_serial_key .
1207 '&auth.password=aquarium&type=0&fen=' .
1208 URI::Escape::uri_escape($pos->fen());
1209 print TBLOG "Downloading $url...\n";
1210 AnyEvent::HTTP::http_get($url, sub {
1211 handle_tb_lookup_return(@_, $pos, $pos->fen());
1215 sub handle_tb_lookup_return {
1216 my ($body, $header, $pos, $fen) = @_;
1217 print TBLOG "Response for [$fen]:\n";
1218 print TBLOG $header . "\n\n";
1219 print TBLOG $body . "\n\n";
1221 my $response = JSON::XS::decode_json($body);
1222 if ($response->{'ErrorCode'} != 0) {
1223 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1225 my $state = $response->{'Response'}{'StateString'};
1226 if ($state eq 'COMPLETE') {
1227 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1228 if (!defined($pgn) || !$pgn->read_game()) {
1229 warn "Error in parsing PGN\n";
1231 $pgn->quick_parse_game;
1233 my $moves = $pgn->moves;
1235 for my $move (@$moves) {
1237 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1238 push @uci_moves, $uci_move;
1241 result => $pgn->result,
1243 score => $response->{'Response'}{'Score'},
1247 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1248 # Try again in a second. Note that if we have changed
1249 # position in the meantime, we might query a completely
1250 # different position! But that's fine.
1252 die "Unknown response state " . $state;
1255 # Wait a second before we schedule another one.
1256 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1257 $tb_lookup_running = 0;
1258 schedule_tb_lookup();
1262 warn "Error in tablebase lookup: $@";
1264 # Don't try this one again, but don't block new lookups either.
1265 $tb_lookup_running = 0;
1270 my ($cmdline, $tag, $cb) = @_;
1271 return undef if (!defined($cmdline));
1272 return Engine->open($cmdline, $tag, $cb);
1275 sub col_letter_to_num {
1276 return ord(shift) - ord('a');
1279 sub row_letter_to_num {
1280 return 7 - (ord(shift) - ord('1'));
1283 sub parse_uci_move {
1285 my $from_col = col_letter_to_num(substr($move, 0, 1));
1286 my $from_row = row_letter_to_num(substr($move, 1, 1));
1287 my $to_col = col_letter_to_num(substr($move, 2, 1));
1288 my $to_row = row_letter_to_num(substr($move, 3, 1));
1289 my $promo = substr($move, 4, 1);
1290 return ($from_col, $from_row, $to_col, $to_row, $promo);