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