Add board/position output to a bitpacked format.
[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 <sgunderson@bigfoot.com>
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 FileHandle;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 require 'Position.pm';
24 require 'Engine.pm';
25 require 'config.pm';
26 use strict;
27 use warnings;
28 no warnings qw(once);
29
30 # Program starts here
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
36 my %tb_cache = ();
37 my $tb_lookup_running = 0;
38 my $last_written_json = undef;
39
40 # TODO: Persist (parts of) this so that we can restart.
41 my %clock_target_for_pos = ();
42
43 $| = 1;
44
45 open(FICSLOG, ">ficslog.txt")
46         or die "ficslog.txt: $!";
47 print FICSLOG "Log starting.\n";
48 select(FICSLOG);
49 $| = 1;
50
51 open(UCILOG, ">ucilog.txt")
52         or die "ucilog.txt: $!";
53 print UCILOG "Log starting.\n";
54 select(UCILOG);
55 $| = 1;
56
57 open(TBLOG, ">tblog.txt")
58         or die "tblog.txt: $!";
59 print TBLOG "Log starting.\n";
60 select(TBLOG);
61 $| = 1;
62
63 select(STDOUT);
64
65 # open the chess engine
66 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
67 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
68 my $last_move;
69 my $last_text = '';
70 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
71
72 uciprint($engine, "setoption name UCI_AnalyseMode value true");
73 while (my ($key, $value) = each %remoteglotconf::engine_config) {
74         uciprint($engine, "setoption name $key value $value");
75 }
76 uciprint($engine, "ucinewgame");
77
78 if (defined($engine2)) {
79         uciprint($engine2, "setoption name UCI_AnalyseMode value true");
80         while (my ($key, $value) = each %remoteglotconf::engine2_config) {
81                 uciprint($engine2, "setoption name $key value $value");
82         }
83         uciprint($engine2, "setoption name MultiPV value 500");
84         uciprint($engine2, "ucinewgame");
85 }
86
87 print "Chess engine ready.\n";
88
89 # now talk to FICS
90 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
91 $t->input_log(\*FICSLOG);
92 $t->open($remoteglotconf::server);
93 $t->print($remoteglotconf::nick);
94 $t->waitfor('/Press return to enter the server/');
95 $t->cmd("");
96
97 # set some options
98 $t->cmd("set shout 0");
99 $t->cmd("set seek 0");
100 $t->cmd("set style 12");
101
102 my $ev1 = AnyEvent->io(
103         fh => fileno($t),
104         poll => 'r',
105         cb => sub {    # what callback to execute
106                 while (1) {
107                         my $line = $t->getline(Timeout => 0, errmode => 'return');
108                         return if (!defined($line));
109
110                         chomp $line;
111                         $line =~ tr/\r//d;
112                         handle_fics($line);
113                 }
114         }
115 );
116 if (defined($remoteglotconf::target)) {
117         if ($remoteglotconf::target =~ /^http:/) {
118                 fetch_pgn($remoteglotconf::target);
119         } else {
120                 $t->cmd("observe $remoteglotconf::target");
121         }
122 }
123 print "FICS ready.\n";
124
125 # Engine events have already been set up by Engine.pm.
126 EV::run;
127
128 sub handle_uci {
129         my ($engine, $line, $primary) = @_;
130
131         return if $line =~ /(upper|lower)bound/;
132
133         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
134         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
135         if ($line =~ /^info/) {
136                 my (@infos) = split / /, $line;
137                 shift @infos;
138
139                 parse_infos($engine, @infos);
140         }
141         if ($line =~ /^id/) {
142                 my (@ids) = split / /, $line;
143                 shift @ids;
144
145                 parse_ids($engine, @ids);
146         }
147         if ($line =~ /^bestmove/) {
148                 if ($primary) {
149                         return if (!$remoteglotconf::uci_assume_full_compliance);
150                         if (defined($pos_waiting)) {
151                                 uciprint($engine, "position fen " . $pos_waiting->fen());
152                                 uciprint($engine, "go infinite");
153
154                                 $pos_calculating = $pos_waiting;
155                                 $pos_waiting = undef;
156                         }
157                 } else {
158                         $engine2->{'info'} = {};
159                         my $pos = $pos_waiting // $pos_calculating;
160                         uciprint($engine2, "position fen " . $pos->fen());
161                         uciprint($engine2, "go infinite");
162                         $pos_calculating_second_engine = $pos;
163                 }
164         }
165         output();
166 }
167
168 my $getting_movelist = 0;
169 my $pos_for_movelist = undef;
170 my @uci_movelist = ();
171 my @pretty_movelist = ();
172
173 sub handle_fics {
174         my $line = shift;
175         if ($line =~ /^<12> /) {
176                 handle_position(Position->new($line));
177                 $t->cmd("moves");
178         }
179         if ($line =~ /^Movelist for game /) {
180                 my $pos = $pos_waiting // $pos_calculating;
181                 if (defined($pos)) {
182                         @uci_movelist = ();
183                         @pretty_movelist = ();
184                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
185                         $getting_movelist = 1;
186                 }
187         }
188         if ($getting_movelist &&
189             $line =~ /^\s* \d+\. \s+                     # move number
190                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
191                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
192                      /x) {
193                 eval {
194                         my $uci_move;
195                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
196                         push @uci_movelist, $uci_move;
197                         push @pretty_movelist, $1;
198
199                         if (defined($2)) {
200                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
201                                 push @uci_movelist, $uci_move;
202                                 push @pretty_movelist, $2;
203                         }
204                 };
205                 if ($@) {
206                         warn "Error when getting FICS move history: $@";
207                         $getting_movelist = 0;
208                 }
209         }
210         if ($getting_movelist &&
211             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
212                 # End of movelist.
213                 for my $pos ($pos_waiting, $pos_calculating) {
214                         next if (!defined($pos));
215                         if ($pos->fen() eq $pos_for_movelist->fen()) {
216                                 $pos->{'pretty_history'} = \@pretty_movelist;
217                         }
218                 }
219                 $getting_movelist = 0;
220         }
221         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
222                 my ($who, $msg) = ($1, $2);
223
224                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
225
226                 if ($msg =~ /^fics (.*?)$/) {
227                         $t->cmd("tell $who Executing '$1' on FICS.");
228                         $t->cmd($1);
229                 } elsif ($msg =~ /^uci (.*?)$/) {
230                         $t->cmd("tell $who Sending '$1' to the engine.");
231                         print { $engine->{'write'} } "$1\n";
232                 } elsif ($msg =~ /^pgn (.*?)$/) {
233                         my $url = $1;
234                         $t->cmd("tell $who Starting to poll '$url'.");
235                         fetch_pgn($url);
236                 } elsif ($msg =~ /^stoppgn$/) {
237                         $t->cmd("tell $who Stopping poll.");
238                         $stop_pgn_fetch = 1;
239                         $http_timer = undef;
240                 } elsif ($msg =~ /^quit$/) {
241                         $t->cmd("tell $who Bye bye.");
242                         exit;
243                 } else {
244                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
245                 }
246         }
247         #print "FICS: [$line]\n";
248 }
249
250 # Starts periodic fetching of PGNs from the given URL.
251 sub fetch_pgn {
252         my ($url) = @_;
253         AnyEvent::HTTP::http_get($url, sub {
254                 handle_pgn(@_, $url);
255         });
256 }
257
258 my ($last_pgn_white, $last_pgn_black);
259 my @last_pgn_uci_moves = ();
260 my $pgn_hysteresis_counter = 0;
261
262 sub handle_pgn {
263         my ($body, $header, $url) = @_;
264
265         if ($stop_pgn_fetch) {
266                 $stop_pgn_fetch = 0;
267                 $http_timer = undef;
268                 return;
269         }
270
271         my $pgn = Chess::PGN::Parse->new(undef, $body);
272         if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
273                 warn "Error in parsing PGN from $url\n";
274         } else {
275                 eval {
276                         $pgn->parse_game({ save_comments => 'yes' });
277                         my $pos = Position->start_pos($pgn->white, $pgn->black);
278                         my $moves = $pgn->moves;
279                         my @uci_moves = ();
280                         for my $move (@$moves) {
281                                 my $uci_move;
282                                 ($pos, $uci_move) = $pos->make_pretty_move($move);
283                                 push @uci_moves, $uci_move;
284                         }
285                         $pos->{'result'} = $pgn->result;
286                         $pos->{'pretty_history'} = $moves;
287
288                         extract_clock($pgn, $pos);
289
290                         # Sometimes, PGNs lose a move or two for a short while,
291                         # or people push out new ones non-atomically. 
292                         # Thus, if we PGN doesn't change names but becomes
293                         # shorter, we mistrust it for a few seconds.
294                         my $trust_pgn = 1;
295                         if (defined($last_pgn_white) && defined($last_pgn_black) &&
296                             $last_pgn_white eq $pgn->white &&
297                             $last_pgn_black eq $pgn->black &&
298                             scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
299                                 if (++$pgn_hysteresis_counter < 3) {
300                                         $trust_pgn = 0; 
301                                 }
302                         }
303                         if ($trust_pgn) {
304                                 $last_pgn_white = $pgn->white;
305                                 $last_pgn_black = $pgn->black;
306                                 @last_pgn_uci_moves = @uci_moves;
307                                 $pgn_hysteresis_counter = 0;
308                                 handle_position($pos);
309                         }
310                 };
311                 if ($@) {
312                         warn "Error in parsing moves from $url\n";
313                 }
314         }
315         
316         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
317                 fetch_pgn($url);
318         });
319 }
320
321 sub handle_position {
322         my ($pos) = @_;
323         find_clock_start($pos);
324                 
325         # if this is already in the queue, ignore it
326         return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
327
328         # if we're already chewing on this and there's nothing else in the queue,
329         # also ignore it
330         return if (!defined($pos_waiting) && defined($pos_calculating) &&
331                  $pos->fen() eq $pos_calculating->fen());
332
333         # if we're already thinking on something, stop and wait for the engine
334         # to approve
335         if (defined($pos_calculating)) {
336                 # Store the final data we have for this position in the history,
337                 # with the precise clock information we just got from the new
338                 # position. (Historic positions store the clock at the end of
339                 # the position.)
340                 #
341                 # Do not output anything new to the main analysis; that's
342                 # going to be obsolete really soon.
343                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
344                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
345                 delete $pos_calculating->{'white_clock_target'};
346                 delete $pos_calculating->{'black_clock_target'};
347                 output_json(1);
348
349                 if (!defined($pos_waiting)) {
350                         uciprint($engine, "stop");
351                 }
352                 if ($remoteglotconf::uci_assume_full_compliance) {
353                         $pos_waiting = $pos;
354                 } else {
355                         uciprint($engine, "position fen " . $pos->fen());
356                         uciprint($engine, "go infinite");
357                         $pos_calculating = $pos;
358                 }
359         } else {
360                 # it's wrong just to give the FEN (the move history is useful,
361                 # and per the UCI spec, we should really have sent "ucinewgame"),
362                 # but it's easier
363                 uciprint($engine, "position fen " . $pos->fen());
364                 uciprint($engine, "go infinite");
365                 $pos_calculating = $pos;
366         }
367
368         if (defined($engine2)) {
369                 if (defined($pos_calculating_second_engine)) {
370                         uciprint($engine2, "stop");
371                 } else {
372                         uciprint($engine2, "position fen " . $pos->fen());
373                         uciprint($engine2, "go infinite");
374                         $pos_calculating_second_engine = $pos;
375                 }
376                 $engine2->{'info'} = {};
377         }
378
379         $engine->{'info'} = {};
380         $last_move = time;
381
382         schedule_tb_lookup();
383
384         # 
385         # Output a command every move to note that we're
386         # still paying attention -- this is a good tradeoff,
387         # since if no move has happened in the last half
388         # hour, the analysis/relay has most likely stopped
389         # and we should stop hogging server resources.
390         #
391         $t->cmd("date");
392 }
393
394 sub parse_infos {
395         my ($engine, @x) = @_;
396         my $mpv = '';
397
398         my $info = $engine->{'info'};
399
400         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
401         for my $i (0..$#x - 1) {
402                 if ($x[$i] eq 'multipv') {
403                         $mpv = $x[$i + 1];
404                         next;
405                 }
406         }
407
408         while (scalar @x > 0) {
409                 if ($x[0] eq 'multipv') {
410                         # Dealt with above
411                         shift @x;
412                         shift @x;
413                         next;
414                 }
415                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
416                         my $key = shift @x;
417                         my $value = shift @x;
418                         $info->{$key} = $value;
419                         next;
420                 }
421                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
422                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
423                     $x[0] eq 'tbhits') {
424                         my $key = shift @x;
425                         my $value = shift @x;
426                         $info->{$key . $mpv} = $value;
427                         next;
428                 }
429                 if ($x[0] eq 'score') {
430                         shift @x;
431
432                         delete $info->{'score_cp' . $mpv};
433                         delete $info->{'score_mate' . $mpv};
434
435                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
436                                 if ($x[0] eq 'cp') {
437                                         shift @x;
438                                         $info->{'score_cp' . $mpv} = shift @x;
439                                 } elsif ($x[0] eq 'mate') {
440                                         shift @x;
441                                         $info->{'score_mate' . $mpv} = shift @x;
442                                 } else {
443                                         shift @x;
444                                 }
445                         }
446                         next;
447                 }
448                 if ($x[0] eq 'pv') {
449                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
450                         last;
451                 }
452                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
453                         last;
454                 }
455
456                 #print "unknown info '$x[0]', trying to recover...\n";
457                 #shift @x;
458                 die "Unknown info '" . join(',', @x) . "'";
459
460         }
461 }
462
463 sub parse_ids {
464         my ($engine, @x) = @_;
465
466         while (scalar @x > 0) {
467                 if ($x[0] =~ /^(name|author)$/) {
468                         my $key = shift @x;
469                         my $value = join(' ', @x);
470                         $engine->{'id'}{$key} = $value;
471                         last;
472                 }
473
474                 # unknown
475                 shift @x;
476         }
477 }
478
479 sub prettyprint_pv_no_cache {
480         my ($board, @pvs) = @_;
481
482         if (scalar @pvs == 0 || !defined($pvs[0])) {
483                 return ();
484         }
485
486         my $pv = shift @pvs;
487         my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
488         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
489         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
490 }
491
492 sub prettyprint_pv {
493         my ($pos, @pvs) = @_;
494
495         my $cachekey = join('', @pvs);
496         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
497                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
498         } else {
499                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
500                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
501                 return @res;
502         }
503 }
504
505 sub output {
506         #return;
507
508         return if (!defined($pos_calculating));
509
510         # Don't update too often.
511         my $age = Time::HiRes::tv_interval($latest_update);
512         if ($age < $remoteglotconf::update_max_interval) {
513                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
514                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
515                 return;
516         }
517         
518         my $info = $engine->{'info'};
519
520         #
521         # If we have tablebase data from a previous lookup, replace the
522         # engine data with the data from the tablebase.
523         #
524         my $fen = $pos_calculating->fen();
525         if (exists($tb_cache{$fen})) {
526                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
527                         delete $info->{$key . '1'};
528                         delete $info->{$key};
529                 }
530                 $info->{'nodes'} = 0;
531                 $info->{'nps'} = 0;
532                 $info->{'depth'} = 0;
533                 $info->{'seldepth'} = 0;
534                 $info->{'tbhits'} = 0;
535
536                 my $t = $tb_cache{$fen};
537                 my $pv = $t->{'pv'};
538                 my $matelen = int((1 + $t->{'score'}) / 2);
539                 if ($t->{'result'} eq '1/2-1/2') {
540                         $info->{'score_cp'} = 0;
541                 } elsif ($t->{'result'} eq '1-0') {
542                         if ($pos_calculating->{'toplay'} eq 'B') {
543                                 $info->{'score_mate'} = -$matelen;
544                         } else {
545                                 $info->{'score_mate'} = $matelen;
546                         }
547                 } else {
548                         if ($pos_calculating->{'toplay'} eq 'B') {
549                                 $info->{'score_mate'} = $matelen;
550                         } else {
551                                 $info->{'score_mate'} = -$matelen;
552                         }
553                 }
554                 $info->{'pv'} = $pv;
555                 $info->{'tablebase'} = 1;
556         } else {
557                 $info->{'tablebase'} = 0;
558         }
559         
560         #
561         # Some programs _always_ report MultiPV, even with only one PV.
562         # In this case, we simply use that data as if MultiPV was never
563         # specified.
564         #
565         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
566                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
567                         if (exists($info->{$key . '1'})) {
568                                 $info->{$key} = $info->{$key . '1'};
569                         }
570                 }
571         }
572         
573         #
574         # Check the PVs first. if they're invalid, just wait, as our data
575         # is most likely out of sync. This isn't a very good solution, as
576         # it can frequently miss stuff, but it's good enough for most users.
577         #
578         eval {
579                 my $dummy;
580                 if (exists($info->{'pv'})) {
581                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
582                 }
583         
584                 my $mpv = 1;
585                 while (exists($info->{'pv' . $mpv})) {
586                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
587                         ++$mpv;
588                 }
589         };
590         if ($@) {
591                 $engine->{'info'} = {};
592                 return;
593         }
594
595         output_screen();
596         output_json(0);
597         $latest_update = [Time::HiRes::gettimeofday];
598 }
599
600 sub output_screen {
601         my $info = $engine->{'info'};
602         my $id = $engine->{'id'};
603
604         my $text = 'Analysis';
605         if ($pos_calculating->{'last_move'} ne 'none') {
606                 if ($pos_calculating->{'toplay'} eq 'W') {
607                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
608                 } else {
609                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
610                 }
611                 if (exists($id->{'name'})) {
612                         $text .= ',';
613                 }
614         }
615
616         if (exists($id->{'name'})) {
617                 $text .= " by $id->{'name'}:\n\n";
618         } else {
619                 $text .= ":\n\n";
620         }
621
622         return unless (exists($pos_calculating->{'board'}));
623                 
624         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
625                 # multi-PV
626                 my $mpv = 1;
627                 while (exists($info->{'pv' . $mpv})) {
628                         $text .= sprintf "  PV%2u", $mpv;
629                         my $score = short_score($info, $pos_calculating, $mpv);
630                         $text .= "  ($score)" if (defined($score));
631
632                         my $tbhits = '';
633                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
634                                 if ($info->{'tbhits' . $mpv} == 1) {
635                                         $tbhits = ", 1 tbhit";
636                                 } else {
637                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
638                                 }
639                         }
640
641                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
642                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
643                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
644                         }
645
646                         $text .= ":\n";
647                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
648                         $text .= "\n";
649                         ++$mpv;
650                 }
651         } else {
652                 # single-PV
653                 my $score = long_score($info, $pos_calculating, '');
654                 $text .= "  $score\n" if defined($score);
655                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
656                 $text .=  "\n";
657
658                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
659                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
660                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
661                 }
662                 if (exists($info->{'seldepth'})) {
663                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
664                 }
665                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
666                         if ($info->{'tbhits'} == 1) {
667                                 $text .= ", one Syzygy hit";
668                         } else {
669                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
670                         }
671                 }
672                 $text .= "\n\n";
673         }
674
675         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
676
677         my @refutation_lines = ();
678         if (defined($engine2)) {
679                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
680                         my $info = $engine2->{'info'};
681                         last if (!exists($info->{'pv' . $mpv}));
682                         eval {
683                                 my $pv = $info->{'pv' . $mpv};
684
685                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
686                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
687                                 if (scalar @pretty_pv > 5) {
688                                         @pretty_pv = @pretty_pv[0..4];
689                                         push @pretty_pv, "...";
690                                 }
691                                 my $key = $pretty_move;
692                                 my $line = sprintf("  %-6s %6s %3s  %s",
693                                         $pretty_move,
694                                         short_score($info, $pos_calculating_second_engine, $mpv),
695                                         "d" . $info->{'depth' . $mpv},
696                                         join(', ', @pretty_pv));
697                                 push @refutation_lines, [ $key, $line ];
698                         };
699                 }
700         }
701
702         if ($#refutation_lines >= 0) {
703                 $text .= "Shallow search of all legal moves:\n\n";
704                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
705                         $text .= $line->[1] . "\n";
706                 }
707                 $text .= "\n\n";        
708         }       
709
710         if ($last_text ne $text) {
711                 print "\e[H\e[2J"; # clear the screen
712                 print $text;
713                 $last_text = $text;
714         }
715 }
716
717 sub output_json {
718         my $historic_json_only = shift;
719         my $info = $engine->{'info'};
720
721         my $json = {};
722         $json->{'position'} = $pos_calculating->to_json_hash();
723         $json->{'id'} = $engine->{'id'};
724         $json->{'score'} = long_score($info, $pos_calculating, '');
725         $json->{'short_score'} = short_score($info, $pos_calculating, '');
726
727         $json->{'nodes'} = $info->{'nodes'};
728         $json->{'nps'} = $info->{'nps'};
729         $json->{'depth'} = $info->{'depth'};
730         $json->{'tbhits'} = $info->{'tbhits'};
731         $json->{'seldepth'} = $info->{'seldepth'};
732         $json->{'tablebase'} = $info->{'tablebase'};
733
734         $json->{'pv_uci'} = $info->{'pv'};  # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
735         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
736
737         my %refutation_lines = ();
738         my @refutation_lines = ();
739         if (defined($engine2)) {
740                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
741                         my $info = $engine2->{'info'};
742                         my $pretty_move = "";
743                         my @pretty_pv = ();
744                         last if (!exists($info->{'pv' . $mpv}));
745
746                         eval {
747                                 my $pv = $info->{'pv' . $mpv};
748                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
749                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
750                                 $refutation_lines{$pv->[0]} = {
751                                         sort_key => $pretty_move,
752                                         depth => $info->{'depth' . $mpv},
753                                         score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
754                                         pretty_score => short_score($info, $pos_calculating, $mpv),
755                                         pretty_move => $pretty_move,
756                                         pv_pretty => \@pretty_pv,
757                                 };
758                         };
759                 }
760         }
761         $json->{'refutation_lines'} = \%refutation_lines;
762
763         my $encoded = JSON::XS::encode_json($json);
764         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
765                 (defined($last_written_json) && $last_written_json eq $encoded)) {
766                 atomic_set_contents($remoteglotconf::json_output, $encoded);
767                 $last_written_json = $encoded;
768         }
769
770         if (exists($pos_calculating->{'pretty_history'}) &&
771             defined($remoteglotconf::json_history_dir)) {
772                 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
773
774                 # Overwrite old analysis (assuming it exists at all) if we're
775                 # using a different engine, or if we've calculated deeper.
776                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
777                 # data; it's not that important.
778                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
779                 my $new_depth = $json->{'depth'} // 0;
780                 my $new_nodes = $json->{'nodes'} // 0;
781                 if (!defined($old_engine) ||
782                     $old_engine ne $json->{'id'}{'name'} ||
783                     $new_depth > $old_depth ||
784                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
785                         atomic_set_contents($filename, $encoded);
786                 }
787         }
788 }
789
790 sub atomic_set_contents {
791         my ($filename, $contents) = @_;
792
793         open my $fh, ">", $filename . ".tmp"
794                 or return;
795         print $fh $contents;
796         close $fh;
797         rename($filename . ".tmp", $filename);
798 }
799
800 sub id_for_pos {
801         my $pos = shift;
802
803         my $halfmove_num = scalar @{$pos->{'pretty_history'}};
804         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
805         return "move$halfmove_num-$fen";
806 }
807
808 sub get_json_analysis_stats {
809         my $filename = shift;
810
811         my ($engine, $depth, $nodes);
812
813         open my $fh, "<", $filename
814                 or return undef;
815         local $/ = undef;
816         eval {
817                 my $json = JSON::XS::decode_json(<$fh>);
818                 $engine = $json->{'id'}{'name'} // die;
819                 $depth = $json->{'depth'} // 0;
820                 $nodes = $json->{'nodes'} // 0;
821         };
822         close $fh;
823         if ($@) {
824                 warn "Error in decoding $filename: $@";
825                 return undef;
826         }
827         return ($engine, $depth, $nodes);
828 }
829
830 sub uciprint {
831         my ($engine, $msg) = @_;
832         $engine->print($msg);
833         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
834 }
835
836 sub short_score {
837         my ($info, $pos, $mpv) = @_;
838
839         my $invert = ($pos->{'toplay'} eq 'B');
840         if (defined($info->{'score_mate' . $mpv})) {
841                 if ($invert) {
842                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
843                 } else {
844                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
845                 }
846         } else {
847                 if (exists($info->{'score_cp' . $mpv})) {
848                         my $score = $info->{'score_cp' . $mpv} * 0.01;
849                         if ($score == 0) {
850                                 if ($info->{'tablebase'}) {
851                                         return "TB draw";
852                                 } else {
853                                         return " 0.00";
854                                 }
855                         }
856                         if ($invert) {
857                                 $score = -$score;
858                         }
859                         return sprintf "%+5.2f", $score;
860                 }
861         }
862
863         return undef;
864 }
865
866 sub score_sort_key {
867         my ($info, $pos, $mpv, $invert) = @_;
868
869         if (defined($info->{'score_mate' . $mpv})) {
870                 my $mate = $info->{'score_mate' . $mpv};
871                 my $score;
872                 if ($mate > 0) {
873                         # Side to move mates
874                         $score = 99999 - $mate;
875                 } else {
876                         # Side to move is getting mated (note the double negative for $mate)
877                         $score = -99999 - $mate;
878                 }
879                 if ($invert) {
880                         $score = -$score;
881                 }
882                 return $score;
883         } else {
884                 if (exists($info->{'score_cp' . $mpv})) {
885                         my $score = $info->{'score_cp' . $mpv};
886                         if ($invert) {
887                                 $score = -$score;
888                         }
889                         return $score;
890                 }
891         }
892
893         return undef;
894 }
895
896 sub long_score {
897         my ($info, $pos, $mpv) = @_;
898
899         if (defined($info->{'score_mate' . $mpv})) {
900                 my $mate = $info->{'score_mate' . $mpv};
901                 if ($pos->{'toplay'} eq 'B') {
902                         $mate = -$mate;
903                 }
904                 if ($mate > 0) {
905                         return sprintf "White mates in %u", $mate;
906                 } else {
907                         return sprintf "Black mates in %u", -$mate;
908                 }
909         } else {
910                 if (exists($info->{'score_cp' . $mpv})) {
911                         my $score = $info->{'score_cp' . $mpv} * 0.01;
912                         if ($score == 0) {
913                                 if ($info->{'tablebase'}) {
914                                         return "Theoretical draw";
915                                 } else {
916                                         return "Score:  0.00";
917                                 }
918                         }
919                         if ($pos->{'toplay'} eq 'B') {
920                                 $score = -$score;
921                         }
922                         return sprintf "Score: %+5.2f", $score;
923                 }
924         }
925
926         return undef;
927 }
928
929 my %book_cache = ();
930 sub book_info {
931         my ($fen, $board, $toplay) = @_;
932
933         if (exists($book_cache{$fen})) {
934                 return $book_cache{$fen};
935         }
936
937         my $ret = `./booklook $fen`;
938         return "" if ($ret =~ /Not found/ || $ret eq '');
939
940         my @moves = ();
941
942         for my $m (split /\n/, $ret) {
943                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
944
945                 my $pmove;
946                 if ($move eq '')  {
947                         $pmove = '(current)';
948                 } else {
949                         ($pmove) = prettyprint_pv_no_cache($board, $move);
950                         $pmove .= $annotation;
951                 }
952
953                 my $score;
954                 if ($toplay eq 'W') {
955                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
956                 } else {
957                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
958                 }
959                 my $n = $win + $draw + $lose;
960                 
961                 my $percent;
962                 if ($n == 0) {
963                         $percent = "     ";
964                 } else {
965                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
966                 }
967
968                 push @moves, [ $pmove, $n, $percent, $rating ];
969         }
970
971         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
972         
973         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
974         for my $m (@moves) {
975                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
976         }
977
978         return $text;
979 }
980
981 sub extract_clock {
982         my ($pgn, $pos) = @_;
983
984         # Look for extended PGN clock tags.
985         my $tags = $pgn->tags;
986         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
987                 $pos->{'white_clock'} = $tags->{'WhiteClock'};
988                 $pos->{'black_clock'} = $tags->{'BlackClock'};
989
990                 $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
991                 $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
992                 return;
993         }
994
995         # Look for TCEC-style time comments.
996         my $moves = $pgn->moves;
997         my $comments = $pgn->comments;
998         my $last_black_move = int((scalar @$moves) / 2);
999         my $last_white_move = int((1 + scalar @$moves) / 2);
1000
1001         my $black_key = $last_black_move . "b";
1002         my $white_key = $last_white_move . "w";
1003
1004         if (exists($comments->{$white_key}) &&
1005             exists($comments->{$black_key}) &&
1006             $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/ &&
1007             $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/) {
1008                 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/;
1009                 $pos->{'white_clock'} = $1;
1010                 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/;
1011                 $pos->{'black_clock'} = $1;
1012                 return;
1013         }
1014 }
1015
1016 sub find_clock_start {
1017         my $pos = shift;
1018
1019         # If the game is over, the clock is stopped.
1020         if (exists($pos->{'result'}) &&
1021             ($pos->{'result'} eq '1-0' ||
1022              $pos->{'result'} eq '1/2-1/2' ||
1023              $pos->{'result'} eq '0-1')) {
1024                 return;
1025         }
1026
1027         # When we don't have any moves, we assume the clock hasn't started yet.
1028         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1029                 return;
1030         }
1031
1032         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1033         if (!exists($pos->{'pretty_history'})) {
1034                 return;
1035         }
1036
1037         my $id = id_for_pos($pos);
1038         if (exists($clock_target_for_pos{$id})) {
1039                 if ($pos->{'toplay'} eq 'W') {
1040                         $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1041                 } else {
1042                         $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1043                 }
1044                 return;
1045         }
1046
1047         # OK, we haven't seen this position before, so we assume the move
1048         # happened right now.
1049         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1050         if (!exists($pos->{$key})) {
1051                 # No clock information.
1052                 return;
1053         }
1054         $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
1055         my $time_left = $1 * 3600 + $2 * 60 + $3;
1056         $clock_target_for_pos{$id} = time + $time_left;
1057         if ($pos->{'toplay'} eq 'W') {
1058                 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1059         } else {
1060                 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1061         }
1062 }
1063
1064 sub schedule_tb_lookup {
1065         return if (!defined($remoteglotconf::tb_serial_key));
1066         my $pos = $pos_waiting // $pos_calculating;
1067         return if (exists($tb_cache{$pos->fen()}));
1068
1069         # If there's more than seven pieces, there's not going to be an answer,
1070         # so don't bother.
1071         return if ($pos->num_pieces() > 7);
1072
1073         # Max one at a time. If it's still relevant when it returns,
1074         # schedule_tb_lookup() will be called again.
1075         return if ($tb_lookup_running);
1076
1077         $tb_lookup_running = 1;
1078         my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1079                 $remoteglotconf::tb_serial_key .
1080                 '&auth.password=aquarium&type=0&fen=' . 
1081                 URI::Escape::uri_escape($pos->fen());
1082         print TBLOG "Downloading $url...\n";
1083         AnyEvent::HTTP::http_get($url, sub {
1084                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1085         });
1086 }
1087
1088 sub handle_tb_lookup_return {
1089         my ($body, $header, $pos, $fen) = @_;
1090         print TBLOG "Response for [$fen]:\n";
1091         print TBLOG $header . "\n\n";
1092         print TBLOG $body . "\n\n";
1093         eval {
1094                 my $response = JSON::XS::decode_json($body);
1095                 if ($response->{'ErrorCode'} != 0) {
1096                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1097                 }
1098                 my $state = $response->{'Response'}{'StateString'};
1099                 if ($state eq 'COMPLETE') {
1100                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1101                         if (!defined($pgn) || !$pgn->read_game()) {
1102                                 warn "Error in parsing PGN\n";
1103                         } else {
1104                                 $pgn->quick_parse_game;
1105                                 my $pvpos = $pos;
1106                                 my $moves = $pgn->moves;
1107                                 my @uci_moves = ();
1108                                 for my $move (@$moves) {
1109                                         my $uci_move;
1110                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1111                                         push @uci_moves, $uci_move;
1112                                 }
1113                                 $tb_cache{$fen} = {
1114                                         result => $pgn->result,
1115                                         pv => \@uci_moves,
1116                                         score => $response->{'Response'}{'Score'},
1117                                 };
1118                                 output();
1119                         }
1120                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1121                         # Try again in a second. Note that if we have changed
1122                         # position in the meantime, we might query a completely
1123                         # different position! But that's fine.
1124                 } else {
1125                         die "Unknown response state " . $state;
1126                 }
1127
1128                 # Wait a second before we schedule another one.
1129                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1130                         $tb_lookup_running = 0;
1131                         schedule_tb_lookup();
1132                 });
1133         };
1134         if ($@) {
1135                 warn "Error in tablebase lookup: $@";
1136
1137                 # Don't try this one again, but don't block new lookups either.
1138                 $tb_lookup_running = 0;
1139         }
1140 }
1141
1142 sub open_engine {
1143         my ($cmdline, $tag, $cb) = @_;
1144         return undef if (!defined($cmdline));
1145         return Engine->open($cmdline, $tag, $cb);
1146 }
1147
1148 sub col_letter_to_num {
1149         return ord(shift) - ord('a');
1150 }
1151
1152 sub row_letter_to_num {
1153         return 7 - (ord(shift) - ord('1'));
1154 }
1155
1156 sub parse_uci_move {
1157         my $move = shift;
1158         my $from_col = col_letter_to_num(substr($move, 0, 1));
1159         my $from_row = row_letter_to_num(substr($move, 1, 1));
1160         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1161         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1162         my $promo    = substr($move, 4, 1);
1163         return ($from_col, $from_row, $to_col, $to_row, $promo);
1164 }