]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
e1da304a6732c49023471600ddf310af5e7663ac
[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 Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use JSON::XS;
17 use strict;
18 use warnings;
19
20 # Configuration
21 my $server = "freechess.org";
22 my $target = "GMCarlsen";
23 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
24 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
25 my $telltarget = undef;   # undef to be silent
26 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
27 my $uci_assume_full_compliance = 0;                    # dangerous :-)
28 my $update_max_interval = 1.0;
29 my @masters = (
30         'Sesse',
31         'Sessse',
32         'Sesssse',
33         'greatestguns',
34         'beuki'
35 );
36
37 # Program starts here
38 $SIG{ALRM} = sub { output(); };
39 my $latest_update = undef;
40
41 $| = 1;
42
43 open(FICSLOG, ">ficslog.txt")
44         or die "ficslog.txt: $!";
45 print FICSLOG "Log starting.\n";
46 select(FICSLOG);
47 $| = 1;
48
49 open(UCILOG, ">ucilog.txt")
50         or die "ucilog.txt: $!";
51 print UCILOG "Log starting.\n";
52 select(UCILOG);
53 $| = 1;
54 select(STDOUT);
55
56 # open the chess engine
57 my $engine = open_engine($engine_cmdline, 'E1');
58 my $engine2 = open_engine($engine2_cmdline, 'E2');
59 my ($last_move, $last_tell);
60 my $last_text = '';
61 my $last_told_text = '';
62 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
63
64 uciprint($engine, "setoption name UCI_AnalyseMode value true");
65 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
66 uciprint($engine, "setoption name NalimovUsage value Rarely");
67 uciprint($engine, "setoption name Hash value 1024");
68 # uciprint($engine, "setoption name MultiPV value 2");
69 uciprint($engine, "ucinewgame");
70
71 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
72 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
73 uciprint($engine2, "setoption name NalimovUsage value Rarely");
74 uciprint($engine2, "setoption name Hash value 1024");
75 uciprint($engine2, "setoption name Threads value 8");
76 uciprint($engine2, "setoption name MultiPV value 500");
77 uciprint($engine2, "ucinewgame");
78
79 print "Chess engine ready.\n";
80
81 # now talk to FICS
82 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
83 $t->input_log(\*FICSLOG);
84 $t->open($server);
85 $t->print("SesseBOT");
86 $t->waitfor('/Press return to enter the server/');
87 $t->cmd("");
88
89 # set some options
90 $t->cmd("set shout 0");
91 $t->cmd("set seek 0");
92 $t->cmd("set style 12");
93 $t->cmd("observe $target");
94
95 # main loop
96 print "FICS ready.\n";
97 while (1) {
98         my $rin = '';
99         my $rout;
100         vec($rin, fileno($engine->{'read'}), 1) = 1;
101         vec($rin, fileno($engine2->{'read'}), 1) = 1;
102         vec($rin, fileno($t), 1) = 1;
103
104         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
105         my $sleep = 1.0;
106
107         while (1) {
108                 my $line = $t->getline(Timeout => 0, errmode => 'return');
109                 last if (!defined($line));
110
111                 chomp $line;
112                 $line =~ tr/\r//d;
113                 if ($line =~ /^<12> /) {
114                         my $pos = style12_to_pos($line);
115                         
116                         # if this is already in the queue, ignore it
117                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
118
119                         # if we're already chewing on this and there's nothing else in the queue,
120                         # also ignore it
121                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
122                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
123
124                         # if we're already thinking on something, stop and wait for the engine
125                         # to approve
126                         if (defined($pos_calculating)) {
127                                 if (!defined($pos_waiting)) {
128                                         uciprint($engine, "stop");
129                                 }
130                                 if ($uci_assume_full_compliance) {
131                                         $pos_waiting = $pos;
132                                 } else {
133                                         uciprint($engine, "position fen " . $pos->{'fen'});
134                                         uciprint($engine, "go infinite");
135                                         $pos_calculating = $pos;
136                                 }
137                         } else {
138                                 # it's wrong just to give the FEN (the move history is useful,
139                                 # and per the UCI spec, we should really have sent "ucinewgame"),
140                                 # but it's easier
141                                 uciprint($engine, "position fen " . $pos->{'fen'});
142                                 uciprint($engine, "go infinite");
143                                 $pos_calculating = $pos;
144                         }
145
146                         if (defined($pos_calculating_second_engine)) {
147                                 uciprint($engine2, "stop");
148                         } else {
149                                 uciprint($engine2, "position fen " . $pos->{'fen'});
150                                 uciprint($engine2, "go infinite");
151                                 $pos_calculating_second_engine = $pos;
152                         }
153
154                         $engine->{'info'} = {};
155                         $engine2->{'info'} = {};
156                         $last_move = time;
157
158                         # 
159                         # Output a command every move to note that we're
160                         # still paying attention -- this is a good tradeoff,
161                         # since if no move has happened in the last half
162                         # hour, the analysis/relay has most likely stopped
163                         # and we should stop hogging server resources.
164                         #
165                         $t->cmd("date");
166                 }
167                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
168                         my ($who, $msg) = ($1, $2);
169
170                         next if (grep { $_ eq $who } (@masters) == 0);
171         
172                         if ($msg =~ /^fics (.*?)$/) {
173                                 $t->cmd("tell $who Executing '$1' on FICS.");
174                                 $t->cmd($1);
175                         } elsif ($msg =~ /^uci (.*?)$/) {
176                                 $t->cmd("tell $who Sending '$1' to the engine.");
177                                 print { $engine->{'write'} } "$1\n";
178                         } else {
179                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
180                         }
181                 }
182                 #print "FICS: [$line]\n";
183                 $sleep = 0;
184         }
185         
186         # any fun on the UCI channel?
187         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
188                 my @lines = read_lines($engine);
189                 for my $line (@lines) {
190                         next if $line =~ /(upper|lower)bound/;
191                         handle_uci($engine, $line, 1);
192                 }
193                 $sleep = 0;
194
195                 output();
196         }
197         if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
198                 my @lines = read_lines($engine2);
199                 for my $line (@lines) {
200                         next if $line =~ /(upper|lower)bound/;
201                         handle_uci($engine2, $line, 0);
202                 }
203                 $sleep = 0;
204
205                 output();
206         }
207
208         sleep $sleep;
209 }
210
211 sub handle_uci {
212         my ($engine, $line, $primary) = @_;
213
214         chomp $line;
215         $line =~ tr/\r//d;
216         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
217         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
218         if ($line =~ /^info/) {
219                 my (@infos) = split / /, $line;
220                 shift @infos;
221
222                 parse_infos($engine, @infos);
223         }
224         if ($line =~ /^id/) {
225                 my (@ids) = split / /, $line;
226                 shift @ids;
227
228                 parse_ids($engine, @ids);
229         }
230         if ($line =~ /^bestmove/) {
231                 if ($primary) {
232                         return if (!$uci_assume_full_compliance);
233                         if (defined($pos_waiting)) {
234                                 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
235                                 uciprint($engine, "go infinite");
236
237                                 $pos_calculating = $pos_waiting;
238                                 $pos_waiting = undef;
239                         }
240                 } else {
241                         $engine2->{'info'} = {};
242                         my $pos = $pos_waiting // $pos_calculating;
243                         uciprint($engine2, "position fen " . $pos->{'fen'});
244                         uciprint($engine2, "go infinite");
245                         $pos_calculating_second_engine = $pos;
246                 }
247         }
248 }
249
250 sub parse_infos {
251         my ($engine, @x) = @_;
252         my $mpv = '';
253
254         my $info = $engine->{'info'};
255
256         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
257         for my $i (0..$#x - 1) {
258                 if ($x[$i] =~ 'multipv') {
259                         $mpv = $x[$i + 1];
260                         next;
261                 }
262         }
263
264         while (scalar @x > 0) {
265                 if ($x[0] =~ 'multipv') {
266                         # Dealt with above
267                         shift @x;
268                         shift @x;
269                         next;
270                 }
271                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
272                         my $key = shift @x;
273                         my $value = shift @x;
274                         $info->{$key} = $value;
275                         next;
276                 }
277                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
278                         my $key = shift @x;
279                         my $value = shift @x;
280                         $info->{$key . $mpv} = $value;
281                         next;
282                 }
283                 if ($x[0] eq 'score') {
284                         shift @x;
285
286                         delete $info->{'score_cp' . $mpv};
287                         delete $info->{'score_mate' . $mpv};
288
289                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
290                                 if ($x[0] eq 'cp') {
291                                         shift @x;
292                                         $info->{'score_cp' . $mpv} = shift @x;
293                                 } elsif ($x[0] eq 'mate') {
294                                         shift @x;
295                                         $info->{'score_mate' . $mpv} = shift @x;
296                                 } else {
297                                         shift @x;
298                                 }
299                         }
300                         next;
301                 }
302                 if ($x[0] eq 'pv') {
303                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
304                         last;
305                 }
306                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
307                         last;
308                 }
309
310                 #print "unknown info '$x[0]', trying to recover...\n";
311                 #shift @x;
312                 die "Unknown info '" . join(',', @x) . "'";
313
314         }
315 }
316
317 sub parse_ids {
318         my ($engine, @x) = @_;
319
320         while (scalar @x > 0) {
321                 if ($x[0] =~ /^(name|author)$/) {
322                         my $key = shift @x;
323                         my $value = join(' ', @x);
324                         $engine->{'id'}{$key} = $value;
325                         last;
326                 }
327
328                 # unknown
329                 shift @x;
330         }
331 }
332
333 sub style12_to_pos {
334         my $str = shift;
335         my %pos = ();
336         my (@x) = split / /, $str;
337         
338         $pos{'board'} = [ @x[1..8] ];
339         $pos{'toplay'} = $x[9];
340         $pos{'ep_file_num'} = $x[10];
341         $pos{'white_castle_k'} = $x[11];
342         $pos{'white_castle_q'} = $x[12];
343         $pos{'black_castle_k'} = $x[13];
344         $pos{'black_castle_q'} = $x[14];
345         $pos{'time_to_100move_rule'} = $x[15];
346         $pos{'move_num'} = $x[26];
347         if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
348                 $pos{'last_move_uci'} = $1 . $2;
349         } else {
350                 $pos{'last_move_uci'} = undef;
351         }
352         $pos{'last_move'} = $x[29];
353         $pos{'fen'} = make_fen(\%pos);
354
355         return \%pos;
356 }
357
358 sub make_fen {
359         my $pos = shift;
360
361         # the board itself
362         my (@board) = @{$pos->{'board'}};
363         for my $rank (0..7) {
364                 $board[$rank] =~ s/(-+)/length($1)/ge;
365         }
366         my $fen = join('/', @board);
367
368         # white/black to move
369         $fen .= " ";
370         $fen .= lc($pos->{'toplay'});
371
372         # castling
373         my $castling = "";
374         $castling .= "K" if ($pos->{'white_castle_k'} == 1);
375         $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
376         $castling .= "k" if ($pos->{'black_castle_k'} == 1);
377         $castling .= "q" if ($pos->{'black_castle_q'} == 1);
378         $castling = "-" if ($castling eq "");
379         # $castling = "-"; # chess960
380         $fen .= " ";
381         $fen .= $castling;
382
383         # en passant
384         my $ep = "-";
385         if ($pos->{'ep_file_num'} != -1) {
386                 my $col = $pos->{'ep_file_num'};
387                 my $nep = (qw(a b c d e f g h))[$col];
388
389                 if ($pos->{'toplay'} eq 'B') {
390                         $nep .= "3";
391                 } else {
392                         $nep .= "6";
393                 }
394
395                 #
396                 # Showing the en passant square when actually no capture can be made
397                 # seems to confuse at least Rybka. Thus, check if there's actually
398                 # a pawn of the opposite side that can do the en passant move, and if
399                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
400                 # "right" thing as per the standard, though.
401                 #
402                 if ($pos->{'toplay'} eq 'B') {
403                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
404                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
405                 } else {
406                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
407                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
408                 }
409         }
410         $fen .= " ";
411         $fen .= $ep;
412
413         # half-move clock
414         $fen .= " ";
415         $fen .= $pos->{'time_to_100move_rule'};
416
417         # full-move clock
418         $fen .= " ";
419         $fen .= $pos->{'move_num'};
420
421         return $fen;
422 }
423
424 sub make_move {
425         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
426         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
427         my $piece = substr($board->[$from_row], $from_col, 1);
428         my @nb = @$board;
429
430         if ($piece eq '-') {
431                 die "Invalid move $move";
432         }
433
434         # white short castling
435         if ($move eq 'e1g1' && $piece eq 'K') {
436                 # king
437                 substr($nb[7], 4, 1, '-');
438                 substr($nb[7], 6, 1, $piece);
439                 
440                 # rook
441                 substr($nb[7], 7, 1, '-');
442                 substr($nb[7], 5, 1, 'R');
443                                 
444                 return \@nb;
445         }
446
447         # white long castling
448         if ($move eq 'e1c1' && $piece eq 'K') {
449                 # king
450                 substr($nb[7], 4, 1, '-');
451                 substr($nb[7], 2, 1, $piece);
452                 
453                 # rook
454                 substr($nb[7], 0, 1, '-');
455                 substr($nb[7], 3, 1, 'R');
456                                 
457                 return \@nb;
458         }
459
460         # black short castling
461         if ($move eq 'e8g8' && $piece eq 'k') {
462                 # king
463                 substr($nb[0], 4, 1, '-');
464                 substr($nb[0], 6, 1, $piece);
465                 
466                 # rook
467                 substr($nb[0], 7, 1, '-');
468                 substr($nb[0], 5, 1, 'r');
469                                 
470                 return \@nb;
471         }
472
473         # black long castling
474         if ($move eq 'e8c8' && $piece eq 'k') {
475                 # king
476                 substr($nb[0], 4, 1, '-');
477                 substr($nb[0], 2, 1, $piece);
478                 
479                 # rook
480                 substr($nb[0], 0, 1, '-');
481                 substr($nb[0], 3, 1, 'r');
482                                 
483                 return \@nb;
484         }
485
486         # check if the from-piece is a pawn
487         if (lc($piece) eq 'p') {
488                 # attack?
489                 if ($from_col != $to_col) {
490                         # en passant?
491                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
492                                 if ($piece eq 'p') {
493                                         substr($nb[$to_row + 1], $to_col, 1, '-');
494                                 } else {
495                                         substr($nb[$to_row - 1], $to_col, 1, '-');
496                                 }
497                         }
498                 } else {
499                         if ($promo ne '') {
500                                 if ($piece eq 'p') {
501                                         $piece = $promo;
502                                 } else {
503                                         $piece = uc($promo);
504                                 }
505                         }
506                 }
507         }
508
509         # update the board
510         substr($nb[$from_row], $from_col, 1, '-');
511         substr($nb[$to_row], $to_col, 1, $piece);
512
513         return \@nb;
514 }
515
516 sub prettyprint_pv {
517         my ($board, @pvs) = @_;
518
519         if (scalar @pvs == 0 || !defined($pvs[0])) {
520                 return ();
521         }
522
523         my $pv = shift @pvs;
524         my $from_col = col_letter_to_num(substr($pv, 0, 1));
525         my $from_row = row_letter_to_num(substr($pv, 1, 1));
526         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
527         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
528         my $promo    = substr($pv, 4, 1);
529
530         my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
531         my $piece = substr($board->[$from_row], $from_col, 1);
532
533         if ($piece eq '-') {
534                 die "Invalid move $pv";
535         }
536
537         # white short castling
538         if ($pv eq 'e1g1' && $piece eq 'K') {
539                 return ('0-0', prettyprint_pv($nb, @pvs));
540         }
541
542         # white long castling
543         if ($pv eq 'e1c1' && $piece eq 'K') {
544                 return ('0-0-0', prettyprint_pv($nb, @pvs));
545         }
546
547         # black short castling
548         if ($pv eq 'e8g8' && $piece eq 'k') {
549                 return ('0-0', prettyprint_pv($nb, @pvs));
550         }
551
552         # black long castling
553         if ($pv eq 'e8c8' && $piece eq 'k') {
554                 return ('0-0-0', prettyprint_pv($nb, @pvs));
555         }
556
557         my $pretty;
558
559         # check if the from-piece is a pawn
560         if (lc($piece) eq 'p') {
561                 # attack?
562                 if ($from_col != $to_col) {
563                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
564                 } else {
565                         $pretty = substr($pv, 2, 2);
566
567                         if (length($pv) == 5) {
568                                 # promotion
569                                 $pretty .= "=";
570                                 $pretty .= uc(substr($pv, 4, 1));
571
572                                 if ($piece eq 'p') {
573                                         $piece = substr($pv, 4, 1);
574                                 } else {
575                                         $piece = uc(substr($pv, 4, 1));
576                                 }
577                         }
578                 }
579         } else {
580                 $pretty = uc($piece);
581
582                 # see how many of these pieces could go here, in all
583                 my $num_total = 0;
584                 for my $col (0..7) {
585                         for my $row (0..7) {
586                                 next unless (substr($board->[$row], $col, 1) eq $piece);
587                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
588                         }
589                 }
590
591                 # see how many of these pieces from the given row could go here
592                 my $num_row = 0;
593                 for my $col (0..7) {
594                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
595                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
596                 }
597                 
598                 # and same for columns
599                 my $num_col = 0;
600                 for my $row (0..7) {
601                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
602                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
603                 }
604                 
605                 # see if we need to disambiguate
606                 if ($num_total > 1) {
607                         if ($num_col == 1) {
608                                 $pretty .= substr($pv, 0, 1);
609                         } elsif ($num_row == 1) {
610                                 $pretty .= substr($pv, 1, 1);
611                         } else {
612                                 $pretty .= substr($pv, 0, 2);
613                         }
614                 }
615
616                 # attack?
617                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
618                         $pretty .= 'x';
619                 }
620
621                 $pretty .= substr($pv, 2, 2);
622         }
623
624         if (in_mate($nb)) {
625                 $pretty .= '#';
626         } elsif (in_check($nb) ne 'none') {
627                 $pretty .= '+';
628         }
629         return ($pretty, prettyprint_pv($nb, @pvs));
630 }
631
632 sub output {
633         #return;
634
635         return if (!defined($pos_calculating));
636
637         # Don't update too often.
638         my $age = Time::HiRes::tv_interval($latest_update);
639         if ($age < $update_max_interval) {
640                 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
641                 return;
642         }
643         
644         my $info = $engine->{'info'};
645         
646         #
647         # Some programs _always_ report MultiPV, even with only one PV.
648         # In this case, we simply use that data as if MultiPV was never
649         # specified.
650         #
651         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
652                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
653                         if (exists($info->{$key . '1'})) {
654                                 $info->{$key} = $info->{$key . '1'};
655                         }
656                 }
657         }
658         
659         #
660         # Check the PVs first. if they're invalid, just wait, as our data
661         # is most likely out of sync. This isn't a very good solution, as
662         # it can frequently miss stuff, but it's good enough for most users.
663         #
664         eval {
665                 my $dummy;
666                 if (exists($info->{'pv'})) {
667                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
668                 }
669         
670                 my $mpv = 1;
671                 while (exists($info->{'pv' . $mpv})) {
672                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
673                         ++$mpv;
674                 }
675         };
676         if ($@) {
677                 $engine->{'info'} = {};
678                 return;
679         }
680
681         output_screen();
682         output_json();
683         $latest_update = [Time::HiRes::gettimeofday];
684 }
685
686 sub output_screen {
687         my $info = $engine->{'info'};
688         my $id = $engine->{'id'};
689
690         my $text = 'Analysis';
691         if ($pos_calculating->{'last_move'} ne 'none') {
692                 if ($pos_calculating->{'toplay'} eq 'W') {
693                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
694                 } else {
695                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
696                 }
697                 if (exists($id->{'name'})) {
698                         $text .= ',';
699                 }
700         }
701
702         if (exists($id->{'name'})) {
703                 $text .= " by $id->{'name'}:\n\n";
704         } else {
705                 $text .= ":\n\n";
706         }
707
708         return unless (exists($pos_calculating->{'board'}));
709                 
710         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
711                 # multi-PV
712                 my $mpv = 1;
713                 while (exists($info->{'pv' . $mpv})) {
714                         $text .= sprintf "  PV%2u", $mpv;
715                         my $score = short_score($info, $pos_calculating, $mpv);
716                         $text .= "  ($score)" if (defined($score));
717
718                         my $tbhits = '';
719                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
720                                 if ($info->{'tbhits' . $mpv} == 1) {
721                                         $tbhits = ", 1 tbhit";
722                                 } else {
723                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
724                                 }
725                         }
726
727                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
728                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
729                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
730                         }
731
732                         $text .= ":\n";
733                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
734                         $text .= "\n";
735                         ++$mpv;
736                 }
737         } else {
738                 # single-PV
739                 my $score = long_score($info, $pos_calculating, '');
740                 $text .= "  $score\n" if defined($score);
741                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
742                 $text .=  "\n";
743
744                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
745                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
746                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
747                 }
748                 if (exists($info->{'seldepth'})) {
749                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
750                 }
751                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
752                         if ($info->{'tbhits'} == 1) {
753                                 $text .= ", one Nalimov hit";
754                         } else {
755                                 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
756                         }
757                 }
758                 $text .= "\n\n";
759         }
760
761         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
762
763         my @refutation_lines = ();
764         for (my $mpv = 1; $mpv < 500; ++$mpv) {
765                 my $info = $engine2->{'info'};
766                 last if (!exists($info->{'pv' . $mpv}));
767                 eval {
768                         my $pv = $info->{'pv' . $mpv};
769
770                         my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
771                         my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
772                         if (scalar @pretty_pv > 5) {
773                                 @pretty_pv = @pretty_pv[0..4];
774                                 push @pretty_pv, "...";
775                         }
776                         my $key = $pretty_move;
777                         my $line = sprintf("  %-6s %6s %3s  %s",
778                                 $pretty_move,
779                                 short_score($info, $pos_calculating_second_engine, $mpv, 0),
780                                 "d" . $info->{'depth' . $mpv},
781                                 join(', ', @pretty_pv));
782                         push @refutation_lines, [ $key, $line ];
783                 };
784         }
785
786         if ($#refutation_lines >= 0) {
787                 $text .= "Shallow search of all legal moves:\n\n";
788                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
789                         $text .= $line->[1] . "\n";
790                 }
791                 $text .= "\n\n";        
792         }       
793
794         if ($last_text ne $text) {
795                 print "\e[H\e[2J"; # clear the screen
796                 print $text;
797                 $last_text = $text;
798         }
799
800         # Now construct the tell text, if any
801         return if (!defined($telltarget));
802
803         my $tell_text = '';
804
805         if (exists($id->{'name'})) {
806                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
807         } else {
808                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
809         }
810
811         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
812                 # multi-PV
813                 my $mpv = 1;
814                 while (exists($info->{'pv' . $mpv})) {
815                         $tell_text .= sprintf "  PV%2u", $mpv;
816                         my $score = short_score($info, $pos_calculating, $mpv);
817                         $tell_text .= "  ($score)" if (defined($score));
818
819                         if (exists($info->{'depth' . $mpv})) {
820                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
821                         }
822
823                         $tell_text .= ": ";
824                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
825                         $tell_text .= "\n";
826                         ++$mpv;
827                 }
828         } else {
829                 # single-PV
830                 my $score = long_score($info, $pos_calculating, '');
831                 $tell_text .= "  $score\n" if defined($score);
832                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
833                 if (exists($info->{'depth'})) {
834                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
835                 }
836                 $tell_text .=  "\n";
837         }
838
839         # see if a new tell is called for -- it is if the delay has expired _and_
840         # this is not simply a repetition of the last one
841         if ($last_told_text ne $tell_text) {
842                 my $now = time;
843                 for my $iv (@tell_intervals) {
844                         last if ($now - $last_move < $iv);
845                         next if ($last_tell - $last_move >= $iv);
846
847                         for my $line (split /\n/, $tell_text) {
848                                 $t->print("tell $telltarget [$target] $line");
849                         }
850
851                         $last_told_text = $text;
852                         $last_tell = $now;
853
854                         last;
855                 }
856         }
857 }
858
859 sub output_json {
860         my $info = $engine->{'info'};
861
862         my $json = {};
863         $json->{'position'} = $pos_calculating;
864         $json->{'id'} = $engine->{'id'};
865         $json->{'score'} = long_score($info, $pos_calculating, '');
866
867         $json->{'nodes'} = $info->{'nodes'};
868         $json->{'nps'} = $info->{'nps'};
869         $json->{'depth'} = $info->{'depth'};
870         $json->{'tbhits'} = $info->{'tbhits'};
871         $json->{'seldepth'} = $info->{'seldepth'};
872
873         # single-PV only for now
874         $json->{'pv_uci'} = $info->{'pv'};
875         $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
876
877         my %refutation_lines = ();
878         my @refutation_lines = ();
879         for (my $mpv = 1; $mpv < 500; ++$mpv) {
880                 my $info = $engine2->{'info'};
881                 my $pretty_move = "";
882                 my @pretty_pv = ();
883                 last if (!exists($info->{'pv' . $mpv}));
884
885                 eval {
886                         my $pv = $info->{'pv' . $mpv};
887                         my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
888                         my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
889                         $refutation_lines{$pv->[0]} = {
890                                 sort_key => $pretty_move,
891                                 depth => $info->{'depth' . $mpv},
892                                 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
893                                 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
894                                 pretty_move => $pretty_move,
895                                 pv_pretty => \@pretty_pv,
896                         };
897                         $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
898                 };
899         }
900         $json->{'refutation_lines'} = \%refutation_lines;
901
902         open my $fh, ">analysis.json.tmp"
903                 or return;
904         print $fh JSON::XS::encode_json($json);
905         close $fh;
906         rename("analysis.json.tmp", "analysis.json");   
907 }
908
909 sub find_kings {
910         my $board = shift;
911         my ($wkr, $wkc, $bkr, $bkc);
912
913         for my $row (0..7) {
914                 for my $col (0..7) {
915                         my $piece = substr($board->[$row], $col, 1);
916                         if ($piece eq 'K') {
917                                 ($wkr, $wkc) = ($row, $col);
918                         } elsif ($piece eq 'k') {
919                                 ($bkr, $bkc) = ($row, $col);
920                         }
921                 }
922         }
923
924         return ($wkr, $wkc, $bkr, $bkc);
925 }
926
927 sub in_mate {
928         my $board = shift;
929         my $check = in_check($board);
930         return 0 if ($check eq 'none');
931
932         # try all possible moves for the side in check
933         for my $row (0..7) {
934                 for my $col (0..7) {
935                         my $piece = substr($board->[$row], $col, 1);
936                         next if ($piece eq '-');
937
938                         if ($check eq 'white') {
939                                 next if ($piece eq lc($piece));
940                         } else {
941                                 next if ($piece eq uc($piece));
942                         }
943
944                         for my $dest_row (0..7) {
945                                 for my $dest_col (0..7) {
946                                         next if ($row == $dest_row && $col == $dest_col);
947                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
948
949                                         my @nb = @$board;
950                                         substr($nb[$row], $col, 1, '-');
951                                         substr($nb[$dest_row], $dest_col, 1, $piece);
952
953                                         my $new_check = in_check(\@nb);
954                                         return 0 if ($new_check ne $check && $new_check ne 'both');
955                                 }
956                         }
957                 }
958         }
959
960         # nothing to do; mate
961         return 1;
962 }
963
964 sub in_check {
965         my $board = shift;
966         my ($black_check, $white_check) = (0, 0);
967
968         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
969
970         # check all pieces for the possibility of threatening the two kings
971         for my $row (0..7) {
972                 for my $col (0..7) {
973                         my $piece = substr($board->[$row], $col, 1);
974                         next if ($piece eq '-');
975                 
976                         if (uc($piece) eq $piece) {
977                                 # white piece
978                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
979                         } else {
980                                 # black piece
981                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
982                         }
983                 }
984         }
985
986         if ($black_check && $white_check) {
987                 return 'both';
988         } elsif ($black_check) {
989                 return 'black';
990         } elsif ($white_check) {
991                 return 'white';
992         } else {
993                 return 'none';
994         }
995 }
996
997 sub can_reach {
998         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
999         
1000         # can't eat your own piece
1001         my $dest_piece = substr($board->[$to_row], $to_col, 1);
1002         if ($dest_piece ne '-') {
1003                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
1004         }
1005
1006         if (lc($piece) eq 'k') {
1007                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
1008         }
1009         if (lc($piece) eq 'r') {
1010                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
1011
1012                 # check that there's a clear passage
1013                 if ($from_row == $to_row) {
1014                         if ($from_col > $to_col) {
1015                                 ($to_col, $from_col) = ($from_col, $to_col);
1016                         }
1017
1018                         for my $c (($from_col+1)..($to_col-1)) {
1019                                 my $middle_piece = substr($board->[$to_row], $c, 1);
1020                                 return 0 if ($middle_piece ne '-');     
1021                         }
1022
1023                         return 1;
1024                 } else {
1025                         if ($from_row > $to_row) {
1026                                 ($to_row, $from_row) = ($from_row, $to_row);
1027                         }
1028
1029                         for my $r (($from_row+1)..($to_row-1)) {
1030                                 my $middle_piece = substr($board->[$r], $to_col, 1);
1031                                 return 0 if ($middle_piece ne '-');     
1032                         }
1033
1034                         return 1;
1035                 }
1036         }
1037         if (lc($piece) eq 'b') {
1038                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
1039
1040                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
1041                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
1042
1043                 my $r = $from_row + $dr;
1044                 my $c = $from_col + $dc;
1045
1046                 while ($r != $to_row) {
1047                         my $middle_piece = substr($board->[$r], $c, 1);
1048                         return 0 if ($middle_piece ne '-');
1049                         
1050                         $r += $dr;
1051                         $c += $dc;
1052                 }
1053
1054                 return 1;
1055         }
1056         if (lc($piece) eq 'n') {
1057                 my $diff_r = abs($from_row - $to_row);
1058                 my $diff_c = abs($from_col - $to_col);
1059                 return 1 if ($diff_r == 2 && $diff_c == 1);
1060                 return 1 if ($diff_r == 1 && $diff_c == 2);
1061                 return 0;
1062         }
1063         if ($piece eq 'q') {
1064                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
1065                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
1066         }
1067         if ($piece eq 'Q') {
1068                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
1069                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
1070         }
1071
1072         # TODO: en passant
1073         if ($piece eq 'p') {
1074                 # black pawn
1075                 if ($to_col == $from_col && $to_row == $from_row + 1) {
1076                         return ($dest_piece eq '-');
1077                 }
1078                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
1079                         my $middle_piece = substr($board->[2], $to_col, 1);
1080                         return ($dest_piece eq '-' && $middle_piece eq '-');
1081                 }
1082                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1083                         return ($dest_piece ne '-');
1084                 }
1085                 return 0;
1086         }
1087         if ($piece eq 'P') {
1088                 # white pawn
1089                 if ($to_col == $from_col && $to_row == $from_row - 1) {
1090                         return ($dest_piece eq '-');
1091                 }
1092                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1093                         my $middle_piece = substr($board->[5], $to_col, 1);
1094                         return ($dest_piece eq '-' && $middle_piece eq '-');
1095                 }
1096                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1097                         return ($dest_piece ne '-');
1098                 }
1099                 return 0;
1100         }
1101         
1102         # unknown piece
1103         return 0;
1104 }
1105
1106 sub uciprint {
1107         my ($engine, $msg) = @_;
1108         print { $engine->{'write'} } "$msg\n";
1109         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1110 }
1111
1112 sub short_score {
1113         my ($info, $pos, $mpv, $invert) = @_;
1114
1115         $invert //= 0;
1116         if ($pos->{'toplay'} eq 'B') {
1117                 $invert = !$invert;
1118         }
1119
1120         if (defined($info->{'score_mate' . $mpv})) {
1121                 if ($invert) {
1122                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1123                 } else {
1124                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1125                 }
1126         } else {
1127                 if (exists($info->{'score_cp' . $mpv})) {
1128                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1129                         if ($score == 0) {
1130                                 return " 0.00";
1131                         }
1132                         if ($invert) {
1133                                 $score = -$score;
1134                         }
1135                         return sprintf "%+5.2f", $score;
1136                 }
1137         }
1138
1139         return undef;
1140 }
1141
1142 sub score_sort_key {
1143         my ($info, $pos, $mpv, $invert) = @_;
1144
1145         if (defined($info->{'score_mate' . $mpv})) {
1146                 if ($invert) {
1147                         return 99999 - $info->{'score_mate' . $mpv};
1148                 } else {
1149                         return -(99999 - $info->{'score_mate' . $mpv});
1150                 }
1151         } else {
1152                 if (exists($info->{'score_cp' . $mpv})) {
1153                         my $score = $info->{'score_cp' . $mpv};
1154                         if ($invert) {
1155                                 $score = -$score;
1156                         }
1157                         return $score;
1158                 }
1159         }
1160
1161         return undef;
1162 }
1163
1164 sub long_score {
1165         my ($info, $pos, $mpv) = @_;
1166
1167         if (defined($info->{'score_mate' . $mpv})) {
1168                 my $mate = $info->{'score_mate' . $mpv};
1169                 if ($pos->{'toplay'} eq 'B') {
1170                         $mate = -$mate;
1171                 }
1172                 if ($mate > 0) {
1173                         return sprintf "White mates in %u", $mate;
1174                 } else {
1175                         return sprintf "Black mates in %u", -$mate;
1176                 }
1177         } else {
1178                 if (exists($info->{'score_cp' . $mpv})) {
1179                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1180                         if ($pos->{'toplay'} eq 'B') {
1181                                 $score = -$score;
1182                         }
1183                         return sprintf "Score: %+5.2f", $score;
1184                 }
1185         }
1186
1187         return undef;
1188 }
1189
1190 my %book_cache = ();
1191 sub book_info {
1192         my ($fen, $board, $toplay) = @_;
1193
1194         if (exists($book_cache{$fen})) {
1195                 return $book_cache{$fen};
1196         }
1197
1198         my $ret = `./booklook $fen`;
1199         return "" if ($ret =~ /Not found/ || $ret eq '');
1200
1201         my @moves = ();
1202
1203         for my $m (split /\n/, $ret) {
1204                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1205
1206                 my $pmove;
1207                 if ($move eq '')  {
1208                         $pmove = '(current)';
1209                 } else {
1210                         ($pmove) = prettyprint_pv($board, $move);
1211                         $pmove .= $annotation;
1212                 }
1213
1214                 my $score;
1215                 if ($toplay eq 'W') {
1216                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1217                 } else {
1218                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1219                 }
1220                 my $n = $win + $draw + $lose;
1221                 
1222                 my $percent;
1223                 if ($n == 0) {
1224                         $percent = "     ";
1225                 } else {
1226                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1227                 }
1228
1229                 push @moves, [ $pmove, $n, $percent, $rating ];
1230         }
1231
1232         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1233         
1234         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1235         for my $m (@moves) {
1236                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1237         }
1238
1239         return $text;
1240 }
1241
1242 sub open_engine {
1243         my ($cmdline, $tag) = @_;
1244         my ($uciread, $uciwrite);
1245         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1246
1247         my $engine = {
1248                 pid => $pid,
1249                 read => $uciread,
1250                 readbuf => '',
1251                 write => $uciwrite,
1252                 info => {},
1253                 ids => {},
1254                 tag => $tag,
1255         };
1256
1257         uciprint($engine, "uci");
1258
1259         # gobble the options
1260         while (<$uciread>) {
1261                 /uciok/ && last;
1262                 handle_uci($engine, $_);
1263         }
1264         
1265         return $engine;
1266 }
1267
1268 sub read_lines {
1269         my $engine = shift;
1270
1271         # 
1272         # Read until we've got a full line -- if the engine sends part of
1273         # a line and then stops we're pretty much hosed, but that should
1274         # never happen.
1275         #
1276         while ($engine->{'readbuf'} !~ /\n/) {
1277                 my $tmp;
1278                 my $ret = sysread $engine->{'read'}, $tmp, 4096;
1279
1280                 if (!defined($ret)) {
1281                         next if ($!{EINTR});
1282                         die "error in reading from the UCI engine: $!";
1283                 } elsif ($ret == 0) {
1284                         die "EOF from UCI engine";
1285                 }
1286
1287                 $engine->{'readbuf'} .= $tmp;
1288         }
1289
1290         # Blah.
1291         my @lines = ();
1292         while ($engine->{'readbuf'} =~ s/^([^\n]*)\n//) {
1293                 my $line = $1;
1294                 $line =~ tr/\r\n//d;
1295                 push @lines, $line;
1296         }
1297         return @lines;
1298 }
1299
1300 sub col_letter_to_num {
1301         return ord(shift) - ord('a');
1302 }
1303
1304 sub row_letter_to_num {
1305         return 7 - (ord(shift) - ord('1'));
1306 }
1307
1308 sub move_to_uci_notation {
1309         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1310         $promo //= "";
1311         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1312 }