]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Show low-depth scores.
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
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.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <steinar+remoteglot@gunderson.no>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use File::Slurp;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 use DBI;
24 use DBD::Pg;
25 require 'Position.pm';
26 require 'Engine.pm';
27 require 'config.pm';
28 use strict;
29 use warnings;
30 no warnings qw(once);
31
32 # Program starts here
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;
38 my %tb_cache = ();
39 my $tb_lookup_running = 0;
40 my $last_written_json = undef;
41
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)
46         or die DBI->errstr;
47 $dbh->{RaiseError} = 1;
48
49 $| = 1;
50
51 open(FICSLOG, ">ficslog.txt")
52         or die "ficslog.txt: $!";
53 print FICSLOG "Log starting.\n";
54 select(FICSLOG);
55 $| = 1;
56
57 open(UCILOG, ">ucilog.txt")
58         or die "ucilog.txt: $!";
59 print UCILOG "Log starting.\n";
60 select(UCILOG);
61 $| = 1;
62
63 open(TBLOG, ">tblog.txt")
64         or die "tblog.txt: $!";
65 print TBLOG "Log starting.\n";
66 select(TBLOG);
67 $| = 1;
68
69 select(STDOUT);
70 umask 0022;  # analysis.json should not be served to users.
71
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); });
75 my $last_move;
76 my $last_text = '';
77 my ($pos_calculating, $pos_calculating_second_engine);
78
79 # If not undef, we've started calculating this position but haven't ever given out
80 # any analysis for it, so we're on a forced timer to do so.
81 my $pos_calculating_started = undef;
82
83 # If not undef, we've output this position, but without a main PV, so we're on
84 # _another_ forced timer to do so.
85 my $pos_pv_started = undef;
86 my $last_output_had_pv = 0;
87
88 setoptions($engine, \%remoteglotconf::engine_config);
89 uciprint($engine, "ucinewgame");
90
91 if (defined($engine2)) {
92         setoptions($engine2, \%remoteglotconf::engine2_config);
93         uciprint($engine2, "setoption name MultiPV value 500");
94         uciprint($engine2, "ucinewgame");
95 }
96
97 print "Chess engine ready.\n";
98
99 # now talk to FICS
100 my ($t, $ev1);
101 if (defined($remoteglotconf::server)) {
102         $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
103         $t->input_log(\*FICSLOG);
104         $t->open($remoteglotconf::server);
105         $t->print($remoteglotconf::nick);
106         $t->waitfor('/Press return to enter the server/');
107         $t->cmd("");
108
109         # set some options
110         $t->cmd("set shout 0");
111         $t->cmd("set seek 0");
112         $t->cmd("set style 12");
113
114         $ev1 = AnyEvent->io(
115                 fh => fileno($t),
116                 poll => 'r',
117                 cb => sub {    # what callback to execute
118                         while (1) {
119                                 my $line = $t->getline(Timeout => 0, errmode => 'return');
120                                 return if (!defined($line));
121
122                                 chomp $line;
123                                 $line =~ tr/\r//d;
124                                 handle_fics($line);
125                         }
126                 }
127         );
128 }
129 if (defined($remoteglotconf::target)) {
130         if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
131                 fetch_pgn($remoteglotconf::target);
132         } elsif (defined($t)) {
133                 $t->cmd("observe $remoteglotconf::target");
134         }
135 }
136 if (defined($t)) {
137         print "FICS ready.\n";
138 }
139
140 # Engine events have already been set up by Engine.pm.
141 EV::run;
142
143 sub handle_uci {
144         my ($engine, $line, $primary) = @_;
145
146         return if $line =~ /(upper|lower)bound/;
147
148         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
149         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
150
151         # If we've sent a stop command, gobble up lines until we see bestmove.
152         return if ($engine->{'stopping'} && $line !~ /^bestmove/);
153         $engine->{'stopping'} = 0;
154
155         if ($line =~ /^info/) {
156                 my (@infos) = split / /, $line;
157                 shift @infos;
158
159                 parse_infos($engine, @infos);
160         }
161         if ($line =~ /^id/) {
162                 my (@ids) = split / /, $line;
163                 shift @ids;
164
165                 parse_ids($engine, @ids);
166         }
167         output();
168 }
169
170 my $getting_movelist = 0;
171 my $pos_for_movelist = undef;
172 my @uci_movelist = ();
173 my @pretty_movelist = ();
174
175 sub handle_fics {
176         my $line = shift;
177         if ($line =~ /^<12> /) {
178                 handle_position(Position->new($line));
179                 $t->cmd("moves");
180         }
181         if ($line =~ /^Movelist for game /) {
182                 my $pos = $pos_calculating;
183                 if (defined($pos)) {
184                         @uci_movelist = ();
185                         @pretty_movelist = ();
186                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
187                         $getting_movelist = 1;
188                 }
189         }
190         if ($getting_movelist &&
191             $line =~ /^\s* \d+\. \s+                     # move number
192                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
193                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
194                      /x) {
195                 eval {
196                         my $uci_move;
197                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
198                         push @uci_movelist, $uci_move;
199                         push @pretty_movelist, $1;
200
201                         if (defined($2)) {
202                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
203                                 push @uci_movelist, $uci_move;
204                                 push @pretty_movelist, $2;
205                         }
206                 };
207                 if ($@) {
208                         warn "Error when getting FICS move history: $@";
209                         $getting_movelist = 0;
210                 }
211         }
212         if ($getting_movelist &&
213             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
214                 # End of movelist.
215                 if (defined($pos_calculating)) {
216                         if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
217                                 $pos_calculating->{'history'} = \@pretty_movelist;
218                         }
219                 }
220                 $getting_movelist = 0;
221         }
222         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
223                 my ($who, $msg) = ($1, $2);
224
225                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
226
227                 if ($msg =~ /^fics (.*?)$/) {
228                         $t->cmd("tell $who Executing '$1' on FICS.");
229                         $t->cmd($1);
230                 } elsif ($msg =~ /^uci (.*?)$/) {
231                         $t->cmd("tell $who Sending '$1' to the engine.");
232                         print { $engine->{'write'} } "$1\n";
233                 } elsif ($msg =~ /^pgn (.*?)$/) {
234                         my $url = $1;
235                         $t->cmd("tell $who Starting to poll '$url'.");
236                         fetch_pgn($url);
237                 } elsif ($msg =~ /^stoppgn$/) {
238                         $t->cmd("tell $who Stopping poll.");
239                         $stop_pgn_fetch = 1;
240                         $http_timer = undef;
241                 } elsif ($msg =~ /^quit$/) {
242                         $t->cmd("tell $who Bye bye.");
243                         exit;
244                 } else {
245                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
246                 }
247         }
248         #print "FICS: [$line]\n";
249 }
250
251 # Starts periodic fetching of PGNs from the given URL.
252 sub fetch_pgn {
253         my ($url) = @_;
254         if ($url =~ m#^/#) {  # Local file.
255                 eval {
256                         local $/ = undef;
257                         open my $fh, "<", $url
258                                 or die "$url: $!";
259                         my $pgn = <$fh>;
260                         close $fh;
261                         handle_pgn($pgn, '', $url);
262                 };
263                 if ($@) {
264                         warn "$url: $@";
265                         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
266                                 fetch_pgn($url);
267                         });
268                 }
269         } else {
270                 AnyEvent::HTTP::http_get($url, sub {
271                         handle_pgn(@_, $url);
272                 });
273         }
274 }
275
276 my ($last_pgn_white, $last_pgn_black);
277 my @last_pgn_uci_moves = ();
278 my $pgn_hysteresis_counter = 0;
279
280 sub handle_pgn {
281         my ($body, $header, $url) = @_;
282
283         if ($stop_pgn_fetch) {
284                 $stop_pgn_fetch = 0;
285                 $http_timer = undef;
286                 return;
287         }
288
289         my $pgn = Chess::PGN::Parse->new(undef, $body);
290         if (!defined($pgn)) {
291                 warn "Error in parsing PGN from $url [body='$body']\n";
292         } elsif (!$pgn->read_game()) {
293                 warn "Error in reading PGN game from $url [body='$body']\n";
294         } elsif ($body !~ /^\[/) {
295                 warn "Malformed PGN from $url [body='$body']\n";
296         } else {
297                 eval {
298                         # Skip to the right game.
299                         while (defined($remoteglotconf::pgn_filter) &&
300                                !&$remoteglotconf::pgn_filter($pgn)) {
301                                 $pgn->read_game() or die "Out of games during filtering";
302                         }
303
304                         $pgn->parse_game({ save_comments => 'yes' });
305                         my $white = $pgn->white;
306                         my $black = $pgn->black;
307                         $white =~ s/,.*//;  # Remove first name.
308                         $black =~ s/,.*//;  # Remove first name.
309                         my $tags = $pgn->tags();
310                         my $pos;
311                         if (exists($tags->{'FEN'})) {
312                                 $pos = Position->from_fen($tags->{'FEN'});
313                                 $pos->{'last_move'} = 'none';
314                                 $pos->{'player_w'} = $white;
315                                 $pos->{'player_b'} = $black;
316                                 $pos->{'start_fen'} = $tags->{'FEN'};
317                         } else {
318                                 $pos = Position->start_pos($white, $black);
319                         }
320                         if (exists($tags->{'Variant'}) &&
321                             $tags->{'Variant'} =~ /960|fischer/i) {
322                                 $pos->{'chess960'} = 1;
323                         } else {
324                                 $pos->{'chess960'} = 0;
325                         }
326                         my $moves = $pgn->moves;
327                         my @uci_moves = ();
328                         my @repretty_moves = ();
329                         for my $move (@$moves) {
330                                 my ($npos, $uci_move) = $pos->make_pretty_move($move);
331                                 push @uci_moves, $uci_move;
332
333                                 # Re-prettyprint the move.
334                                 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
335                                 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
336                                 push @repretty_moves, $pretty;
337                                 $pos = $npos;
338                         }
339                         if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
340                                 $pos->{'result'} = $pgn->result;
341                         }
342                         $pos->{'history'} = \@repretty_moves;
343
344                         extract_clock($pgn, $pos);
345
346                         # Sometimes, PGNs lose a move or two for a short while,
347                         # or people push out new ones non-atomically. 
348                         # Thus, if we PGN doesn't change names but becomes
349                         # shorter, we mistrust it for a few seconds.
350                         my $trust_pgn = 1;
351                         if (defined($last_pgn_white) && defined($last_pgn_black) &&
352                             $last_pgn_white eq $pgn->white &&
353                             $last_pgn_black eq $pgn->black &&
354                             scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
355                                 if (++$pgn_hysteresis_counter < 3) {
356                                         $trust_pgn = 0; 
357                                 }
358                         }
359                         if ($trust_pgn) {
360                                 $last_pgn_white = $pgn->white;
361                                 $last_pgn_black = $pgn->black;
362                                 @last_pgn_uci_moves = @uci_moves;
363                                 $pgn_hysteresis_counter = 0;
364                                 handle_position($pos);
365                         }
366                 };
367                 if ($@) {
368                         warn "Error in parsing moves from $url: $@\n";
369                 }
370         }
371         
372         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
373                 fetch_pgn($url);
374         });
375 }
376
377 sub handle_position {
378         my ($pos) = @_;
379         find_clock_start($pos, $pos_calculating);
380                 
381         # If we're already chewing on this and there's nothing else in the queue,
382         # ignore it.
383         if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
384                 $pos_calculating->{'result'} = $pos->{'result'};
385                 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
386                         $pos_calculating->{$key} //= $pos->{$key};
387                 }
388                 return;
389         }
390
391         # If we're already thinking on something, stop and wait for the engine
392         # to approve.
393         if (defined($pos_calculating)) {
394                 # Store the final data we have for this position in the history,
395                 # with the precise clock information we just got from the new
396                 # position. (Historic positions store the clock at the end of
397                 # the position.)
398                 #
399                 # Do not output anything new to the main analysis; that's
400                 # going to be obsolete really soon. (Exception: If we've never
401                 # output anything for this move, ie., it didn't hit the 200ms
402                 # limit, spit it out to the user anyway. It's probably a really
403                 # fast blitz game or something, and it's good to show the moves
404                 # as they come in even without great analysis.)
405                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
406                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
407                 delete $pos_calculating->{'white_clock_target'};
408                 delete $pos_calculating->{'black_clock_target'};
409
410                 if (defined($pos_calculating_started)) {
411                         output_json(0);
412                 } else {
413                         output_json(1);
414                 }
415                 $pos_calculating_started = [Time::HiRes::gettimeofday];
416                 $pos_pv_started = undef;
417
418                 # Ask the engine to stop; we will throw away its data until it
419                 # sends us "bestmove", signaling the end of it.
420                 $engine->{'stopping'} = 1;
421                 uciprint($engine, "stop");
422         }
423
424         # It's wrong to just give the FEN (the move history is useful,
425         # and per the UCI spec, we should really have sent "ucinewgame"),
426         # but it's easier, and it works around a Stockfish repetition issue.
427         if ($engine->{'chess960'} != $pos->{'chess960'}) {
428                 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
429                 $engine->{'chess960'} = $pos->{'chess960'};
430         }
431         uciprint($engine, "position fen " . $pos->fen());
432         uciprint($engine, "go infinite");
433         $pos_calculating = $pos;
434         $pos_calculating_started = [Time::HiRes::gettimeofday];
435         $pos_pv_started = undef;
436
437         if (defined($engine2)) {
438                 if (defined($pos_calculating_second_engine)) {
439                         $engine2->{'stopping'} = 1;
440                         uciprint($engine2, "stop");
441                 }
442                 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
443                         uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
444                         $engine2->{'chess960'} = $pos->{'chess960'};
445                 }
446                 uciprint($engine2, "position fen " . $pos->fen());
447                 uciprint($engine2, "go infinite");
448                 $pos_calculating_second_engine = $pos;
449                 $engine2->{'info'} = {};
450         }
451
452         $engine->{'info'} = {};
453         $last_move = time;
454
455         schedule_tb_lookup();
456
457         # 
458         # Output a command every move to note that we're
459         # still paying attention -- this is a good tradeoff,
460         # since if no move has happened in the last half
461         # hour, the analysis/relay has most likely stopped
462         # and we should stop hogging server resources.
463         #
464         if (defined($t)) {
465                 $t->cmd("date");
466         }
467 }
468
469 sub parse_infos {
470         my ($engine, @x) = @_;
471         my $mpv = '';
472
473         my $info = $engine->{'info'};
474
475         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
476         for my $i (0..$#x - 1) {
477                 if ($x[$i] eq 'multipv') {
478                         $mpv = $x[$i + 1];
479                         next;
480                 }
481         }
482
483         my $prev_depth = $info->{'depth1'} // $info->{'depth'};
484
485         while (scalar @x > 0) {
486                 if ($x[0] eq 'multipv') {
487                         # Dealt with above
488                         shift @x;
489                         shift @x;
490                         next;
491                 }
492                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
493                         my $key = shift @x;
494                         my $value = shift @x;
495                         $info->{$key} = $value;
496                         next;
497                 }
498                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
499                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
500                     $x[0] eq 'tbhits') {
501                         my $key = shift @x;
502                         my $value = shift @x;
503                         $info->{$key . $mpv} = $value;
504                         next;
505                 }
506                 if ($x[0] eq 'score') {
507                         shift @x;
508
509                         delete $info->{'score_cp' . $mpv};
510                         delete $info->{'score_mate' . $mpv};
511                         delete $info->{'splicepos' . $mpv};
512
513                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
514                                 if ($x[0] eq 'cp') {
515                                         shift @x;
516                                         $info->{'score_cp' . $mpv} = shift @x;
517                                 } elsif ($x[0] eq 'mate') {
518                                         shift @x;
519                                         $info->{'score_mate' . $mpv} = shift @x;
520                                 } else {
521                                         shift @x;
522                                 }
523                         }
524                         next;
525                 }
526                 if ($x[0] eq 'pv') {
527                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
528                         last;
529                 }
530                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
531                         last;
532                 }
533
534                 #print "unknown info '$x[0]', trying to recover...\n";
535                 #shift @x;
536                 die "Unknown info '" . join(',', @x) . "'";
537
538         }
539
540         my $now_depth = $info->{'depth1'} // $info->{'depth'};
541         if (defined($prev_depth) && POSIX::floor($now_depth / 10) > POSIX::floor($prev_depth / 10)) {
542                 my $d = POSIX::floor($now_depth / 10) * 10;  # In case we skipped some.
543                 my $cp = $info->{'score_cp1'} // $info->{'score_cp'};
544                 my $mate = $info->{'score_mate1'} // $info->{'score_mate'};
545                 push @{$info->{'lowdepth'}}, [ $d, $cp, $mate ];
546         }
547 }
548
549 sub parse_ids {
550         my ($engine, @x) = @_;
551
552         while (scalar @x > 0) {
553                 if ($x[0] eq 'name') {
554                         my $value = join(' ', @x);
555                         $engine->{'id'}{'author'} = $value;
556                         last;
557                 }
558
559                 # unknown
560                 shift @x;
561         }
562 }
563
564 sub prettyprint_pv_no_cache {
565         my ($board, @pvs) = @_;
566
567         if (scalar @pvs == 0 || !defined($pvs[0])) {
568                 return ();
569         }
570
571         my @ret = ();
572         for my $pv (@pvs) {
573                 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
574                 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
575                 push @ret, $pretty;
576                 $board = $nb;
577         }
578         return @ret;
579 }
580
581 sub prettyprint_pv {
582         my ($pos, @pvs) = @_;
583
584         my $cachekey = join('', @pvs);
585         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
586                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
587         } else {
588                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
589                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
590                 return @res;
591         }
592 }
593
594 my %tbprobe_cache = ();
595
596 sub complete_using_tbprobe {
597         my ($pos, $info, $mpv) = @_;
598
599         # We need Fathom installed to do standalone TB probes.
600         return if (!defined($remoteglotconf::fathom_cmdline));
601
602         # If we already have a mate, don't bother; in some cases, it would even be
603         # better than a tablebase score.
604         return if defined($info->{'score_mate' . $mpv});
605
606         # If we have a draw or near-draw score, there's also not much interesting
607         # we could add from a tablebase. We only really want mates.
608         return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
609
610         # Run through the PV until we are at a 6-man position.
611         # TODO: We could in theory only have 5-man data.
612         my @pv = @{$info->{'pv' . $mpv}};
613         my $key = $pos->fen() . " " . join('', @pv);
614         my @moves = ();
615         my $splicepos;
616         if (exists($tbprobe_cache{$key})) {
617                 my $c = $tbprobe_cache{$key};
618                 @moves = @{$c->{'moves'}};
619                 $splicepos = $c->{'splicepos'};
620         } else {
621                 if ($mpv ne '') {
622                         # Force doing at least one move of the PV.
623                         my $move = shift @pv;
624                         push @moves, $move;
625                         $pos = $pos->make_move(parse_uci_move($move));
626                 }
627
628                 while ($pos->num_pieces() > 7 && $#pv > -1) {
629                         my $move = shift @pv;
630                         push @moves, $move;
631                         $pos = $pos->make_move(parse_uci_move($move));
632                 }
633
634                 return if ($pos->num_pieces() > 7);
635
636                 my $fen = $pos->fen();
637                 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
638                 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
639                 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
640                 $pgn->quick_parse_game;
641
642                 # Splice the PV from the tablebase onto what we have so far.
643                 $splicepos = scalar @moves;
644                 for my $move (@{$pgn->moves}) {
645                         last if $move eq '#';
646                         last if $move eq '1-0';
647                         last if $move eq '0-1';
648                         last if $move eq '1/2-1/2';
649                         my $uci_move;
650                         ($pos, $uci_move) = $pos->make_pretty_move($move);
651                         push @moves, $uci_move;
652                 }
653
654                 $tbprobe_cache{$key} = {
655                         moves => \@moves,
656                         splicepos => $splicepos
657                 };
658         }
659
660         $info->{'pv' . $mpv} = \@moves;
661
662         my $matelen = int((1 + scalar @moves) / 2);
663         if ((scalar @moves) % 2 == 0) {
664                 $info->{'score_mate' . $mpv} = -$matelen;
665         } else {
666                 $info->{'score_mate' . $mpv} = $matelen;
667         }
668         $info->{'splicepos' . $mpv} = $splicepos;
669 }
670
671 sub output {
672         #return;
673
674         return if (!defined($pos_calculating));
675
676         my $info = $engine->{'info'};
677
678         # Don't update too often.
679         my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
680         if (defined($pos_calculating_started)) {
681                 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
682                 $wait = $new_pos_wait if ($new_pos_wait < $wait);
683         }
684         if (!$last_output_had_pv && has_pv($info)) {
685                 if (!defined($pos_pv_started)) {
686                         $pos_pv_started = [Time::HiRes::gettimeofday];
687                 }
688                 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
689                 # so give us just 200ms more to increase the quality and then force a display.
690                 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
691                 $wait = $new_pos_wait if ($new_pos_wait < $wait);
692         }
693         if ($wait > 0.0) {
694                 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
695                 return;
696         }
697         $pos_pv_started = undef;
698         
699         # We're outputting something for this position now, so the special handling
700         # for new positions is off.
701         undef $pos_calculating_started;
702         
703         #
704         # If we have tablebase data from a previous lookup, replace the
705         # engine data with the data from the tablebase.
706         #
707         my $fen = $pos_calculating->fen();
708         if (exists($tb_cache{$fen})) {
709                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
710                         delete $info->{$key . '1'};
711                         delete $info->{$key};
712                 }
713                 $info->{'nodes'} = 0;
714                 $info->{'nps'} = 0;
715                 $info->{'depth'} = 0;
716                 $info->{'seldepth'} = 0;
717                 $info->{'tbhits'} = 0;
718
719                 my $t = $tb_cache{$fen};
720                 my $pv = $t->{'pv'};
721                 my $matelen = int((1 + $t->{'score'}) / 2);
722                 if ($t->{'result'} eq '1/2-1/2') {
723                         $info->{'score_cp'} = 0;
724                 } elsif ($t->{'result'} eq '1-0') {
725                         if ($pos_calculating->{'toplay'} eq 'B') {
726                                 $info->{'score_mate'} = -$matelen;
727                         } else {
728                                 $info->{'score_mate'} = $matelen;
729                         }
730                 } else {
731                         if ($pos_calculating->{'toplay'} eq 'B') {
732                                 $info->{'score_mate'} = $matelen;
733                         } else {
734                                 $info->{'score_mate'} = -$matelen;
735                         }
736                 }
737                 $info->{'pv'} = $pv;
738                 $info->{'tablebase'} = 1;
739         } else {
740                 $info->{'tablebase'} = 0;
741         }
742         
743         #
744         # Some programs _always_ report MultiPV, even with only one PV.
745         # In this case, we simply use that data as if MultiPV was never
746         # specified.
747         #
748         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
749                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
750                         if (exists($info->{$key . '1'})) {
751                                 $info->{$key} = $info->{$key . '1'};
752                         } else {
753                                 delete $info->{$key};
754                         }
755                 }
756         }
757         
758         #
759         # Check the PVs first. if they're invalid, just wait, as our data
760         # is most likely out of sync. This isn't a very good solution, as
761         # it can frequently miss stuff, but it's good enough for most users.
762         #
763         eval {
764                 my $dummy;
765                 if (exists($info->{'pv'})) {
766                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
767                 }
768         
769                 my $mpv = 1;
770                 while (exists($info->{'pv' . $mpv})) {
771                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
772                         ++$mpv;
773                 }
774         };
775         if ($@) {
776                 $engine->{'info'} = {};
777                 return;
778         }
779
780         # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
781         if (exists($info->{'pv'})) {
782                 complete_using_tbprobe($pos_calculating, $info, '');
783         }
784
785         my $mpv = 1;
786         while (exists($info->{'pv' . $mpv})) {
787                 complete_using_tbprobe($pos_calculating, $info, $mpv);
788                 ++$mpv;
789         }
790
791         output_screen();
792         output_json(0);
793         $latest_update = [Time::HiRes::gettimeofday];
794         $last_output_had_pv = has_pv($info);
795 }
796
797 sub has_pv {
798         my $info = shift;
799         return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
800         return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
801         return 0;
802 }
803
804 sub output_screen {
805         my $info = $engine->{'info'};
806         my $id = $engine->{'id'};
807
808         my $text = 'Analysis';
809         if ($pos_calculating->{'last_move'} ne 'none') {
810                 if ($pos_calculating->{'toplay'} eq 'W') {
811                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
812                 } else {
813                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
814                 }
815                 if (exists($id->{'name'})) {
816                         $text .= ',';
817                 }
818         }
819
820         if (exists($id->{'name'})) {
821                 $text .= " by $id->{'name'}:\n\n";
822         } else {
823                 $text .= ":\n\n";
824         }
825
826         return unless (exists($pos_calculating->{'board'}));
827                 
828         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
829                 # multi-PV
830                 my $mpv = 1;
831                 while (exists($info->{'pv' . $mpv})) {
832                         $text .= sprintf "  PV%2u", $mpv;
833                         my $score = short_score($info, $pos_calculating, $mpv);
834                         $text .= "  ($score)" if (defined($score));
835
836                         my $tbhits = '';
837                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
838                                 if ($info->{'tbhits' . $mpv} == 1) {
839                                         $tbhits = ", 1 tbhit";
840                                 } else {
841                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
842                                 }
843                         }
844
845                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
846                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
847                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
848                         }
849
850                         $text .= ":\n";
851                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
852                         $text .= "\n";
853                         ++$mpv;
854                 }
855         } else {
856                 # single-PV
857                 my $score = long_score($info, $pos_calculating, '');
858                 $text .= "  $score\n" if defined($score);
859                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
860                 $text .=  "\n";
861
862                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
863                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
864                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
865                 }
866                 if (exists($info->{'seldepth'})) {
867                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
868                 }
869                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
870                         if ($info->{'tbhits'} == 1) {
871                                 $text .= ", one Syzygy hit";
872                         } else {
873                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
874                         }
875                 }
876                 $text .= "\n\n";
877         }
878
879         my @refutation_lines = ();
880         if (defined($engine2)) {
881                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
882                         my $info = $engine2->{'info'};
883                         last if (!exists($info->{'pv' . $mpv}));
884                         eval {
885                                 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
886                                 my $pv = $info->{'pv' . $mpv};
887                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
888                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
889                                 if (scalar @pretty_pv > 5) {
890                                         @pretty_pv = @pretty_pv[0..4];
891                                         push @pretty_pv, "...";
892                                 }
893                                 my $key = $pretty_move;
894                                 my $line = sprintf("  %-6s %6s %3s  %s",
895                                         $pretty_move,
896                                         short_score($info, $pos_calculating_second_engine, $mpv),
897                                         "d" . $info->{'depth' . $mpv},
898                                         join(', ', @pretty_pv));
899                                 push @refutation_lines, [ $key, $line ];
900                         };
901                 }
902         }
903
904         if ($#refutation_lines >= 0) {
905                 $text .= "Shallow search of all legal moves:\n\n";
906                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
907                         $text .= $line->[1] . "\n";
908                 }
909                 $text .= "\n\n";        
910         }       
911
912         if ($last_text ne $text) {
913                 print "\e[H\e[2J"; # clear the screen
914                 print $text;
915                 $last_text = $text;
916         }
917 }
918
919 sub output_json {
920         my $historic_json_only = shift;
921         my $info = $engine->{'info'};
922
923         my $json = {};
924         $json->{'position'} = $pos_calculating->to_json_hash();
925         $json->{'engine'} = $engine->{'id'};
926         if (defined($remoteglotconf::engine_url)) {
927                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
928         }
929         if (defined($remoteglotconf::engine_details)) {
930                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
931         }
932         my @grpc_backends = ();
933         if (defined($remoteglotconf::engine_grpc_backend)) {
934                 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
935         }
936         if (defined($remoteglotconf::engine2_grpc_backend)) {
937                 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
938         }
939         $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
940         if (defined($remoteglotconf::move_source)) {
941                 $json->{'move_source'} = $remoteglotconf::move_source;
942         }
943         if (defined($remoteglotconf::move_source_url)) {
944                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
945         }
946         $json->{'score'} = score_digest($info, $pos_calculating, '');
947         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
948
949         $json->{'nodes'} = $info->{'nodes'};
950         $json->{'nps'} = $info->{'nps'};
951         $json->{'depth'} = $info->{'depth'};
952         $json->{'tbhits'} = $info->{'tbhits'};
953         $json->{'seldepth'} = $info->{'seldepth'};
954         $json->{'tablebase'} = $info->{'tablebase'};
955         $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
956
957         $json->{'lowdepth'} = {};
958         if (exists($info->{'lowdepth'})) {
959                 for my $ld (@{$info->{'lowdepth'}}) {
960                         $json->{'lowdepth'}{$ld->[0]} = score_digest_inner($ld->[1], $ld->[2], undef, 0, $pos_calculating);
961                 }
962         }
963
964         my %refutation_lines = ();
965         my @refutation_lines = ();
966         if (defined($engine2)) {
967                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
968                         my $info = $engine2->{'info'};
969                         my $pretty_move = "";
970                         my @pretty_pv = ();
971                         last if (!exists($info->{'pv' . $mpv}));
972
973                         eval {
974                                 complete_using_tbprobe($pos_calculating, $info, $mpv);
975                                 my $pv = $info->{'pv' . $mpv};
976                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
977                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
978                                 $refutation_lines{$pretty_move} = {
979                                         depth => $info->{'depth' . $mpv},
980                                         score => score_digest($info, $pos_calculating, $mpv),
981                                         move => $pretty_move,
982                                         pv => \@pretty_pv,
983                                 };
984                                 if (exists($info->{'splicepos' . $mpv})) {
985                                         $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
986                                 }
987                         };
988                 }
989         }
990         $json->{'refutation_lines'} = \%refutation_lines;
991
992         # Piece together historic score information, to the degree we have it.
993         if (!$historic_json_only && exists($pos_calculating->{'history'})) {
994                 my %score_history = ();
995
996                 local $dbh->{AutoCommit} = 0;
997                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
998                 my $pos;
999                 if (exists($pos_calculating->{'start_fen'})) {
1000                         $pos = Position->from_fen($pos_calculating->{'start_fen'});
1001                 } else {
1002                         $pos = Position->start_pos('white', 'black');
1003                 }
1004                 $pos->{'chess960'} = $pos_calculating->{'chess960'};
1005                 my $halfmove_num = 0;
1006                 for my $move (@{$pos_calculating->{'history'}}) {
1007                         my $id = id_for_pos($pos, $halfmove_num);
1008                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
1009                         if (defined($ref)) {
1010                                 $score_history{$halfmove_num} = [
1011                                         $ref->{'score_type'},
1012                                         $ref->{'score_value'}
1013                                 ];
1014                         }
1015                         ++$halfmove_num;
1016                         ($pos) = $pos->make_pretty_move($move);
1017                 }
1018                 $q->finish;
1019                 $dbh->commit;
1020
1021                 # If at any point we are missing 10 consecutive moves,
1022                 # truncate the history there. This is so we don't get into
1023                 # a situation where we e.g. start analyzing at move 45,
1024                 # but we have analysis for 1. e4 from some completely different game
1025                 # and thus show a huge hole.
1026                 my $consecutive_missing = 0;
1027                 my $truncate_until = 0;
1028                 for (my $i = $halfmove_num; $i --> 0; ) {
1029                         if ($consecutive_missing >= 10) {
1030                                 delete $score_history{$i};
1031                                 next;
1032                         }
1033                         if (exists($score_history{$i})) {
1034                                 $consecutive_missing = 0;
1035                         } else {
1036                                 ++$consecutive_missing;
1037                         }
1038                 }
1039
1040                 $json->{'score_history'} = \%score_history;
1041         }
1042
1043         # Give out a list of other games going on. (Empty is fine.)
1044         # TODO: Don't bother reading our own file, the data will be stale anyway.
1045         if (!$historic_json_only) {
1046                 my @games = ();
1047
1048                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
1049                 $q->execute;
1050                 while (my $ref = $q->fetchrow_hashref) {
1051                         eval {
1052                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
1053                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
1054
1055                                 die "Missing position" if (!exists($other_game_json->{'position'}));
1056                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
1057                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1058
1059                                 my $game = {
1060                                         id => $ref->{'id'},
1061                                         name => "$white–$black",
1062                                         url => $ref->{'url'},
1063                                         hashurl => $ref->{'hash_url'},
1064                                 };
1065                                 if (defined($other_game_json->{'position'}{'result'})) {
1066                                         $game->{'result'} = $other_game_json->{'position'}{'result'};
1067                                 } else {
1068                                         $game->{'score'} = $other_game_json->{'score'};
1069                                 }
1070                                 push @games, $game;
1071                         };
1072                         if ($@) {
1073                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1074                         }
1075                 }
1076
1077                 if (scalar @games > 0) {
1078                         $json->{'games'} = \@games;
1079                 }
1080         }
1081
1082         my $json_enc = JSON::XS->new;
1083         $json_enc->canonical(1);
1084         my $encoded = $json_enc->encode($json);
1085         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1086                 (defined($last_written_json) && $last_written_json eq $encoded)) {
1087                 atomic_set_contents($remoteglotconf::json_output, $encoded);
1088                 $last_written_json = $encoded;
1089         }
1090
1091         if (exists($pos_calculating->{'history'}) &&
1092             defined($remoteglotconf::json_history_dir)) {
1093                 my $id = id_for_pos($pos_calculating);
1094                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1095
1096                 # Overwrite old analysis (assuming it exists at all) if we're
1097                 # using a different engine, or if we've calculated deeper.
1098                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1099                 # data; it's not that important.
1100                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1101                 my $new_depth = $json->{'depth'} // 0;
1102                 my $new_nodes = $json->{'nodes'} // 0;
1103                 if (!defined($old_engine) ||
1104                     $old_engine ne $json->{'engine'}{'name'} ||
1105                     $new_depth > $old_depth ||
1106                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1107                         atomic_set_contents($filename, $encoded);
1108                         if (defined($json->{'score'})) {
1109                                 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1110                                          '    ON CONFLICT (id) DO UPDATE SET ' .
1111                                          '        score_type=EXCLUDED.score_type, ' .
1112                                          '        score_value=EXCLUDED.score_value, ' .
1113                                          '        engine=EXCLUDED.engine, ' .
1114                                          '        depth=EXCLUDED.depth, ' .
1115                                          '        nodes=EXCLUDED.nodes',
1116                                         undef,
1117                                         $id, $json->{'score'}[0], $json->{'score'}[1],
1118                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1119                         }
1120                 }
1121         }
1122 }
1123
1124 sub atomic_set_contents {
1125         my ($filename, $contents) = @_;
1126
1127         open my $fh, ">", $filename . ".tmp"
1128                 or return;
1129         print $fh $contents;
1130         close $fh;
1131         rename($filename . ".tmp", $filename);
1132 }
1133
1134 sub id_for_pos {
1135         my ($pos, $halfmove_num) = @_;
1136
1137         $halfmove_num //= scalar @{$pos->{'history'}};
1138         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1139         return "move$halfmove_num-$fen";
1140 }
1141
1142 sub get_json_analysis_stats {
1143         my $id = shift;
1144         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1145         if (defined($ref)) {
1146                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1147         } else {
1148                 return ('', 0, 0);
1149         }
1150 }
1151
1152 sub uciprint {
1153         my ($engine, $msg) = @_;
1154         $engine->print($msg);
1155         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1156 }
1157
1158 sub short_score {
1159         my ($info, $pos, $mpv) = @_;
1160
1161         my $invert = ($pos->{'toplay'} eq 'B');
1162         if (defined($info->{'score_mate' . $mpv})) {
1163                 if ($invert) {
1164                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1165                 } else {
1166                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1167                 }
1168         } else {
1169                 if (exists($info->{'score_cp' . $mpv})) {
1170                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1171                         if ($score == 0) {
1172                                 if ($info->{'tablebase'}) {
1173                                         return "TB draw";
1174                                 } else {
1175                                         return " 0.00";
1176                                 }
1177                         }
1178                         if ($invert) {
1179                                 $score = -$score;
1180                         }
1181                         return sprintf "%+5.2f", $score;
1182                 }
1183         }
1184
1185         return undef;
1186 }
1187
1188 # Sufficient for computing long_score, short_score, plot_score and
1189 # (with side-to-play information) score_sort_key.
1190 sub score_digest {
1191         my ($info, $pos, $mpv) = @_;
1192         return score_digest_inner(
1193                 $info->{'score_cp' . $mpv},
1194                 $info->{'score_mate' . $mpv},
1195                 $info->{'splicepos' . $mpv},
1196                 $info->{'tablebase'},
1197                 $pos);
1198 }
1199
1200 sub score_digest_inner {
1201         my ($score, $mate, $sp, $tablebase, $pos) = @_;
1202         if (defined($mate)) {
1203                 if ($pos->{'toplay'} eq 'B') {
1204                         $mate = -$mate;
1205                 }
1206                 if (defined($sp)) {
1207                         if ($mate > 0) {
1208                                 return ['T', $sp];
1209                         } else {
1210                                 return ['t', $sp];
1211                         }
1212                 } else {
1213                         if ($mate > 0) {
1214                                 return ['M', $mate];
1215                         } elsif ($mate < 0) {
1216                                 return ['m', -$mate];
1217                         } elsif ($pos->{'toplay'} eq 'B') {
1218                                 return ['M', 0];
1219                         } else {
1220                                 return ['m', 0];
1221                         }
1222                 }
1223         } else {
1224                 if (defined($score)) {
1225                         if ($pos->{'toplay'} eq 'B') {
1226                                 $score = -$score;
1227                         }
1228                         if ($score == 0 && $tablebase) {
1229                                 return ['d', undef];
1230                         } else {
1231                                 return ['cp', int($score)];
1232                         }
1233                 }
1234         }
1235
1236         return undef;
1237 }
1238
1239 sub long_score {
1240         my ($info, $pos, $mpv) = @_;
1241
1242         if (defined($info->{'score_mate' . $mpv})) {
1243                 my $mate = $info->{'score_mate' . $mpv};
1244                 if ($pos->{'toplay'} eq 'B') {
1245                         $mate = -$mate;
1246                 }
1247                 if (exists($info->{'splicepos' . $mpv})) {
1248                         my $sp = $info->{'splicepos' . $mpv};
1249                         if ($mate > 0) {
1250                                 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1251                         } else {
1252                                 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1253                         }
1254                 } else {
1255                         if ($mate > 0) {
1256                                 return sprintf "White mates in %u", $mate;
1257                         } else {
1258                                 return sprintf "Black mates in %u", -$mate;
1259                         }
1260                 }
1261         } else {
1262                 if (exists($info->{'score_cp' . $mpv})) {
1263                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1264                         if ($score == 0) {
1265                                 if ($info->{'tablebase'}) {
1266                                         return "Theoretical draw";
1267                                 } else {
1268                                         return "Score:  0.00";
1269                                 }
1270                         }
1271                         if ($pos->{'toplay'} eq 'B') {
1272                                 $score = -$score;
1273                         }
1274                         return sprintf "Score: %+5.2f", $score;
1275                 }
1276         }
1277
1278         return undef;
1279 }
1280
1281 # For graphs; a single number in centipawns, capped at +/- 500.
1282 sub plot_score {
1283         my ($info, $pos, $mpv) = @_;
1284
1285         my $invert = ($pos->{'toplay'} eq 'B');
1286         if (defined($info->{'score_mate' . $mpv})) {
1287                 my $mate = $info->{'score_mate' . $mpv};
1288                 if ($invert) {
1289                         $mate = -$mate;
1290                 }
1291                 if ($mate > 0) {
1292                         return 500;
1293                 } else {
1294                         return -500;
1295                 }
1296         } else {
1297                 if (exists($info->{'score_cp' . $mpv})) {
1298                         my $score = $info->{'score_cp' . $mpv};
1299                         if ($invert) {
1300                                 $score = -$score;
1301                         }
1302                         $score = 500 if ($score > 500);
1303                         $score = -500 if ($score < -500);
1304                         return int($score);
1305                 }
1306         }
1307
1308         return undef;
1309 }
1310
1311 sub extract_clock {
1312         my ($pgn, $pos) = @_;
1313
1314         # Look for extended PGN clock tags.
1315         my $tags = $pgn->tags;
1316         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1317                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1318                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1319                 return;
1320         }
1321
1322         # Look for TCEC-style time comments.
1323         my $moves = $pgn->moves;
1324         my $comments = $pgn->comments;
1325         my $last_black_move = int((scalar @$moves) / 2);
1326         my $last_white_move = int((1 + scalar @$moves) / 2);
1327
1328         my $black_key = $last_black_move . "b";
1329         my $white_key = $last_white_move . "w";
1330
1331         if (exists($comments->{$white_key}) &&
1332             exists($comments->{$black_key}) &&
1333             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1334             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1335                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1336                 $pos->{'white_clock'} = hms_to_sec($1);
1337                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1338                 $pos->{'black_clock'} = hms_to_sec($1);
1339                 return;
1340         }
1341
1342         delete $pos->{'white_clock'};
1343         delete $pos->{'black_clock'};
1344 }
1345
1346 sub hms_to_sec {
1347         my $hms = shift;
1348         return undef if (!defined($hms));
1349         $hms =~ /(\d+):(\d+):(\d+)/;
1350         return $1 * 3600 + $2 * 60 + $3;
1351 }
1352
1353 sub find_clock_start {
1354         my ($pos, $prev_pos) = @_;
1355
1356         # If the game is over, the clock is stopped.
1357         if (exists($pos->{'result'}) &&
1358             ($pos->{'result'} eq '1-0' ||
1359              $pos->{'result'} eq '1/2-1/2' ||
1360              $pos->{'result'} eq '0-1')) {
1361                 return;
1362         }
1363
1364         # When we don't have any moves, we assume the clock hasn't started yet.
1365         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1366                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1367                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1368                 }
1369                 return;
1370         }
1371
1372         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1373         # The history is needed for id_for_pos.
1374         if (!exists($pos->{'history'})) {
1375                 return;
1376         }
1377
1378         my $id = id_for_pos($pos);
1379         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);
1380         if (defined($clock_info)) {
1381                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1382                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1383                 if ($pos->{'toplay'} eq 'W') {
1384                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1385                 } else {
1386                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1387                 }
1388                 return;
1389         }
1390
1391         # OK, we haven't seen this position before, so we assume the move
1392         # happened right now.
1393
1394         # See if we should do our own clock management (ie., clock information
1395         # is spurious or non-existent).
1396         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1397                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1398                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1399                 if (defined($prev_pos->{'white_clock_target'})) {
1400                         $wc = $prev_pos->{'white_clock_target'} - time;
1401                 }
1402                 if (defined($prev_pos->{'black_clock_target'})) {
1403                         $bc = $prev_pos->{'black_clock_target'} - time;
1404                 }
1405                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1406                 $pos->{'white_clock'} = $wc;
1407                 $pos->{'black_clock'} = $bc;
1408         }
1409
1410         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1411         if (!exists($pos->{$key})) {
1412                 # No clock information.
1413                 return;
1414         }
1415         my $time_left = $pos->{$key};
1416         my ($white_clock_target, $black_clock_target);
1417         if ($pos->{'toplay'} eq 'W') {
1418                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1419         } else {
1420                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1421         }
1422         local $dbh->{AutoCommit} = 0;
1423         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1424         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1425                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1426         $dbh->commit;
1427 }
1428
1429 sub schedule_tb_lookup {
1430         return if (!defined($remoteglotconf::tb_serial_key));
1431         my $pos = $pos_calculating;
1432         return if (exists($tb_cache{$pos->fen()}));
1433
1434         # If there's more than seven pieces, there's not going to be an answer,
1435         # so don't bother.
1436         return if ($pos->num_pieces() > 7);
1437
1438         # Max one at a time. If it's still relevant when it returns,
1439         # schedule_tb_lookup() will be called again.
1440         return if ($tb_lookup_running);
1441
1442         $tb_lookup_running = 1;
1443         my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1444                 $remoteglotconf::tb_serial_key .
1445                 '&auth.password=aquarium&type=0&fen=' . 
1446                 URI::Escape::uri_escape($pos->fen());
1447         print TBLOG "Downloading $url...\n";
1448         AnyEvent::HTTP::http_get($url, sub {
1449                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1450         });
1451 }
1452
1453 sub handle_tb_lookup_return {
1454         my ($body, $header, $pos, $fen) = @_;
1455         print TBLOG "Response for [$fen]:\n";
1456         print TBLOG $header . "\n\n";
1457         print TBLOG $body . "\n\n";
1458         eval {
1459                 my $response = JSON::XS::decode_json($body);
1460                 if ($response->{'ErrorCode'} != 0) {
1461                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1462                 }
1463                 my $state = $response->{'Response'}{'StateString'};
1464                 if ($state eq 'COMPLETE') {
1465                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1466                         if (!defined($pgn) || !$pgn->read_game()) {
1467                                 warn "Error in parsing PGN\n";
1468                         } else {
1469                                 $pgn->quick_parse_game;
1470                                 my $pvpos = $pos;
1471                                 my $moves = $pgn->moves;
1472                                 my @uci_moves = ();
1473                                 for my $move (@$moves) {
1474                                         my $uci_move;
1475                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1476                                         push @uci_moves, $uci_move;
1477                                 }
1478                                 $tb_cache{$fen} = {
1479                                         result => $pgn->result,
1480                                         pv => \@uci_moves,
1481                                         score => $response->{'Response'}{'Score'},
1482                                 };
1483                                 output();
1484                         }
1485                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1486                         # Try again in a second. Note that if we have changed
1487                         # position in the meantime, we might query a completely
1488                         # different position! But that's fine.
1489                 } else {
1490                         die "Unknown response state " . $state;
1491                 }
1492
1493                 # Wait a second before we schedule another one.
1494                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1495                         $tb_lookup_running = 0;
1496                         schedule_tb_lookup();
1497                 });
1498         };
1499         if ($@) {
1500                 warn "Error in tablebase lookup: $@";
1501
1502                 # Don't try this one again, but don't block new lookups either.
1503                 $tb_lookup_running = 0;
1504         }
1505 }
1506
1507 sub open_engine {
1508         my ($cmdline, $tag, $cb) = @_;
1509         return undef if (!defined($cmdline));
1510         return Engine->open($cmdline, $tag, $cb);
1511 }
1512
1513 sub col_letter_to_num {
1514         return ord(shift) - ord('a');
1515 }
1516
1517 sub row_letter_to_num {
1518         return 7 - (ord(shift) - ord('1'));
1519 }
1520
1521 sub parse_uci_move {
1522         my $move = shift;
1523         my $from_col = col_letter_to_num(substr($move, 0, 1));
1524         my $from_row = row_letter_to_num(substr($move, 1, 1));
1525         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1526         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1527         my $promo    = substr($move, 4, 1);
1528         return ($from_row, $from_col, $to_row, $to_col, $promo);
1529 }
1530
1531 sub setoptions {
1532         my ($engine, $config) = @_;
1533         uciprint($engine, "setoption name UCI_AnalyseMode value true");
1534         uciprint($engine, "setoption name Analysis Contempt value Off");
1535         if (exists($config->{'Threads'})) {  # Threads first, because clearing hash can be multithreaded then.
1536                 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1537         }
1538         while (my ($key, $value) = each %$config) {
1539                 next if $key eq 'Threads';
1540                 uciprint($engine, "setoption name $key value $value");
1541         }
1542 }