4 # remoteglot - Connects an abitrary UCI-speaking engine to a (live) PGN,
5 # for live analysis of relayed games.
7 # Copyright 2007 Steinar H. Gunderson <steinar+remoteglot@gunderson.no>
8 # Licensed under the GNU General Public License, version 2.
14 use Chess::PGN::Parse;
23 require 'Position.pm';
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
36 my $tb_lookup_running = 0;
37 my $last_written_json = undef;
39 # Persisted so we can restart.
40 # TODO: Figure out an appropriate way to deal with database restarts
41 # and/or Postgres going away entirely.
42 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
44 $dbh->{RaiseError} = 1;
48 open(UCILOG, ">ucilog.txt")
49 or die "ucilog.txt: $!";
50 print UCILOG "Log starting.\n";
54 open(TBLOG, ">tblog.txt")
55 or die "tblog.txt: $!";
56 print TBLOG "Log starting.\n";
61 umask 0022; # analysis.json should not be served to users.
63 # open the chess engine
64 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
65 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
68 my ($pos_calculating, $pos_calculating_second_engine);
70 # If not undef, we've started calculating this position but haven't ever given out
71 # any analysis for it, so we're on a forced timer to do so.
72 my $pos_calculating_started = undef;
74 # If not undef, we've output this position, but without a main PV, so we're on
75 # _another_ forced timer to do so.
76 my $pos_pv_started = undef;
77 my $last_output_had_pv = 0;
79 setoptions($engine, \%remoteglotconf::engine_config);
80 uciprint($engine, "ucinewgame");
82 if (defined($engine2)) {
83 setoptions($engine2, \%remoteglotconf::engine2_config);
84 uciprint($engine2, "setoption name MultiPV value 500");
85 uciprint($engine2, "ucinewgame");
88 print "Chess engine ready.\n";
90 if (defined($remoteglotconf::target)) {
91 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
92 my $target = $remoteglotconf::target;
94 $target =~ s#https://lichess.org/broadcast/.*/([^/]+)?$#https://lichess.org/api/stream/broadcast/round/$1.pgn#;
99 # Engine events have already been set up by Engine.pm.
103 my ($engine, $line, $primary) = @_;
105 return if $line =~ /(upper|lower)bound/;
107 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
108 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
110 # If we've sent a stop command, gobble up lines until we see bestmove.
111 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
112 $engine->{'stopping'} = 0;
114 if ($line =~ /^info/ && $line !~ / cluster /) {
115 my (@infos) = split / /, $line;
118 parse_infos($engine, @infos);
120 if ($line =~ /^id/) {
121 my (@ids) = split / /, $line;
124 parse_ids($engine, @ids);
129 my $getting_movelist = 0;
130 my $pos_for_movelist = undef;
131 my @uci_movelist = ();
132 my @pretty_movelist = ();
134 # Starts periodic fetching of PGNs from the given URL.
137 if ($url =~ m#^/#) { # Local file.
140 open my $fh, "<", $url
144 handle_pgn($pgn, '', $url);
148 $http_timer = AnyEvent->timer(after => $remoteglotconf::poll_frequency, cb => sub {
154 AnyEvent::HTTP::http_get($url,
156 handle_partial_pgn(@_, \$buffer, $url);
159 end_pgn(@_, \$buffer, $url);
164 my ($last_pgn_white, $last_pgn_black);
165 my @last_pgn_uci_moves = ();
166 my $pgn_hysteresis_counter = 0;
168 sub handle_partial_pgn {
169 my ($body, $header, $buffer, $url) = @_;
171 if ($stop_pgn_fetch) {
177 while ($$buffer =~ s/^\s*(.*)\n\n\n//s) {
178 handle_pgn($1, $url);
184 my ($body, $header, $buffer, $url) = @_;
185 handle_pgn($$buffer, $url);
187 $http_timer = AnyEvent->timer(after => $remoteglotconf::poll_frequency, cb => sub {
193 my ($body, $url) = @_;
195 my $pgn = Chess::PGN::Parse->new(undef, $body);
196 if (!defined($pgn)) {
197 warn "Error in parsing PGN from $url [body='$body']\n";
198 } elsif (!$pgn->read_game()) {
199 warn "Error in reading PGN game from $url [body='$body']\n";
200 } elsif ($body !~ /^\[/) {
201 warn "Malformed PGN from $url [body='$body']\n";
204 # Skip to the right game.
205 while (defined($remoteglotconf::pgn_filter) &&
206 !&$remoteglotconf::pgn_filter($pgn)) {
207 $pgn->read_game() or die "Out of games during filtering";
210 $pgn->parse_game({ save_comments => 'yes' });
211 my $white = $pgn->white;
212 my $black = $pgn->black;
213 $white =~ s/,.*//; # Remove first name.
214 $black =~ s/,.*//; # Remove first name.
215 my $tags = $pgn->tags();
217 if (exists($tags->{'FEN'})) {
218 $pos = Position->from_fen($tags->{'FEN'});
219 $pos->{'last_move'} = 'none';
220 $pos->{'player_w'} = $white;
221 $pos->{'player_b'} = $black;
222 $pos->{'start_fen'} = $tags->{'FEN'};
224 $pos = Position->start_pos($white, $black);
226 if (exists($tags->{'Variant'}) &&
227 $tags->{'Variant'} =~ /960|fischer/i) {
228 $pos->{'chess960'} = 1;
230 $pos->{'chess960'} = 0;
232 my $moves = $pgn->moves;
234 my @repretty_moves = ();
235 for my $move (@$moves) {
236 my ($npos, $uci_move) = $pos->make_pretty_move($move);
237 push @uci_moves, $uci_move;
239 # Re-prettyprint the move.
240 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
241 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
242 push @repretty_moves, $pretty;
245 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
246 $pos->{'result'} = $pgn->result;
249 my @extra_moves = ();
250 $pos = extend_from_manual_override($pos, \@repretty_moves, \@extra_moves);
251 extract_clock($pgn, $pos);
252 $pos->{'history'} = \@repretty_moves;
253 $pos->{'extra_moves'} = \@extra_moves;
255 # Sometimes, PGNs lose a move or two for a short while,
256 # or people push out new ones non-atomically.
257 # Thus, if we PGN doesn't change names but becomes
258 # shorter, we mistrust it for a few seconds.
260 if (defined($last_pgn_white) && defined($last_pgn_black) &&
261 $last_pgn_white eq $pgn->white &&
262 $last_pgn_black eq $pgn->black &&
263 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
264 if (++$pgn_hysteresis_counter < 3) {
269 $last_pgn_white = $pgn->white;
270 $last_pgn_black = $pgn->black;
271 @last_pgn_uci_moves = @uci_moves;
272 $pgn_hysteresis_counter = 0;
273 handle_position($pos);
277 warn "Error in parsing moves from $url: $@\n";
281 $http_timer = AnyEvent->timer(after => $remoteglotconf::poll_frequency, cb => sub {
286 sub handle_position {
288 find_clock_start($pos, $pos_calculating);
290 # If we're already chewing on this and there's nothing else in the queue,
292 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
293 $pos_calculating->{'result'} = $pos->{'result'};
294 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
295 $pos_calculating->{$key} //= $pos->{$key};
297 $pos_calculating->{'extra_moves'} = $pos->{'extra_moves'};
301 # If we're already thinking on something, stop and wait for the engine
303 if (defined($pos_calculating)) {
304 # Store the final data we have for this position in the history,
305 # with the precise clock information we just got from the new
306 # position. (Historic positions store the clock at the end of
309 # Do not output anything new to the main analysis; that's
310 # going to be obsolete really soon. (Exception: If we've never
311 # output anything for this move, ie., it didn't hit the 200ms
312 # limit, spit it out to the user anyway. It's probably a really
313 # fast blitz game or something, and it's good to show the moves
314 # as they come in even without great analysis.)
315 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
316 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
317 delete $pos_calculating->{'white_clock_target'};
318 delete $pos_calculating->{'black_clock_target'};
320 if (defined($pos_calculating_started)) {
325 $pos_calculating_started = [Time::HiRes::gettimeofday];
326 $pos_pv_started = undef;
328 # Ask the engine to stop; we will throw away its data until it
329 # sends us "bestmove", signaling the end of it.
330 $engine->{'stopping'} = 1;
331 uciprint($engine, "stop");
334 # It's wrong to just give the FEN (the move history is useful,
335 # and per the UCI spec, we should really have sent "ucinewgame"),
336 # but it's easier, and it works around a Stockfish repetition issue.
337 if ($engine->{'chess960'} != $pos->{'chess960'}) {
338 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
339 $engine->{'chess960'} = $pos->{'chess960'};
341 uciprint($engine, "position fen " . $pos->fen());
342 uciprint($engine, "go infinite");
343 $pos_calculating = $pos;
344 $pos_calculating_started = [Time::HiRes::gettimeofday];
345 $pos_pv_started = undef;
347 if (defined($engine2)) {
348 if (defined($pos_calculating_second_engine)) {
349 $engine2->{'stopping'} = 1;
350 uciprint($engine2, "stop");
352 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
353 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
354 $engine2->{'chess960'} = $pos->{'chess960'};
356 uciprint($engine2, "position fen " . $pos->fen());
357 uciprint($engine2, "go infinite");
358 $pos_calculating_second_engine = $pos;
359 $engine2->{'info'} = {};
362 $engine->{'info'} = {};
367 my ($engine, @x) = @_;
370 my $info = $engine->{'info'};
372 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
373 for my $i (0..$#x - 1) {
374 if ($x[$i] eq 'multipv') {
380 while (scalar @x > 0) {
381 if ($x[0] eq 'multipv') {
387 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
389 my $value = shift @x;
390 $info->{$key} = $value;
393 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
394 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
397 my $value = shift @x;
398 $info->{$key . $mpv} = $value;
401 if ($x[0] eq 'score') {
404 delete $info->{'score_cp' . $mpv};
405 delete $info->{'score_mate' . $mpv};
406 delete $info->{'splicepos' . $mpv};
408 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
411 $info->{'score_cp' . $mpv} = shift @x;
412 } elsif ($x[0] eq 'mate') {
414 $info->{'score_mate' . $mpv} = shift @x;
422 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
425 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
429 #print "unknown info '$x[0]', trying to recover...\n";
431 die "Unknown info '" . join(',', @x) . "'";
437 my ($engine, @x) = @_;
439 while (scalar @x > 0) {
440 if ($x[0] eq 'name') {
441 my $value = join(' ', @x);
442 $engine->{'id'}{'author'} = $value;
451 sub prettyprint_pv_no_cache {
452 my ($board, @pvs) = @_;
454 if (scalar @pvs == 0 || !defined($pvs[0])) {
460 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
461 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
469 my ($pos, @pvs) = @_;
471 my $cachekey = join('', @pvs);
472 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
473 return @{$pos->{'prettyprint_cache'}{$cachekey}};
475 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
476 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
481 my %tbprobe_cache = ();
483 sub complete_using_tbprobe {
484 my ($pos, $info, $mpv) = @_;
486 # We need Fathom installed to do standalone TB probes.
487 return if (!defined($remoteglotconf::fathom_cmdline));
489 # If we already have a mate, don't bother; in some cases, it would even be
490 # better than a tablebase score.
491 return if defined($info->{'score_mate' . $mpv});
493 # If we have a draw or near-draw score, there's also not much interesting
494 # we could add from a tablebase. We only really want mates.
495 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
497 # Run through the PV until we are at a 6-man position.
498 # TODO: We could in theory only have 5-man data.
499 my @pv = @{$info->{'pv' . $mpv}};
500 my $key = $pos->fen() . " " . join('', @pv);
503 if (exists($tbprobe_cache{$key})) {
504 my $c = $tbprobe_cache{$key};
505 @moves = @{$c->{'moves'}};
506 $splicepos = $c->{'splicepos'};
509 # Force doing at least one move of the PV.
510 my $move = shift @pv;
512 $pos = $pos->make_move(parse_uci_move($move));
515 while ($pos->num_pieces() > 7 && $#pv > -1) {
516 my $move = shift @pv;
518 $pos = $pos->make_move(parse_uci_move($move));
521 return if ($pos->num_pieces() > 7);
523 my $fen = $pos->fen();
524 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
525 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
526 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
527 $pgn->quick_parse_game;
529 # Splice the PV from the tablebase onto what we have so far.
530 $splicepos = scalar @moves;
531 for my $move (@{$pgn->moves}) {
532 last if $move eq '#';
533 last if $move eq '1-0';
534 last if $move eq '0-1';
535 last if $move eq '1/2-1/2';
537 ($pos, $uci_move) = $pos->make_pretty_move($move);
538 push @moves, $uci_move;
541 $tbprobe_cache{$key} = {
543 splicepos => $splicepos
547 $info->{'pv' . $mpv} = \@moves;
549 my $matelen = int((1 + scalar @moves) / 2);
550 if ((scalar @moves) % 2 == 0) {
551 $info->{'score_mate' . $mpv} = -$matelen;
553 $info->{'score_mate' . $mpv} = $matelen;
555 $info->{'splicepos' . $mpv} = $splicepos;
561 return if (!defined($pos_calculating));
563 my $info = $engine->{'info'};
565 # Don't update too often.
566 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
567 if (defined($pos_calculating_started)) {
568 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
569 $wait = $new_pos_wait if ($new_pos_wait < $wait);
571 if (!$last_output_had_pv && has_pv($info)) {
572 if (!defined($pos_pv_started)) {
573 $pos_pv_started = [Time::HiRes::gettimeofday];
575 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
576 # so give us just 200ms more to increase the quality and then force a display.
577 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
578 $wait = $new_pos_wait if ($new_pos_wait < $wait);
581 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
584 $pos_pv_started = undef;
586 # We're outputting something for this position now, so the special handling
587 # for new positions is off.
588 undef $pos_calculating_started;
591 # Some programs _always_ report MultiPV, even with only one PV.
592 # In this case, we simply use that data as if MultiPV was never
595 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
596 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
597 if (exists($info->{$key . '1'})) {
598 $info->{$key} = $info->{$key . '1'};
600 delete $info->{$key};
606 # Check the PVs first. if they're invalid, just wait, as our data
607 # is most likely out of sync. This isn't a very good solution, as
608 # it can frequently miss stuff, but it's good enough for most users.
612 if (exists($info->{'pv'})) {
613 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
617 while (exists($info->{'pv' . $mpv})) {
618 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
623 $engine->{'info'} = {};
627 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
628 if (exists($info->{'pv'})) {
629 complete_using_tbprobe($pos_calculating, $info, '');
633 while (exists($info->{'pv' . $mpv})) {
634 complete_using_tbprobe($pos_calculating, $info, $mpv);
640 $latest_update = [Time::HiRes::gettimeofday];
641 $last_output_had_pv = has_pv($info);
646 return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
647 return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
652 my $info = $engine->{'info'};
653 my $id = $engine->{'id'};
655 my $text = 'Analysis';
656 if ($pos_calculating->{'last_move'} ne 'none') {
657 if ($pos_calculating->{'toplay'} eq 'W') {
658 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
660 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
662 if (exists($id->{'name'})) {
667 if (exists($id->{'name'})) {
668 $text .= " by $id->{'name'}:\n\n";
673 return unless (exists($pos_calculating->{'board'}));
675 my $extra_moves = $pos_calculating->{'extra_moves'};
676 if (defined($extra_moves) && scalar @$extra_moves > 0) {
677 $text .= " Manual move extensions: " . join(' ', @$extra_moves) . "\n";
680 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
683 while (exists($info->{'pv' . $mpv})) {
684 $text .= sprintf " PV%2u", $mpv;
685 my $score = short_score($info, $pos_calculating, $mpv);
686 $text .= " ($score)" if (defined($score));
689 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
690 if ($info->{'tbhits' . $mpv} == 1) {
691 $tbhits = ", 1 tbhit";
693 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
697 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
698 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
699 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
703 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
709 my $score = long_score($info, $pos_calculating, '');
710 $text .= " $score\n" if defined($score);
711 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
714 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
715 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
716 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
718 if (exists($info->{'seldepth'})) {
719 $text .= sprintf " (%u selective)", $info->{'seldepth'};
721 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
722 if ($info->{'tbhits'} == 1) {
723 $text .= ", one Syzygy hit";
725 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
731 my @refutation_lines = ();
732 if (defined($engine2)) {
733 for (my $mpv = 1; $mpv < 500; ++$mpv) {
734 my $info = $engine2->{'info'};
735 last if (!exists($info->{'pv' . $mpv}));
737 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
738 my $pv = $info->{'pv' . $mpv};
739 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
740 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
741 if (scalar @pretty_pv > 5) {
742 @pretty_pv = @pretty_pv[0..4];
743 push @pretty_pv, "...";
745 my $key = $pretty_move;
746 my $line = sprintf(" %-6s %6s %3s %s",
748 short_score($info, $pos_calculating_second_engine, $mpv),
749 "d" . $info->{'depth' . $mpv},
750 join(', ', @pretty_pv));
751 push @refutation_lines, [ $key, $line ];
756 if ($#refutation_lines >= 0) {
757 $text .= "Shallow search of all legal moves:\n\n";
758 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
759 $text .= $line->[1] . "\n";
764 if ($last_text ne $text) {
765 print "
\e[H
\e[2J"; # clear the screen
772 my $historic_json_only = shift;
773 my $info = $engine->{'info'};
776 $json->{'position'} = $pos_calculating->to_json_hash();
777 $json->{'engine'} = $engine->{'id'};
778 if (defined($remoteglotconf::engine_url)) {
779 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
781 if (defined($remoteglotconf::engine_details)) {
782 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
784 my @grpc_backends = ();
785 if (defined($remoteglotconf::engine_grpc_backend)) {
786 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
788 if (defined($remoteglotconf::engine2_grpc_backend)) {
789 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
791 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
792 if (defined($remoteglotconf::move_source)) {
793 $json->{'move_source'} = $remoteglotconf::move_source;
795 if (defined($remoteglotconf::move_source_url)) {
796 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
798 $json->{'score'} = score_digest($info, $pos_calculating, '');
800 $json->{'nodes'} = $info->{'nodes'};
801 $json->{'nps'} = $info->{'nps'};
802 $json->{'depth'} = $info->{'depth'};
803 $json->{'tbhits'} = $info->{'tbhits'};
804 $json->{'seldepth'} = $info->{'seldepth'};
805 $json->{'tablebase'} = $info->{'tablebase'};
806 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
808 my %refutation_lines = ();
809 my @refutation_lines = ();
810 if (defined($engine2)) {
811 for (my $mpv = 1; $mpv < 500; ++$mpv) {
812 my $info = $engine2->{'info'};
813 my $pretty_move = "";
815 last if (!exists($info->{'pv' . $mpv}));
818 complete_using_tbprobe($pos_calculating, $info, $mpv);
819 my $pv = $info->{'pv' . $mpv};
820 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
821 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
822 $refutation_lines{$pretty_move} = {
823 depth => $info->{'depth' . $mpv},
824 score => score_digest($info, $pos_calculating, $mpv),
825 move => $pretty_move,
828 if (exists($info->{'splicepos' . $mpv})) {
829 $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
834 $json->{'refutation_lines'} = \%refutation_lines;
836 # Piece together historic score information, to the degree we have it.
837 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
838 my %score_history = ();
840 local $dbh->{AutoCommit} = 0;
841 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
843 if (exists($pos_calculating->{'start_fen'})) {
844 $pos = Position->from_fen($pos_calculating->{'start_fen'});
846 $pos = Position->start_pos('white', 'black');
848 $pos->{'chess960'} = $pos_calculating->{'chess960'};
849 my $halfmove_num = 0;
850 for my $move (@{$pos_calculating->{'history'}}) {
851 my $id = id_for_pos($pos, $halfmove_num);
852 my $ref = $dbh->selectrow_hashref($q, undef, $id);
854 $score_history{$halfmove_num} = [
855 $ref->{'score_type'},
856 $ref->{'score_value'}
860 ($pos) = $pos->make_pretty_move($move);
865 # If at any point we are missing 10 consecutive moves,
866 # truncate the history there. This is so we don't get into
867 # a situation where we e.g. start analyzing at move 45,
868 # but we have analysis for 1. e4 from some completely different game
869 # and thus show a huge hole.
870 my $consecutive_missing = 0;
871 my $truncate_until = 0;
872 for (my $i = $halfmove_num; $i --> 0; ) {
873 if ($consecutive_missing >= 10) {
874 delete $score_history{$i};
877 if (exists($score_history{$i})) {
878 $consecutive_missing = 0;
880 ++$consecutive_missing;
884 $json->{'score_history'} = \%score_history;
887 # Give out a list of other games going on. (Empty is fine.)
888 # TODO: Don't bother reading our own file, the data will be stale anyway.
889 if (!$historic_json_only) {
892 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
894 while (my $ref = $q->fetchrow_hashref) {
896 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
897 my $other_game_json = JSON::XS::decode_json($other_game_contents);
899 die "Missing position" if (!exists($other_game_json->{'position'}));
900 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
901 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
905 name => "$white–$black",
906 url => $ref->{'url'},
907 hashurl => $ref->{'hash_url'},
909 if (defined($other_game_json->{'position'}{'result'})) {
910 $game->{'result'} = $other_game_json->{'position'}{'result'};
912 $game->{'score'} = $other_game_json->{'score'};
917 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
921 if (scalar @games > 0) {
922 $json->{'games'} = \@games;
926 my $json_enc = JSON::XS->new;
927 $json_enc->canonical(1);
928 my $encoded = $json_enc->encode($json);
929 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
930 (defined($last_written_json) && $last_written_json eq $encoded)) {
931 atomic_set_contents($remoteglotconf::json_output, $encoded);
932 $last_written_json = $encoded;
935 if (exists($pos_calculating->{'history'}) &&
936 defined($remoteglotconf::json_history_dir) && defined($json->{'engine'}{name})) {
937 my $id = id_for_pos($pos_calculating);
938 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
940 # Overwrite old analysis (assuming it exists at all) if we're
941 # using a different engine, or if we've calculated deeper.
942 # nodes is used as a tiebreaker. Don't bother about Multi-PV
943 # data; it's not that important.
944 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
945 my $new_depth = $json->{'depth'} // 0;
946 my $new_nodes = $json->{'nodes'} // 0;
947 if (!defined($old_engine) ||
948 $old_engine ne $json->{'engine'}{'name'} ||
949 $new_depth > $old_depth ||
950 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
951 atomic_set_contents($filename, $encoded);
952 if (defined($json->{'score'})) {
953 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
954 ' ON CONFLICT (id) DO UPDATE SET ' .
955 ' score_type=EXCLUDED.score_type, ' .
956 ' score_value=EXCLUDED.score_value, ' .
957 ' engine=EXCLUDED.engine, ' .
958 ' depth=EXCLUDED.depth, ' .
959 ' nodes=EXCLUDED.nodes',
961 $id, $json->{'score'}[0], $json->{'score'}[1],
962 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
968 sub atomic_set_contents {
969 my ($filename, $contents) = @_;
971 open my $fh, ">", $filename . ".tmp"
975 rename($filename . ".tmp", $filename);
979 my ($pos, $halfmove_num) = @_;
981 $halfmove_num //= scalar @{$pos->{'history'}};
982 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
983 return "move$halfmove_num-$fen";
986 sub get_json_analysis_stats {
988 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
990 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
997 my ($engine, $msg) = @_;
998 $engine->print($msg);
999 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1003 my ($info, $pos, $mpv) = @_;
1005 my $invert = ($pos->{'toplay'} eq 'B');
1006 if (defined($info->{'score_mate' . $mpv})) {
1008 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1010 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1013 if (exists($info->{'score_cp' . $mpv})) {
1014 my $score = $info->{'score_cp' . $mpv} * 0.01;
1016 if ($info->{'tablebase'}) {
1025 return sprintf "%+5.2f", $score;
1032 # Sufficient for computing long_score, short_score, plot_score and
1033 # (with side-to-play information) score_sort_key.
1035 my ($info, $pos, $mpv) = @_;
1037 if (defined($info->{'score_mate' . $mpv})) {
1038 my $mate = $info->{'score_mate' . $mpv};
1039 if ($pos->{'toplay'} eq 'B') {
1042 if (exists($info->{'splicepos' . $mpv})) {
1043 my $sp = $info->{'splicepos' . $mpv};
1051 return ['M', $mate];
1052 } elsif ($mate < 0) {
1053 return ['m', -$mate];
1054 } elsif ($pos->{'toplay'} eq 'B') {
1061 if (exists($info->{'score_cp' . $mpv})) {
1062 my $score = $info->{'score_cp' . $mpv};
1063 if ($pos->{'toplay'} eq 'B') {
1066 if ($score == 0 && $info->{'tablebase'}) {
1067 return ['d', undef];
1069 return ['cp', int($score)];
1078 my ($info, $pos, $mpv) = @_;
1080 if (defined($info->{'score_mate' . $mpv})) {
1081 my $mate = $info->{'score_mate' . $mpv};
1082 if ($pos->{'toplay'} eq 'B') {
1085 if (exists($info->{'splicepos' . $mpv})) {
1086 my $sp = $info->{'splicepos' . $mpv};
1088 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1090 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1094 return sprintf "White mates in %u", $mate;
1096 return sprintf "Black mates in %u", -$mate;
1100 if (exists($info->{'score_cp' . $mpv})) {
1101 my $score = $info->{'score_cp' . $mpv} * 0.01;
1103 if ($info->{'tablebase'}) {
1104 return "Theoretical draw";
1106 return "Score: 0.00";
1109 if ($pos->{'toplay'} eq 'B') {
1112 return sprintf "Score: %+5.2f", $score;
1119 # For graphs; a single number in centipawns, capped at +/- 500.
1121 my ($info, $pos, $mpv) = @_;
1123 my $invert = ($pos->{'toplay'} eq 'B');
1124 if (defined($info->{'score_mate' . $mpv})) {
1125 my $mate = $info->{'score_mate' . $mpv};
1135 if (exists($info->{'score_cp' . $mpv})) {
1136 my $score = $info->{'score_cp' . $mpv};
1140 $score = 500 if ($score > 500);
1141 $score = -500 if ($score < -500);
1149 sub extend_from_manual_override {
1150 my ($pos, $moves, $extra_moves) = @_;
1152 my $q = $dbh->prepare('SELECT next_move FROM game_extensions WHERE fen=? AND history=? AND player_w=? AND player_b=? AND (CURRENT_TIMESTAMP - ts) < INTERVAL \'1 hour\'');
1154 my $player_w = $pos->{'player_w'};
1155 my $player_b = $pos->{'player_b'};
1156 if ($player_w =~ /^base64:(.*)$/) {
1157 $player_w = MIME::Base64::decode_base64($1);
1159 if ($player_b =~ /^base64:(.*)$/) {
1160 $player_b = MIME::Base64::decode_base64($1);
1162 #use Data::Dumper; print Dumper([$pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b]);
1163 $q->execute($pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b);
1164 my $ref = $q->fetchrow_hashref;
1165 if (defined($ref)) {
1166 my $move = $ref->{'next_move'};
1167 ($pos) = $pos->make_pretty_move($move);
1168 push @$moves, $move;
1169 push @$extra_moves, $move;
1178 my ($pgn, $pos) = @_;
1180 # Look for extended PGN clock tags.
1181 my $tags = $pgn->tags;
1182 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1183 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1184 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1188 # Look for TCEC-style time comments.
1189 my $moves = $pgn->moves;
1190 my $comments = $pgn->comments;
1191 my $last_black_move = int((scalar @$moves) / 2);
1192 my $last_white_move = int((1 + scalar @$moves) / 2);
1194 my $black_key = $last_black_move . "b";
1195 my $white_key = $last_white_move . "w";
1197 if (exists($comments->{$white_key}) &&
1198 exists($comments->{$black_key}) &&
1199 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1200 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1201 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1202 $pos->{'white_clock'} = hms_to_sec($1);
1203 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1204 $pos->{'black_clock'} = hms_to_sec($1);
1208 delete $pos->{'white_clock'};
1209 delete $pos->{'black_clock'};
1214 return undef if (!defined($hms));
1215 $hms =~ /(\d+):(\d+):(\d+)/;
1216 return $1 * 3600 + $2 * 60 + $3;
1219 sub find_clock_start {
1220 my ($pos, $prev_pos) = @_;
1222 # If the game is over, the clock is stopped.
1223 if (exists($pos->{'result'}) &&
1224 ($pos->{'result'} eq '1-0' ||
1225 $pos->{'result'} eq '1/2-1/2' ||
1226 $pos->{'result'} eq '0-1')) {
1230 # When we don't have any moves, we assume the clock hasn't started yet.
1231 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1232 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1233 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1238 # The history is needed for id_for_pos.
1239 if (!exists($pos->{'history'})) {
1243 my $id = id_for_pos($pos);
1244 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=? AND COALESCE(white_clock_target, black_clock_target) >= EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - INTERVAL \'1 day\'));', undef, $id);
1245 if (defined($clock_info)) {
1246 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1247 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1248 if ($pos->{'toplay'} eq 'W') {
1249 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1251 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1256 # OK, we haven't seen this position before, so we assume the move
1257 # happened right now.
1259 # See if we should do our own clock management (ie., clock information
1260 # is spurious or non-existent).
1261 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1262 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1263 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1264 if (defined($prev_pos->{'white_clock_target'})) {
1265 $wc = $prev_pos->{'white_clock_target'} - time;
1267 if (defined($prev_pos->{'black_clock_target'})) {
1268 $bc = $prev_pos->{'black_clock_target'} - time;
1270 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1271 $pos->{'white_clock'} = $wc;
1272 $pos->{'black_clock'} = $bc;
1275 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1276 if (!exists($pos->{$key})) {
1277 # No clock information.
1280 my $time_left = $pos->{$key};
1281 my ($white_clock_target, $black_clock_target);
1282 if ($pos->{'toplay'} eq 'W') {
1283 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1285 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1287 local $dbh->{AutoCommit} = 0;
1288 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1289 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1290 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1295 my ($cmdline, $tag, $cb) = @_;
1296 return undef if (!defined($cmdline));
1297 return Engine->open($cmdline, $tag, $cb);
1300 sub col_letter_to_num {
1301 return ord(shift) - ord('a');
1304 sub row_letter_to_num {
1305 return 7 - (ord(shift) - ord('1'));
1308 sub parse_uci_move {
1310 my $from_col = col_letter_to_num(substr($move, 0, 1));
1311 my $from_row = row_letter_to_num(substr($move, 1, 1));
1312 my $to_col = col_letter_to_num(substr($move, 2, 1));
1313 my $to_row = row_letter_to_num(substr($move, 3, 1));
1314 my $promo = substr($move, 4, 1);
1315 return ($from_row, $from_col, $to_row, $to_col, $promo);
1319 my ($engine, $config) = @_;
1320 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1321 uciprint($engine, "setoption name Analysis Contempt value Off");
1322 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1323 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1325 while (my ($key, $value) = each %$config) {
1326 next if $key eq 'Threads';
1327 uciprint($engine, "setoption name $key value $value");