]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Move back to development version (was inadvertedly changed).
[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         while (scalar @x > 0) {
484                 if ($x[0] eq 'multipv') {
485                         # Dealt with above
486                         shift @x;
487                         shift @x;
488                         next;
489                 }
490                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
491                         my $key = shift @x;
492                         my $value = shift @x;
493                         $info->{$key} = $value;
494                         next;
495                 }
496                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
497                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
498                     $x[0] eq 'tbhits') {
499                         my $key = shift @x;
500                         my $value = shift @x;
501                         $info->{$key . $mpv} = $value;
502                         next;
503                 }
504                 if ($x[0] eq 'score') {
505                         shift @x;
506
507                         delete $info->{'score_cp' . $mpv};
508                         delete $info->{'score_mate' . $mpv};
509                         delete $info->{'splicepos' . $mpv};
510
511                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
512                                 if ($x[0] eq 'cp') {
513                                         shift @x;
514                                         $info->{'score_cp' . $mpv} = shift @x;
515                                 } elsif ($x[0] eq 'mate') {
516                                         shift @x;
517                                         $info->{'score_mate' . $mpv} = shift @x;
518                                 } else {
519                                         shift @x;
520                                 }
521                         }
522                         next;
523                 }
524                 if ($x[0] eq 'pv') {
525                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
526                         last;
527                 }
528                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
529                         last;
530                 }
531
532                 #print "unknown info '$x[0]', trying to recover...\n";
533                 #shift @x;
534                 die "Unknown info '" . join(',', @x) . "'";
535
536         }
537 }
538
539 sub parse_ids {
540         my ($engine, @x) = @_;
541
542         while (scalar @x > 0) {
543                 if ($x[0] eq 'name') {
544                         my $value = join(' ', @x);
545                         $engine->{'id'}{'author'} = $value;
546                         last;
547                 }
548
549                 # unknown
550                 shift @x;
551         }
552 }
553
554 sub prettyprint_pv_no_cache {
555         my ($board, @pvs) = @_;
556
557         if (scalar @pvs == 0 || !defined($pvs[0])) {
558                 return ();
559         }
560
561         my @ret = ();
562         for my $pv (@pvs) {
563                 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
564                 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
565                 push @ret, $pretty;
566                 $board = $nb;
567         }
568         return @ret;
569 }
570
571 sub prettyprint_pv {
572         my ($pos, @pvs) = @_;
573
574         my $cachekey = join('', @pvs);
575         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
576                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
577         } else {
578                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
579                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
580                 return @res;
581         }
582 }
583
584 my %tbprobe_cache = ();
585
586 sub complete_using_tbprobe {
587         my ($pos, $info, $mpv) = @_;
588
589         # We need Fathom installed to do standalone TB probes.
590         return if (!defined($remoteglotconf::fathom_cmdline));
591
592         # If we already have a mate, don't bother; in some cases, it would even be
593         # better than a tablebase score.
594         return if defined($info->{'score_mate' . $mpv});
595
596         # If we have a draw or near-draw score, there's also not much interesting
597         # we could add from a tablebase. We only really want mates.
598         return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
599
600         # Run through the PV until we are at a 6-man position.
601         # TODO: We could in theory only have 5-man data.
602         my @pv = @{$info->{'pv' . $mpv}};
603         my $key = $pos->fen() . " " . join('', @pv);
604         my @moves = ();
605         my $splicepos;
606         if (exists($tbprobe_cache{$key})) {
607                 my $c = $tbprobe_cache{$key};
608                 @moves = @{$c->{'moves'}};
609                 $splicepos = $c->{'splicepos'};
610         } else {
611                 if ($mpv ne '') {
612                         # Force doing at least one move of the PV.
613                         my $move = shift @pv;
614                         push @moves, $move;
615                         $pos = $pos->make_move(parse_uci_move($move));
616                 }
617
618                 while ($pos->num_pieces() > 7 && $#pv > -1) {
619                         my $move = shift @pv;
620                         push @moves, $move;
621                         $pos = $pos->make_move(parse_uci_move($move));
622                 }
623
624                 return if ($pos->num_pieces() > 7);
625
626                 my $fen = $pos->fen();
627                 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
628                 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
629                 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
630                 $pgn->quick_parse_game;
631
632                 # Splice the PV from the tablebase onto what we have so far.
633                 $splicepos = scalar @moves;
634                 for my $move (@{$pgn->moves}) {
635                         last if $move eq '#';
636                         last if $move eq '1-0';
637                         last if $move eq '0-1';
638                         last if $move eq '1/2-1/2';
639                         my $uci_move;
640                         ($pos, $uci_move) = $pos->make_pretty_move($move);
641                         push @moves, $uci_move;
642                 }
643
644                 $tbprobe_cache{$key} = {
645                         moves => \@moves,
646                         splicepos => $splicepos
647                 };
648         }
649
650         $info->{'pv' . $mpv} = \@moves;
651
652         my $matelen = int((1 + scalar @moves) / 2);
653         if ((scalar @moves) % 2 == 0) {
654                 $info->{'score_mate' . $mpv} = -$matelen;
655         } else {
656                 $info->{'score_mate' . $mpv} = $matelen;
657         }
658         $info->{'splicepos' . $mpv} = $splicepos;
659 }
660
661 sub output {
662         #return;
663
664         return if (!defined($pos_calculating));
665
666         my $info = $engine->{'info'};
667
668         # Don't update too often.
669         my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
670         if (defined($pos_calculating_started)) {
671                 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
672                 $wait = $new_pos_wait if ($new_pos_wait < $wait);
673         }
674         if (!$last_output_had_pv && has_pv($info)) {
675                 if (!defined($pos_pv_started)) {
676                         $pos_pv_started = [Time::HiRes::gettimeofday];
677                 }
678                 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
679                 # so give us just 200ms more to increase the quality and then force a display.
680                 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
681                 $wait = $new_pos_wait if ($new_pos_wait < $wait);
682         }
683         if ($wait > 0.0) {
684                 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
685                 return;
686         }
687         $pos_pv_started = undef;
688         
689         # We're outputting something for this position now, so the special handling
690         # for new positions is off.
691         undef $pos_calculating_started;
692         
693         #
694         # If we have tablebase data from a previous lookup, replace the
695         # engine data with the data from the tablebase.
696         #
697         my $fen = $pos_calculating->fen();
698         if (exists($tb_cache{$fen})) {
699                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
700                         delete $info->{$key . '1'};
701                         delete $info->{$key};
702                 }
703                 $info->{'nodes'} = 0;
704                 $info->{'nps'} = 0;
705                 $info->{'depth'} = 0;
706                 $info->{'seldepth'} = 0;
707                 $info->{'tbhits'} = 0;
708
709                 my $t = $tb_cache{$fen};
710                 my $pv = $t->{'pv'};
711                 my $matelen = int((1 + $t->{'score'}) / 2);
712                 if ($t->{'result'} eq '1/2-1/2') {
713                         $info->{'score_cp'} = 0;
714                 } elsif ($t->{'result'} eq '1-0') {
715                         if ($pos_calculating->{'toplay'} eq 'B') {
716                                 $info->{'score_mate'} = -$matelen;
717                         } else {
718                                 $info->{'score_mate'} = $matelen;
719                         }
720                 } else {
721                         if ($pos_calculating->{'toplay'} eq 'B') {
722                                 $info->{'score_mate'} = $matelen;
723                         } else {
724                                 $info->{'score_mate'} = -$matelen;
725                         }
726                 }
727                 $info->{'pv'} = $pv;
728                 $info->{'tablebase'} = 1;
729         } else {
730                 $info->{'tablebase'} = 0;
731         }
732         
733         #
734         # Some programs _always_ report MultiPV, even with only one PV.
735         # In this case, we simply use that data as if MultiPV was never
736         # specified.
737         #
738         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
739                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
740                         if (exists($info->{$key . '1'})) {
741                                 $info->{$key} = $info->{$key . '1'};
742                         } else {
743                                 delete $info->{$key};
744                         }
745                 }
746         }
747         
748         #
749         # Check the PVs first. if they're invalid, just wait, as our data
750         # is most likely out of sync. This isn't a very good solution, as
751         # it can frequently miss stuff, but it's good enough for most users.
752         #
753         eval {
754                 my $dummy;
755                 if (exists($info->{'pv'})) {
756                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
757                 }
758         
759                 my $mpv = 1;
760                 while (exists($info->{'pv' . $mpv})) {
761                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
762                         ++$mpv;
763                 }
764         };
765         if ($@) {
766                 $engine->{'info'} = {};
767                 return;
768         }
769
770         # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
771         if (exists($info->{'pv'})) {
772                 complete_using_tbprobe($pos_calculating, $info, '');
773         }
774
775         my $mpv = 1;
776         while (exists($info->{'pv' . $mpv})) {
777                 complete_using_tbprobe($pos_calculating, $info, $mpv);
778                 ++$mpv;
779         }
780
781         output_screen();
782         output_json(0);
783         $latest_update = [Time::HiRes::gettimeofday];
784         $last_output_had_pv = has_pv($info);
785 }
786
787 sub has_pv {
788         my $info = shift;
789         return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
790         return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
791         return 0;
792 }
793
794 sub output_screen {
795         my $info = $engine->{'info'};
796         my $id = $engine->{'id'};
797
798         my $text = 'Analysis';
799         if ($pos_calculating->{'last_move'} ne 'none') {
800                 if ($pos_calculating->{'toplay'} eq 'W') {
801                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
802                 } else {
803                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
804                 }
805                 if (exists($id->{'name'})) {
806                         $text .= ',';
807                 }
808         }
809
810         if (exists($id->{'name'})) {
811                 $text .= " by $id->{'name'}:\n\n";
812         } else {
813                 $text .= ":\n\n";
814         }
815
816         return unless (exists($pos_calculating->{'board'}));
817                 
818         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
819                 # multi-PV
820                 my $mpv = 1;
821                 while (exists($info->{'pv' . $mpv})) {
822                         $text .= sprintf "  PV%2u", $mpv;
823                         my $score = short_score($info, $pos_calculating, $mpv);
824                         $text .= "  ($score)" if (defined($score));
825
826                         my $tbhits = '';
827                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
828                                 if ($info->{'tbhits' . $mpv} == 1) {
829                                         $tbhits = ", 1 tbhit";
830                                 } else {
831                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
832                                 }
833                         }
834
835                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
836                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
837                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
838                         }
839
840                         $text .= ":\n";
841                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
842                         $text .= "\n";
843                         ++$mpv;
844                 }
845         } else {
846                 # single-PV
847                 my $score = long_score($info, $pos_calculating, '');
848                 $text .= "  $score\n" if defined($score);
849                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
850                 $text .=  "\n";
851
852                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
853                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
854                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
855                 }
856                 if (exists($info->{'seldepth'})) {
857                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
858                 }
859                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
860                         if ($info->{'tbhits'} == 1) {
861                                 $text .= ", one Syzygy hit";
862                         } else {
863                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
864                         }
865                 }
866                 $text .= "\n\n";
867         }
868
869         my @refutation_lines = ();
870         if (defined($engine2)) {
871                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
872                         my $info = $engine2->{'info'};
873                         last if (!exists($info->{'pv' . $mpv}));
874                         eval {
875                                 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
876                                 my $pv = $info->{'pv' . $mpv};
877                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
878                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
879                                 if (scalar @pretty_pv > 5) {
880                                         @pretty_pv = @pretty_pv[0..4];
881                                         push @pretty_pv, "...";
882                                 }
883                                 my $key = $pretty_move;
884                                 my $line = sprintf("  %-6s %6s %3s  %s",
885                                         $pretty_move,
886                                         short_score($info, $pos_calculating_second_engine, $mpv),
887                                         "d" . $info->{'depth' . $mpv},
888                                         join(', ', @pretty_pv));
889                                 push @refutation_lines, [ $key, $line ];
890                         };
891                 }
892         }
893
894         if ($#refutation_lines >= 0) {
895                 $text .= "Shallow search of all legal moves:\n\n";
896                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
897                         $text .= $line->[1] . "\n";
898                 }
899                 $text .= "\n\n";        
900         }       
901
902         if ($last_text ne $text) {
903                 print "\e[H\e[2J"; # clear the screen
904                 print $text;
905                 $last_text = $text;
906         }
907 }
908
909 sub output_json {
910         my $historic_json_only = shift;
911         my $info = $engine->{'info'};
912
913         my $json = {};
914         $json->{'position'} = $pos_calculating->to_json_hash();
915         $json->{'engine'} = $engine->{'id'};
916         if (defined($remoteglotconf::engine_url)) {
917                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
918         }
919         if (defined($remoteglotconf::engine_details)) {
920                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
921         }
922         my @grpc_backends = ();
923         if (defined($remoteglotconf::engine_grpc_backend)) {
924                 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
925         }
926         if (defined($remoteglotconf::engine2_grpc_backend)) {
927                 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
928         }
929         $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
930         if (defined($remoteglotconf::move_source)) {
931                 $json->{'move_source'} = $remoteglotconf::move_source;
932         }
933         if (defined($remoteglotconf::move_source_url)) {
934                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
935         }
936         $json->{'score'} = score_digest($info, $pos_calculating, '');
937         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
938
939         $json->{'nodes'} = $info->{'nodes'};
940         $json->{'nps'} = $info->{'nps'};
941         $json->{'depth'} = $info->{'depth'};
942         $json->{'tbhits'} = $info->{'tbhits'};
943         $json->{'seldepth'} = $info->{'seldepth'};
944         $json->{'tablebase'} = $info->{'tablebase'};
945         $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
946
947         my %refutation_lines = ();
948         my @refutation_lines = ();
949         if (defined($engine2)) {
950                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
951                         my $info = $engine2->{'info'};
952                         my $pretty_move = "";
953                         my @pretty_pv = ();
954                         last if (!exists($info->{'pv' . $mpv}));
955
956                         eval {
957                                 complete_using_tbprobe($pos_calculating, $info, $mpv);
958                                 my $pv = $info->{'pv' . $mpv};
959                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
960                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
961                                 $refutation_lines{$pretty_move} = {
962                                         depth => $info->{'depth' . $mpv},
963                                         score => score_digest($info, $pos_calculating, $mpv),
964                                         move => $pretty_move,
965                                         pv => \@pretty_pv,
966                                 };
967                                 if (exists($info->{'splicepos' . $mpv})) {
968                                         $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
969                                 }
970                         };
971                 }
972         }
973         $json->{'refutation_lines'} = \%refutation_lines;
974
975         # Piece together historic score information, to the degree we have it.
976         if (!$historic_json_only && exists($pos_calculating->{'history'})) {
977                 my %score_history = ();
978
979                 local $dbh->{AutoCommit} = 0;
980                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
981                 my $pos;
982                 if (exists($pos_calculating->{'start_fen'})) {
983                         $pos = Position->from_fen($pos_calculating->{'start_fen'});
984                 } else {
985                         $pos = Position->start_pos('white', 'black');
986                 }
987                 $pos->{'chess960'} = $pos_calculating->{'chess960'};
988                 my $halfmove_num = 0;
989                 for my $move (@{$pos_calculating->{'history'}}) {
990                         my $id = id_for_pos($pos, $halfmove_num);
991                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
992                         if (defined($ref)) {
993                                 $score_history{$halfmove_num} = [
994                                         $ref->{'score_type'},
995                                         $ref->{'score_value'}
996                                 ];
997                         }
998                         ++$halfmove_num;
999                         ($pos) = $pos->make_pretty_move($move);
1000                 }
1001                 $q->finish;
1002                 $dbh->commit;
1003
1004                 # If at any point we are missing 10 consecutive moves,
1005                 # truncate the history there. This is so we don't get into
1006                 # a situation where we e.g. start analyzing at move 45,
1007                 # but we have analysis for 1. e4 from some completely different game
1008                 # and thus show a huge hole.
1009                 my $consecutive_missing = 0;
1010                 my $truncate_until = 0;
1011                 for (my $i = $halfmove_num; $i --> 0; ) {
1012                         if ($consecutive_missing >= 10) {
1013                                 delete $score_history{$i};
1014                                 next;
1015                         }
1016                         if (exists($score_history{$i})) {
1017                                 $consecutive_missing = 0;
1018                         } else {
1019                                 ++$consecutive_missing;
1020                         }
1021                 }
1022
1023                 $json->{'score_history'} = \%score_history;
1024         }
1025
1026         # Give out a list of other games going on. (Empty is fine.)
1027         # TODO: Don't bother reading our own file, the data will be stale anyway.
1028         if (!$historic_json_only) {
1029                 my @games = ();
1030
1031                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
1032                 $q->execute;
1033                 while (my $ref = $q->fetchrow_hashref) {
1034                         eval {
1035                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
1036                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
1037
1038                                 die "Missing position" if (!exists($other_game_json->{'position'}));
1039                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
1040                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1041
1042                                 my $game = {
1043                                         id => $ref->{'id'},
1044                                         name => "$white–$black",
1045                                         url => $ref->{'url'},
1046                                         hashurl => $ref->{'hash_url'},
1047                                 };
1048                                 if (defined($other_game_json->{'position'}{'result'})) {
1049                                         $game->{'result'} = $other_game_json->{'position'}{'result'};
1050                                 } else {
1051                                         $game->{'score'} = $other_game_json->{'score'};
1052                                 }
1053                                 push @games, $game;
1054                         };
1055                         if ($@) {
1056                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1057                         }
1058                 }
1059
1060                 if (scalar @games > 0) {
1061                         $json->{'games'} = \@games;
1062                 }
1063         }
1064
1065         my $json_enc = JSON::XS->new;
1066         $json_enc->canonical(1);
1067         my $encoded = $json_enc->encode($json);
1068         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1069                 (defined($last_written_json) && $last_written_json eq $encoded)) {
1070                 atomic_set_contents($remoteglotconf::json_output, $encoded);
1071                 $last_written_json = $encoded;
1072         }
1073
1074         if (exists($pos_calculating->{'history'}) &&
1075             defined($remoteglotconf::json_history_dir)) {
1076                 my $id = id_for_pos($pos_calculating);
1077                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1078
1079                 # Overwrite old analysis (assuming it exists at all) if we're
1080                 # using a different engine, or if we've calculated deeper.
1081                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1082                 # data; it's not that important.
1083                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1084                 my $new_depth = $json->{'depth'} // 0;
1085                 my $new_nodes = $json->{'nodes'} // 0;
1086                 if (!defined($old_engine) ||
1087                     $old_engine ne $json->{'engine'}{'name'} ||
1088                     $new_depth > $old_depth ||
1089                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1090                         atomic_set_contents($filename, $encoded);
1091                         if (defined($json->{'score'})) {
1092                                 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1093                                          '    ON CONFLICT (id) DO UPDATE SET ' .
1094                                          '        score_type=EXCLUDED.score_type, ' .
1095                                          '        score_value=EXCLUDED.score_value, ' .
1096                                          '        engine=EXCLUDED.engine, ' .
1097                                          '        depth=EXCLUDED.depth, ' .
1098                                          '        nodes=EXCLUDED.nodes',
1099                                         undef,
1100                                         $id, $json->{'score'}[0], $json->{'score'}[1],
1101                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1102                         }
1103                 }
1104         }
1105 }
1106
1107 sub atomic_set_contents {
1108         my ($filename, $contents) = @_;
1109
1110         open my $fh, ">", $filename . ".tmp"
1111                 or return;
1112         print $fh $contents;
1113         close $fh;
1114         rename($filename . ".tmp", $filename);
1115 }
1116
1117 sub id_for_pos {
1118         my ($pos, $halfmove_num) = @_;
1119
1120         $halfmove_num //= scalar @{$pos->{'history'}};
1121         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1122         return "move$halfmove_num-$fen";
1123 }
1124
1125 sub get_json_analysis_stats {
1126         my $id = shift;
1127         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1128         if (defined($ref)) {
1129                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1130         } else {
1131                 return ('', 0, 0);
1132         }
1133 }
1134
1135 sub uciprint {
1136         my ($engine, $msg) = @_;
1137         $engine->print($msg);
1138         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1139 }
1140
1141 sub short_score {
1142         my ($info, $pos, $mpv) = @_;
1143
1144         my $invert = ($pos->{'toplay'} eq 'B');
1145         if (defined($info->{'score_mate' . $mpv})) {
1146                 if ($invert) {
1147                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1148                 } else {
1149                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1150                 }
1151         } else {
1152                 if (exists($info->{'score_cp' . $mpv})) {
1153                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1154                         if ($score == 0) {
1155                                 if ($info->{'tablebase'}) {
1156                                         return "TB draw";
1157                                 } else {
1158                                         return " 0.00";
1159                                 }
1160                         }
1161                         if ($invert) {
1162                                 $score = -$score;
1163                         }
1164                         return sprintf "%+5.2f", $score;
1165                 }
1166         }
1167
1168         return undef;
1169 }
1170
1171 # Sufficient for computing long_score, short_score, plot_score and
1172 # (with side-to-play information) score_sort_key.
1173 sub score_digest {
1174         my ($info, $pos, $mpv) = @_;
1175
1176         if (defined($info->{'score_mate' . $mpv})) {
1177                 my $mate = $info->{'score_mate' . $mpv};
1178                 if ($pos->{'toplay'} eq 'B') {
1179                         $mate = -$mate;
1180                 }
1181                 if (exists($info->{'splicepos' . $mpv})) {
1182                         my $sp = $info->{'splicepos' . $mpv};
1183                         if ($mate > 0) {
1184                                 return ['T', $sp];
1185                         } else {
1186                                 return ['t', $sp];
1187                         }
1188                 } else {
1189                         if ($mate > 0) {
1190                                 return ['M', $mate];
1191                         } elsif ($mate < 0) {
1192                                 return ['m', -$mate];
1193                         } elsif ($pos->{'toplay'} eq 'B') {
1194                                 return ['M', 0];
1195                         } else {
1196                                 return ['m', 0];
1197                         }
1198                 }
1199         } else {
1200                 if (exists($info->{'score_cp' . $mpv})) {
1201                         my $score = $info->{'score_cp' . $mpv};
1202                         if ($pos->{'toplay'} eq 'B') {
1203                                 $score = -$score;
1204                         }
1205                         if ($score == 0 && $info->{'tablebase'}) {
1206                                 return ['d', undef];
1207                         } else {
1208                                 return ['cp', int($score)];
1209                         }
1210                 }
1211         }
1212
1213         return undef;
1214 }
1215
1216 sub long_score {
1217         my ($info, $pos, $mpv) = @_;
1218
1219         if (defined($info->{'score_mate' . $mpv})) {
1220                 my $mate = $info->{'score_mate' . $mpv};
1221                 if ($pos->{'toplay'} eq 'B') {
1222                         $mate = -$mate;
1223                 }
1224                 if (exists($info->{'splicepos' . $mpv})) {
1225                         my $sp = $info->{'splicepos' . $mpv};
1226                         if ($mate > 0) {
1227                                 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1228                         } else {
1229                                 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1230                         }
1231                 } else {
1232                         if ($mate > 0) {
1233                                 return sprintf "White mates in %u", $mate;
1234                         } else {
1235                                 return sprintf "Black mates in %u", -$mate;
1236                         }
1237                 }
1238         } else {
1239                 if (exists($info->{'score_cp' . $mpv})) {
1240                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1241                         if ($score == 0) {
1242                                 if ($info->{'tablebase'}) {
1243                                         return "Theoretical draw";
1244                                 } else {
1245                                         return "Score:  0.00";
1246                                 }
1247                         }
1248                         if ($pos->{'toplay'} eq 'B') {
1249                                 $score = -$score;
1250                         }
1251                         return sprintf "Score: %+5.2f", $score;
1252                 }
1253         }
1254
1255         return undef;
1256 }
1257
1258 # For graphs; a single number in centipawns, capped at +/- 500.
1259 sub plot_score {
1260         my ($info, $pos, $mpv) = @_;
1261
1262         my $invert = ($pos->{'toplay'} eq 'B');
1263         if (defined($info->{'score_mate' . $mpv})) {
1264                 my $mate = $info->{'score_mate' . $mpv};
1265                 if ($invert) {
1266                         $mate = -$mate;
1267                 }
1268                 if ($mate > 0) {
1269                         return 500;
1270                 } else {
1271                         return -500;
1272                 }
1273         } else {
1274                 if (exists($info->{'score_cp' . $mpv})) {
1275                         my $score = $info->{'score_cp' . $mpv};
1276                         if ($invert) {
1277                                 $score = -$score;
1278                         }
1279                         $score = 500 if ($score > 500);
1280                         $score = -500 if ($score < -500);
1281                         return int($score);
1282                 }
1283         }
1284
1285         return undef;
1286 }
1287
1288 sub extract_clock {
1289         my ($pgn, $pos) = @_;
1290
1291         # Look for extended PGN clock tags.
1292         my $tags = $pgn->tags;
1293         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1294                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1295                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1296                 return;
1297         }
1298
1299         # Look for TCEC-style time comments.
1300         my $moves = $pgn->moves;
1301         my $comments = $pgn->comments;
1302         my $last_black_move = int((scalar @$moves) / 2);
1303         my $last_white_move = int((1 + scalar @$moves) / 2);
1304
1305         my $black_key = $last_black_move . "b";
1306         my $white_key = $last_white_move . "w";
1307
1308         if (exists($comments->{$white_key}) &&
1309             exists($comments->{$black_key}) &&
1310             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1311             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1312                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1313                 $pos->{'white_clock'} = hms_to_sec($1);
1314                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1315                 $pos->{'black_clock'} = hms_to_sec($1);
1316                 return;
1317         }
1318
1319         delete $pos->{'white_clock'};
1320         delete $pos->{'black_clock'};
1321 }
1322
1323 sub hms_to_sec {
1324         my $hms = shift;
1325         return undef if (!defined($hms));
1326         $hms =~ /(\d+):(\d+):(\d+)/;
1327         return $1 * 3600 + $2 * 60 + $3;
1328 }
1329
1330 sub find_clock_start {
1331         my ($pos, $prev_pos) = @_;
1332
1333         # If the game is over, the clock is stopped.
1334         if (exists($pos->{'result'}) &&
1335             ($pos->{'result'} eq '1-0' ||
1336              $pos->{'result'} eq '1/2-1/2' ||
1337              $pos->{'result'} eq '0-1')) {
1338                 return;
1339         }
1340
1341         # When we don't have any moves, we assume the clock hasn't started yet.
1342         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1343                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1344                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1345                 }
1346                 return;
1347         }
1348
1349         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1350         # The history is needed for id_for_pos.
1351         if (!exists($pos->{'history'})) {
1352                 return;
1353         }
1354
1355         my $id = id_for_pos($pos);
1356         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);
1357         if (defined($clock_info)) {
1358                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1359                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1360                 if ($pos->{'toplay'} eq 'W') {
1361                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1362                 } else {
1363                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1364                 }
1365                 return;
1366         }
1367
1368         # OK, we haven't seen this position before, so we assume the move
1369         # happened right now.
1370
1371         # See if we should do our own clock management (ie., clock information
1372         # is spurious or non-existent).
1373         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1374                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1375                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1376                 if (defined($prev_pos->{'white_clock_target'})) {
1377                         $wc = $prev_pos->{'white_clock_target'} - time;
1378                 }
1379                 if (defined($prev_pos->{'black_clock_target'})) {
1380                         $bc = $prev_pos->{'black_clock_target'} - time;
1381                 }
1382                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1383                 $pos->{'white_clock'} = $wc;
1384                 $pos->{'black_clock'} = $bc;
1385         }
1386
1387         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1388         if (!exists($pos->{$key})) {
1389                 # No clock information.
1390                 return;
1391         }
1392         my $time_left = $pos->{$key};
1393         my ($white_clock_target, $black_clock_target);
1394         if ($pos->{'toplay'} eq 'W') {
1395                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1396         } else {
1397                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1398         }
1399         local $dbh->{AutoCommit} = 0;
1400         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1401         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1402                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1403         $dbh->commit;
1404 }
1405
1406 sub schedule_tb_lookup {
1407         return if (!defined($remoteglotconf::tb_serial_key));
1408         my $pos = $pos_calculating;
1409         return if (exists($tb_cache{$pos->fen()}));
1410
1411         # If there's more than seven pieces, there's not going to be an answer,
1412         # so don't bother.
1413         return if ($pos->num_pieces() > 7);
1414
1415         # Max one at a time. If it's still relevant when it returns,
1416         # schedule_tb_lookup() will be called again.
1417         return if ($tb_lookup_running);
1418
1419         $tb_lookup_running = 1;
1420         my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1421                 $remoteglotconf::tb_serial_key .
1422                 '&auth.password=aquarium&type=0&fen=' . 
1423                 URI::Escape::uri_escape($pos->fen());
1424         print TBLOG "Downloading $url...\n";
1425         AnyEvent::HTTP::http_get($url, sub {
1426                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1427         });
1428 }
1429
1430 sub handle_tb_lookup_return {
1431         my ($body, $header, $pos, $fen) = @_;
1432         print TBLOG "Response for [$fen]:\n";
1433         print TBLOG $header . "\n\n";
1434         print TBLOG $body . "\n\n";
1435         eval {
1436                 my $response = JSON::XS::decode_json($body);
1437                 if ($response->{'ErrorCode'} != 0) {
1438                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1439                 }
1440                 my $state = $response->{'Response'}{'StateString'};
1441                 if ($state eq 'COMPLETE') {
1442                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1443                         if (!defined($pgn) || !$pgn->read_game()) {
1444                                 warn "Error in parsing PGN\n";
1445                         } else {
1446                                 $pgn->quick_parse_game;
1447                                 my $pvpos = $pos;
1448                                 my $moves = $pgn->moves;
1449                                 my @uci_moves = ();
1450                                 for my $move (@$moves) {
1451                                         my $uci_move;
1452                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1453                                         push @uci_moves, $uci_move;
1454                                 }
1455                                 $tb_cache{$fen} = {
1456                                         result => $pgn->result,
1457                                         pv => \@uci_moves,
1458                                         score => $response->{'Response'}{'Score'},
1459                                 };
1460                                 output();
1461                         }
1462                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1463                         # Try again in a second. Note that if we have changed
1464                         # position in the meantime, we might query a completely
1465                         # different position! But that's fine.
1466                 } else {
1467                         die "Unknown response state " . $state;
1468                 }
1469
1470                 # Wait a second before we schedule another one.
1471                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1472                         $tb_lookup_running = 0;
1473                         schedule_tb_lookup();
1474                 });
1475         };
1476         if ($@) {
1477                 warn "Error in tablebase lookup: $@";
1478
1479                 # Don't try this one again, but don't block new lookups either.
1480                 $tb_lookup_running = 0;
1481         }
1482 }
1483
1484 sub open_engine {
1485         my ($cmdline, $tag, $cb) = @_;
1486         return undef if (!defined($cmdline));
1487         return Engine->open($cmdline, $tag, $cb);
1488 }
1489
1490 sub col_letter_to_num {
1491         return ord(shift) - ord('a');
1492 }
1493
1494 sub row_letter_to_num {
1495         return 7 - (ord(shift) - ord('1'));
1496 }
1497
1498 sub parse_uci_move {
1499         my $move = shift;
1500         my $from_col = col_letter_to_num(substr($move, 0, 1));
1501         my $from_row = row_letter_to_num(substr($move, 1, 1));
1502         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1503         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1504         my $promo    = substr($move, 4, 1);
1505         return ($from_row, $from_col, $to_row, $to_col, $promo);
1506 }
1507
1508 sub setoptions {
1509         my ($engine, $config) = @_;
1510         uciprint($engine, "setoption name UCI_AnalyseMode value true");
1511         uciprint($engine, "setoption name Analysis Contempt value Off");
1512         if (exists($config->{'Threads'})) {  # Threads first, because clearing hash can be multithreaded then.
1513                 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1514         }
1515         while (my ($key, $value) = each %$config) {
1516                 next if $key eq 'Threads';
1517                 uciprint($engine, "setoption name $key value $value");
1518         }
1519 }