Relay fail-lo/fail-high info
[polyglot.git] / xboard2uci.c
1
2 // xboard2uci.c
3
4 // includes
5
6 #include <errno.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <time.h>
11
12 #include "board.h"
13 #include "book.h"
14 #include "colour.h"
15 #include "engine.h"
16 #include "fen.h"
17 #include "game.h"
18 #include "gui.h"
19 #include "line.h"
20 #include "main.h"
21 #include "move.h"
22 #include "move_do.h"
23 #include "move_legal.h"
24 #include "move_gen.h"
25 #include "option.h"
26 #include "parse.h"
27 #include "san.h"
28 #include "uci.h"
29 #include "uci2uci.h"
30 #include "util.h"
31 #include "xboard2uci.h"
32
33 // defines
34
35 #define StringSize 4096
36
37 // constants
38
39 static const bool UseDebug = FALSE;
40 static const bool DelayPong = FALSE;
41
42 // types
43
44 typedef struct {
45    int state;
46    bool computer[ColourNb];
47    bool playedAllMoves[ColourNb];
48    int exp_move;
49    int hint_move;
50    int resign_nb;
51    my_timer_t timer[1];
52 } state_t;
53
54 typedef struct {
55     bool has_feature_memory;
56     bool has_feature_smp;
57     bool has_feature_egt_nalimov;
58     bool has_feature_egt_gaviota;
59     bool has_feature_egt_syzygy;
60     bool analyse;
61     bool computer;
62     const char * name;
63     bool ics;
64     bool new_hack; // "new" is a C++ keyword
65     bool ponder;
66     int ping;
67     bool post;
68     int proto_ver;
69     bool result;
70
71     int mps;
72     double base;
73     double inc;
74     
75     bool time_limit;
76     double time_max;
77     
78     bool depth_limit;
79     int depth_max;
80     
81     double my_time;
82     double opp_time;
83
84     int node_rate;
85 } xb_t;
86
87 typedef enum { WAIT, THINK, PONDER, ANALYSE } dummy_state_t;
88
89 // variables
90
91 static state_t State[1];
92 static xb_t XB[1];
93
94 // prototypes
95
96 static void comp_move      (int move);
97 static void move_step      (int move);
98 static void board_update   ();
99
100 static void mess           ();
101 static void no_mess        (int move);
102
103 static void search_update  ();
104 static void search_clear   ();
105 static void update_remaining_time();
106 static int  report_best_score();
107 static bool kibitz_throttle (bool searching);
108 static void start_protected_command();
109 static void end_protected_command();
110
111 static bool active         ();
112 static bool ponder         ();
113 static bool ponder_ok      (int ponder_move);
114
115 static void stop_search    ();
116
117 static void send_board     (int extra_move);
118 static void send_pv        ();
119 static void send_info      ();
120
121 static void send_xboard_options ();
122
123 static void learn          (int result);
124
125
126 // functions
127
128 // xboard2uci_init()
129
130 void xboard2uci_init() {
131    // init
132
133    game_clear(Game);
134
135    // state
136
137    State->state = WAIT;
138
139    State->computer[White] = FALSE;
140    State->computer[Black] = TRUE;
141
142    State->exp_move = MoveNone;
143    State->hint_move = MoveNone;
144    State->resign_nb = 0;
145    my_timer_reset(State->timer);
146
147    // yes there are engines that do not have the "Hash" option....
148    XB->has_feature_memory= (option_find(Uci->option,"Hash")!=NULL);
149    XB->has_feature_smp = (uci_thread_option(Uci)!=NULL);
150    // TODO: support for other types of table bases
151    // This is a quick hack. 
152    XB->has_feature_egt_nalimov = (option_find(Uci->option,"NalimovPath")!=NULL);
153    XB->has_feature_egt_gaviota = (option_find(Uci->option,"GaviotaTbPath")!=NULL);
154    XB->has_feature_egt_syzygy  = (option_find(Uci->option,"SyzygyPath")!=NULL);
155    XB->analyse = FALSE;
156    XB->computer = FALSE;
157    XB->name = NULL;
158    my_string_set(&XB->name,"<empty>");
159    XB->ics = FALSE;
160    XB->new_hack = TRUE;
161    XB->ping = -1;
162    XB->ponder = FALSE;
163    XB->post = FALSE;
164    XB->proto_ver = 1;
165    XB->result = FALSE;
166
167    XB->mps = 0;
168    XB->base = 300.0;
169    XB->inc = 0.0;
170
171    XB->time_limit = FALSE;
172    XB->time_max = 5.0;
173
174    XB->depth_limit = FALSE;
175    XB->depth_max = 127;
176
177    XB->my_time = 300.0;
178    XB->opp_time = 300.0;
179
180    XB->node_rate = -1;
181 }
182
183
184 static list_t move_list[1];
185
186 // xboard2uci_gui_step()
187
188 void xboard2uci_gui_step(char string[]) {
189
190         int move;
191         char move_string[256];
192         board_t board[1];
193
194                 if (FALSE) {
195          
196                 } else if (match(string,"accepted *")) {
197
198                         // ignore
199
200                 } else if (match(string,"analyze")) {
201
202                         State->computer[White] = FALSE;
203                         State->computer[Black] = FALSE;
204
205                         XB->analyse = TRUE;
206                         XB->new_hack = FALSE;
207                         ASSERT(!XB->result);
208                         XB->result = FALSE;
209
210                         mess();
211
212                 } else if (match(string,"bk")) {
213
214                         if (option_get_bool(Option,"Book")) {
215                                 game_get_board(Game,board);
216                                 book_disp(board);
217                         } else { // [HGM] without book, print all legal moves
218                                 int i, gen=!list_size(move_list);
219                                 game_get_board(Game,board);
220                                 if(gen) gen_legal_moves(move_list,board);
221                                 for(i=0; i<list_size(move_list); i++){
222                                         if(gen) move_list->value[i] = 0;
223                                         move_to_san(move_list->move[i],board,move_string,256);
224                                         printf(" %s%6s\n", move_list->value[i]? "* " : "", move_string);
225                                 }
226                                 // this is necessary by the xboard protocol
227                                 printf("\n");
228                         }
229
230                 } else if (match(string,"exclude *") || match(string,"option Polyglot exclude move=*")) { // [HGM] 
231
232                                 int i, all = !strcmp(Star[0], "all"), change=FALSE, cnt=0;
233                                 game_get_board(Game,board);
234                                 if(!list_size(move_list)) {
235                                         gen_legal_moves(move_list,board);
236                                         for(i=0; i<list_size(move_list); i++){
237                                                 move_list->value[i] = 0;
238                                         }
239                                 }
240                                 move = move_from_san(Star[0],board);
241
242                                 for(i=0; i<list_size(move_list); i++){
243                                         if(all || move_list->move[i] == move)
244                                                 change |= !move_list->value[i], move_list->value[i] = 1;
245                                         cnt += !move_list->value[i];
246                                 }
247                                 if(change && cnt) mess(); // do not relay to engine if no change or no moves left
248
249                 } else if (match(string,"include *")) { // [HGM] 
250
251                         int i, all = !strcmp(Star[0], "all"), change = FALSE;
252                         game_get_board(Game,board);
253                         move = move_from_san(Star[0],board);
254
255                         for(i=0; i<list_size(move_list); i++){
256                                 if(all || move_list->move[i] == move)
257                                         change |= move_list->value[i], move_list->value[i] = 0;
258                         }
259                         if(change) mess();
260
261                 } else if (match(string,"black")) {
262
263                         if (colour_is_black(game_turn(Game))) {
264
265                                 State->computer[White] = TRUE;
266                                 State->computer[Black] = FALSE;
267
268                                 XB->new_hack = TRUE;
269                                 XB->result = FALSE;
270
271                                 mess();
272                         }
273
274                 } else if (match(string,"computer")) {
275
276                         XB->computer = TRUE;
277
278                 } else if (match(string,"draw")) {
279                         if(option_find(Uci->option,"UCI_DrawOffers")){
280                             my_log("POLYGLOT draw from XB received");
281                                 uci_send_option(Uci,"DrawOffer","%s","draw");}
282                         else if (option_get_bool(Option,"HandleDraws") && Uci->root_move_nb > 20) { // [HGM] PG draw handling
283                             my_log("POLYGLOT draw from XB received");
284                             if (Uci->best_score <= -option_get_int(Option,"ContemptScore")) 
285                                 gui_send(GUI,"offer draw");}
286                 } else if (match(string,"easy")) {
287
288                         XB->ponder = FALSE;
289
290                         mess();
291
292                 } else if (match(string,"edit")) {
293
294                         // refuse
295
296                         gui_send(GUI,"Error (unknown command): %s",string);
297
298                 } else if (match(string,"exit")) {
299
300                         State->computer[White] = FALSE;
301                         State->computer[Black] = FALSE;
302
303                         XB->analyse = FALSE;
304
305                         mess();
306
307                 } else if (match(string,"force")) {
308
309                         State->computer[White] = FALSE;
310                         State->computer[Black] = FALSE;
311
312                         mess();
313
314                 } else if (match(string,"go")) {
315
316                         State->computer[game_turn(Game)] = TRUE;
317                         State->computer[colour_opp(game_turn(Game))] = FALSE;
318
319                         XB->new_hack = FALSE;
320                         ASSERT(!XB->result);
321                         XB->result = FALSE;
322
323                         mess();
324
325                 } else if (match(string,"hard")) {
326
327                         XB->ponder = TRUE;
328
329                         mess();
330
331                 } else if (match(string,"hint")) {
332                     
333                         move=MoveNone;
334                         game_get_board(Game,board);
335                         if (option_get_bool(Option,"Book")) {
336
337                                 move = book_move(board,FALSE);
338                         }
339                         if(move==MoveNone && State->hint_move!=MoveNone){
340                             move=State->hint_move;
341                             
342                         }
343                         if (move != MoveNone && move_is_legal(move,board)) {
344                             move_to_san(move,board,move_string,256);
345                             gui_send(GUI,"Hint: %s",move_string);
346                         }
347
348                 } else if (match(string,"ics *")) {
349
350                         XB->ics = TRUE;
351
352                 } else if (match(string,"level * *:* *")) {
353
354                         XB->mps  = atoi(Star[0]);
355                         XB->base = ((double)atoi(Star[1])) * 60.0 + ((double)atoi(Star[2]));
356                         XB->inc  = ((double)atoi(Star[3]));
357
358                 } else if (match(string,"level * * *")) {
359
360                         XB->mps  = atoi(Star[0]);
361                         XB->base = ((double)atoi(Star[1])) * 60.0;
362                         XB->inc  = ((double)atoi(Star[2]));
363
364                 } else if (match(string,"name *")) {
365
366                         my_string_set(&XB->name,Star[0]);
367
368                 } else if (match(string,"new")) {
369
370                     uci_send_isready_sync(Uci);
371                         my_log("POLYGLOT NEW GAME\n");
372
373                         option_set(Option,"Chess960","false");
374
375                         game_clear(Game);
376
377                         move_list->size = 0; // [HGM] clear all exclude moves
378
379                         if (XB->analyse) {
380                                 State->computer[White] = FALSE;
381                                 State->computer[Black] = FALSE;
382                         } else {
383                                 State->computer[White] = FALSE;
384                                 State->computer[Black] = TRUE;
385                                 State->playedAllMoves[White] = TRUE; // [HGM]
386                                 State->playedAllMoves[Black] = TRUE;
387                         }
388
389                         XB->new_hack = TRUE;
390                         XB->result = FALSE;
391
392                         XB->depth_limit = FALSE;
393             XB->node_rate=-1;
394
395                         XB->computer = FALSE;
396                         my_string_set(&XB->name,"<empty>");
397
398                         board_update();
399                         mess();
400
401                         uci_send_ucinewgame(Uci);
402
403                 } else if (match(string,"nopost")) {
404
405                         XB->post = FALSE;
406
407                 } else if (match(string,"otim *")) {
408
409                         XB->opp_time = ((double)atoi(Star[0])) / 100.0;
410                         if (XB->opp_time < 0.0) XB->opp_time = 0.0;
411
412                 } else if (match(string,"pause")) {
413
414                         // refuse
415
416                         gui_send(GUI,"Error (unknown command): %s",string);
417
418                 } else if (match(string,"ping *")) {
419
420                         // HACK; TODO: answer only after an engine move
421
422                         if (DelayPong) {
423                                 if (XB->ping >= 0) gui_send(GUI,"pong %d",XB->ping); // HACK: get rid of old ping
424                                 XB->ping = atoi(Star[0]);
425                                 uci_send_isready_sync(Uci);
426                         } else {
427                                 ASSERT(XB->ping==-1);
428                                 gui_send(GUI,"pong %s",Star[0]);
429                         }
430         } else if (match(string,"nps *")) {
431             
432                 // fake WB play-by-nodes mode
433             XB->node_rate = atoi(Star[0]);
434                 } else if (match(string,"playother")) {
435
436                         State->computer[game_turn(Game)] = FALSE;
437                         State->computer[colour_opp(game_turn(Game))] = TRUE;
438
439                         XB->new_hack = FALSE;
440                         ASSERT(!XB->result);
441                         XB->result = FALSE;
442
443                         mess();
444
445                 } else if (match(string,"post")) {
446
447                         XB->post = TRUE;
448
449                 } else if (match(string,"protover *")) {
450             XB->proto_ver = atoi(Star[0]);
451             ASSERT(XB->proto_ver>=2);
452             send_xboard_options();
453
454                 } else if (match(string,"quit")) {
455                         my_log("POLYGLOT *** \"quit\" from GUI ***\n");
456                         quit();
457                 } else if (match(string,"random")) {
458
459                         // ignore
460
461                 } else if (match(string,"rating * *")) {
462
463                         // ignore
464
465                 } else if (match(string,"remove")) {
466
467                         if (game_pos(Game) >= 2) {
468
469                                 game_goto(Game,game_pos(Game)-2);
470
471                                 ASSERT(!XB->new_hack);
472                                 XB->new_hack = FALSE; // HACK?
473                                 XB->result = FALSE;
474
475                                 board_update();
476                                 mess();
477                         }
478
479                 } else if (match(string,"rejected *")) {
480
481                         // ignore
482
483                 } else if (match(string,"reset")) { // protover 3?
484
485                         // refuse
486
487                         gui_send(GUI,"Error (unknown command): %s",string);
488
489                 } else if (FALSE
490                         || match(string,"result * {*}")
491                         || match(string,"result * {* }")
492                         || match(string,"result * { *}")
493                         || match(string,"result * { * }")) {
494
495                                 my_log("POLYGLOT GAME END\n");
496
497                                 XB->result = TRUE;
498
499                                 mess();
500
501                                 // book learning
502
503                                 if (option_get_bool(Option,"Book") &&
504                     option_get_bool(Option,"BookLearn")) {
505
506                                         if (FALSE) {
507                                         } else if (my_string_equal(Star[0],"1-0")) {
508                                                 learn(+1);
509                                         } else if (my_string_equal(Star[0],"0-1")) {
510                                                 learn(-1);
511                                         } else if (my_string_equal(Star[0],"1/2-1/2")) {
512                                                 learn(0);
513                                         }
514                                 }
515                 } else if (match(string,"resume")) {
516
517                         // refuse
518
519                         gui_send(GUI,"Error (unknown command): %s",string);
520
521         } else if (match(string,"option *=*")   ||
522                    match(string,"option * =*") ||
523                    match(string,"option *= *") ||
524                    match(string,"option * = *")
525                    ){
526             char *name=Star[0];
527             char *value=Star[1];
528             if(match(name, "Polyglot *")){
529                 char *pg_name=Star[0];
530                 polyglot_set_option(pg_name,value);
531             }else{
532                 option_t *opt=option_find(Uci->option,name);
533                 if(opt){
534                     if(my_string_case_equal(opt->type,"check")){
535                        value=my_string_equal(value,"1")?"true":"false";
536                     }
537                     start_protected_command();
538                     uci_send_option(Uci, name, "%s", value);
539                     end_protected_command();
540                 }else{
541                     gui_send(GUI,"Error (unknown option): %s",name); 
542                 }
543             }
544         } else if (match(string,"option *")){
545             char *name=Star[0];
546              if(match(name, "Polyglot *")){
547                 char *pg_name=Star[0];
548                 polyglot_set_option(pg_name,"<empty>");
549              }else{           
550                start_protected_command();
551                 // value is ignored
552                if(!uci_send_option(Uci, name, "%s", "<empty>")){
553                  gui_send(GUI,"Error (unknown option): %s",name); 
554                }; 
555                end_protected_command();
556              }
557         } else if (XB->has_feature_smp && match(string,"cores *")){
558                 int cores=atoi(Star[0]);
559                 if(cores>=1){
560                     // updating the number of cores
561                     my_log("POLYGLOT setting the number of cores to %d\n",cores);
562                     start_protected_command();
563                     uci_set_threads(Uci,cores); 
564                     end_protected_command();
565                 } else{
566                    // refuse
567                     gui_send(GUI,"Error (unknown command): %s",string);
568                 }
569         } else if (match(string,"egtpath * *")){
570                 char *type=Star[0];
571                 char *path=Star[1];
572                 if(my_string_empty(path)){
573                     // refuse
574                     gui_send(GUI,"Error (unknown command): %s",string);
575                 }else{
576                     if(my_string_case_equal(type,"nalimov") && XB->has_feature_egt_nalimov){
577                         // updating NalimovPath
578                         my_log("POLYGLOT setting the Nalimov path to %s\n",path);
579                         start_protected_command();
580                         uci_send_option(Uci,"NalimovPath","%s",path);
581                         end_protected_command();
582                     }else if(my_string_case_equal(type,"gaviota") && XB->has_feature_egt_gaviota){
583                         // updating GaviotaPath
584                         my_log("POLYGLOT setting the Gaviota path to %s\n",path);
585                         start_protected_command();
586                         uci_send_option(Uci,"GaviotaTbPath","%s",path);
587                         end_protected_command();
588                     }else if(my_string_case_equal(type,"syzygy") && XB->has_feature_egt_syzygy){
589                         // updating SyzygyPath
590                         my_log("POLYGLOT setting the Syzygy path to %s\n",path);
591                         start_protected_command();
592                         uci_send_option(Uci,"SyzygyPath","%s",path);
593                         end_protected_command();
594                     }else{
595                         // refuse
596                         gui_send(GUI,"Error (unsupported table base format): %s",string);
597                     }
598                 }
599         } else if (XB->has_feature_memory && match(string,"memory *")){
600             int memory = atoi(Star[0]);
601             int egt_cache;
602             int real_memory;
603             if(memory>=1){
604                 // updating the available memory
605                 option_t *opt;
606                 int h;
607                 my_log("POLYGLOT setting the amount of memory to %dMb\n",memory);
608                 egt_cache=0;
609                 if(XB->has_feature_egt_nalimov && (opt=option_find(Uci->option,"NalimovCache"))){
610                     h=atoi(opt->value);
611                     if(h>egt_cache)egt_cache=h;
612                 }
613                 if(XB->has_feature_egt_gaviota && 
614                          (opt=option_find(Uci->option,"GaviotaTbCache"))){
615                     h=atoi(opt->value);
616                     if(h>egt_cache)egt_cache=h;
617                 }
618                 my_log("POLYGLOT EGTB Cache is %dMb\n",egt_cache);
619                 real_memory=memory-egt_cache;
620                 opt=option_find(Uci->option,"Hash");
621                 if(opt && real_memory > atoi(opt->max)) real_memory = atoi(opt->max); // [HGM] top off
622                 if(real_memory>0){
623                     start_protected_command();
624                     uci_send_option(Uci,"Hash", "%d", real_memory);
625                     end_protected_command();
626                 }
627             }else{
628                 // refuse
629                 gui_send(GUI,"Error (unknown command): %s",string);
630             }
631
632                 } else if (match(string,"sd *")) {
633
634                         XB->depth_limit = TRUE;
635                         XB->depth_max = atoi(Star[0]);
636
637                 } else if (match(string,"setboard *")) {
638
639                         my_log("POLYGLOT FEN %s\n",Star[0]);
640
641                         if (!game_init(Game,Star[0])) my_fatal("xboard_step(): bad FEN \"%s\"\n",Star[0]);
642
643                         move_list->size = 0; // [HGM] clear all exclude moves
644
645                         State->computer[White] = FALSE;
646                         State->computer[Black] = FALSE;
647
648                         XB->new_hack = TRUE; // HACK?
649                         XB->result = FALSE;
650
651                         board_update();
652                         mess();
653
654                 } else if (match(string,"st *")) {
655
656                         XB->time_limit = TRUE;
657                         XB->time_max = ((double)atoi(Star[0]));
658
659                 } else if (match(string,"time *")) {
660
661                         XB->my_time = ((double)atoi(Star[0])) / 100.0;
662                         if (XB->my_time < 0.0) XB->my_time = 0.0;
663
664                 } else if (match(string,"undo")) {
665
666                         move_list->size = 0; // [HGM] clear all exclude moves
667
668                         if (game_pos(Game) >= 1) {
669
670                                 game_goto(Game,game_pos(Game)-1);
671
672                                 ASSERT(!XB->new_hack);
673                                 XB->new_hack = FALSE; // HACK?
674                                 XB->result = FALSE;
675
676                                 board_update();
677                                 mess();
678                         }
679
680                 } else if (match(string,"usermove *")) {
681
682                         move_list->size = 0; // [HGM] clear all exclude moves
683
684                         game_get_board(Game,board);
685                         move = move_from_san(Star[0],board);
686
687                         if (move != MoveNone && move_is_legal(move,board)) {
688
689                                 XB->new_hack = FALSE;
690                                 ASSERT(!XB->result);
691                                 XB->result = FALSE;
692
693                                 // [HGM] externally supplied move means we did not fully play the current stm
694                                 State->playedAllMoves[colour_is_white(game_turn(Game)) ? White : Black] = FALSE;
695
696                                 move_step(move);
697                                 no_mess(move);
698
699                         } else {
700
701                                 gui_send(GUI,"Illegal move: %s",Star[0]);
702                         }
703
704                 } else if (match(string,"variant *")) {
705
706                         if (my_string_equal(Star[0],"fischerandom")) {
707                                 option_set(Option,"Chess960","true");
708                         } else {
709                                 option_set(Option,"Chess960","false");
710                         }
711
712                 } else if (match(string,"white")) {
713
714                         if (colour_is_white(game_turn(Game))) {
715
716                                 State->computer[White] = FALSE;
717                                 State->computer[Black] = TRUE;
718
719                                 XB->new_hack = TRUE;
720                                 XB->result = FALSE;
721
722                                 mess();
723                         }
724
725                 } else if (match(string,"xboard")) {
726
727                         // ignore
728
729                 } else if (match(string,".")) { // analyse info
730
731                         if (State->state == ANALYSE) {
732                                 int depth=Uci->best_depth;//HACK: don't clear engine-output window...
733
734                                 ASSERT(Uci->searching);
735                                 ASSERT(Uci->pending_nb>=1);
736
737                                 if (Uci->root_move != MoveNone && move_is_legal(Uci->root_move,Uci->board)) {
738                                         move_to_san(Uci->root_move,Uci->board,move_string,256);
739                                         gui_send(GUI,"stat01: %.0f "S64_FORMAT" %d %d %d %s",Uci->time*100.0,Uci->node_nb,/*Uci->*/depth,Uci->root_move_nb-(Uci->root_move_pos+1),Uci->root_move_nb,move_string);
740                                 } else {
741                                         gui_send(GUI,"stat01: %.0f "S64_FORMAT" %d %d %d",Uci->time*100.0,Uci->node_nb,/*Uci->*/depth,0,0); // HACK
742                                 }
743                         }
744
745                 } else if (match(string,"?")) { // move now
746
747                         if (State->state == THINK) {
748
749                                 ASSERT(Uci->searching);
750                                 ASSERT(Uci->pending_nb>=1);
751
752                                 // HACK: just send "stop" to the engine
753
754                                 if (Uci->searching) {
755                                         my_log("POLYGLOT STOP SEARCH\n");
756                                         engine_send(Engine,"stop");
757                                 }
758                         }
759
760                 } else { // unknown command, maybe a move?
761
762                         game_get_board(Game,board);
763                         move = move_from_san(string,board);
764
765                         if (move != MoveNone && move_is_legal(move,board)) {
766
767                                 XB->new_hack = FALSE;
768                                 ASSERT(!XB->result);
769                                 XB->result = FALSE;
770
771                                 move_step(move);
772                                 no_mess(move);
773
774                         } else if (move != MoveNone) {
775
776                                 gui_send(GUI,"Illegal move: %s",string);
777
778                         } else {
779
780                                 gui_send(GUI,"Error (unknown command): %s",string);
781                         }
782                 }
783         return;
784 }
785
786 // xboard2uci_engine_step()
787
788 void xboard2uci_engine_step(char string[]) {
789
790         int event;
791     board_t board[1];
792                 event = uci_parse(Uci,string);
793
794                 // react to events
795
796                 if ((event & EVENT_READY) != 0) {
797
798                         // the engine is now ready
799
800                         if (!Uci->ready) {
801                                 Uci->ready = TRUE;
802                     //  if (XB->proto_ver >= 2) xboard_send(XBoard,"feature done=1");
803                         }
804
805                         if (!DelayPong && XB->ping >= 0) {
806                                 gui_send(GUI,"pong %d",XB->ping);
807                                 XB->ping = -1;
808                         }
809                 }
810
811                 if ((event & EVENT_MOVE) != 0 && State->state == THINK) {
812
813                         // the engine is playing a move
814
815                         // MEGA HACK: estimate remaining time because XBoard won't send it!
816
817                         my_timer_stop(State->timer);
818
819                         XB->my_time -= my_timer_elapsed_real(State->timer);
820                         XB->my_time += XB->inc;
821                         if (XB->mps != 0 && (game_move_nb(Game) + 1) % XB->mps == 0) XB->my_time += XB->base;
822
823                         if (XB->my_time < 0.0) XB->my_time = 0.0;
824
825                         // make sure to remember the ponder move
826
827                         State->hint_move=Uci->ponder_move;
828
829                         // play the engine move
830
831                         comp_move(Uci->best_move);
832
833                 }
834
835                 if ((event & EVENT_PV) != 0) {
836
837                         // the engine has sent a new PV
838
839                         send_pv();
840                 }
841                 if ((event & EVENT_INFO) != 0) {
842
843                         // the engine has sent info
844
845                         send_info();
846                 }
847                 if((event & (EVENT_DRAW|EVENT_RESIGN))!=0){
848                         my_log("POYGLOT draw offer/resign from engine\n");
849                         if(option_find(Uci->option,"UCI_DrawOffers")){
850                                 if(event & EVENT_DRAW)
851                                         gui_send(GUI,"offer draw");
852                                 else
853                                         gui_send(GUI,"resign");
854                         }
855                 }
856                 if(((event & EVENT_ILLEGAL_MOVE)!=0) && (State->state == THINK)){
857                     game_get_board(Game,board);
858                     if(board->turn==White){
859                         gui_send(GUI,"0-1 {polyglot: resign"
860                                  " (illegal engine move by white: %s)}",Uci->bestmove);
861                     }else{
862                         gui_send(GUI,"1-0 {polyglot: resign"
863                                  " (illegal engine move by black: %s)}",Uci->bestmove);
864                     }
865                     board_disp(board);
866                     XB->result = TRUE;
867                     mess();
868                 }
869 }
870
871 // format_xboard_option_line
872
873 void format_xboard_option_line(char * option_line, option_t *opt){
874     int j;
875     char option_string[StringSize];
876     char *tmp;
877     strcpy(option_line,"");
878         // buffer overflow alert
879     strcat(option_line,"feature option=\"");
880     if(opt->mode&PG){
881         strcat(option_line,"Polyglot ");
882     }
883     sprintf(option_string,"%s",opt->name);
884     strcat(option_line,option_string);
885     sprintf(option_string," -%s",opt->type);
886     strcat(option_line,option_string);
887     if(!IS_BUTTON(opt->type) && strcmp(opt->type,"combo")){
888         if(strcmp(opt->type,"check")){
889             sprintf(option_string," %s",opt->value);
890         }else{
891             sprintf(option_string," %d",
892                     my_string_case_equal(opt->value,"true")||
893                     my_string_equal(opt->value,"1")
894                     ?1:0);
895         }
896         strcat(option_line,option_string);
897     }
898     if(IS_SPIN(opt->type)){
899         sprintf(option_string," %s",opt->min);
900             strcat(option_line,option_string);
901     }
902     if(IS_SPIN(opt->type)){
903         sprintf(option_string," %s",opt->max);
904         strcat(option_line,option_string);
905     }
906     for(j=0;j<opt->var_nb;j++){
907         if(!strcmp(opt->var[j],opt->value)){
908             sprintf(option_string," *%s",opt->var[j]);
909         }else{
910             sprintf(option_string," %s",opt->var[j]);
911         }
912         strcat(option_line,option_string);
913         if(j!=opt->var_nb-1){
914             strcat(option_line," ///");
915         }
916     }
917     strcat(option_line,"\"");
918     if(option_get_bool(Option,"WbWorkArounds") &&
919        (tmp=strstr(option_line,"Draw"))){
920         *tmp='d';
921         my_log("POLYGLOT Decapitalizing \"Draw\" in option \"%s\"\n",
922                opt->name);
923     }
924 }
925
926 // disarm() // [HGM] cleanse a string of offending double-quotes
927
928 static char*disarm(const char *s){
929     static char buf[25];
930     char *p = buf, *q;
931     strncpy(buf, s, 24);
932     q = buf + strlen(buf) - 1;
933     while(*q == '"') *q-- = '\0';          // strip trailing quotes
934     while(*p == '"') p++;                  // strip leading quotes
935     while((q = strchr(p, '"'))) *q = '\''; // replace internal quotes
936     return p;
937 }
938
939 // send_xboard_options()
940
941 static void send_xboard_options(){
942     
943     char egtfeature[StringSize];
944     int tbs=0;
945     
946     gui_send(GUI,"feature done=0");
947     
948     gui_send(GUI,"feature analyze=1");
949     gui_send(GUI,"feature exclude=1");
950     gui_send(GUI,"feature colors=0");
951     gui_send(GUI,"feature draw=1");
952     gui_send(GUI,"feature ics=1");
953     gui_send(GUI,"feature myname=\"%s\"",
954              disarm(option_get_string(Option,"EngineName")));
955     gui_send(GUI,"feature name=1");
956     gui_send(GUI,"feature pause=0");
957     gui_send(GUI,"feature ping=1");
958     gui_send(GUI,"feature playother=1");
959     gui_send(GUI,"feature sigint=1");
960     gui_send(GUI,"feature reuse=1");
961     gui_send(GUI,"feature san=0");
962     gui_send(GUI,"feature setboard=1");
963     gui_send(GUI,"feature sigint=0");
964     gui_send(GUI,"feature sigterm=0");
965     gui_send(GUI,"feature time=1");
966     gui_send(GUI,"feature usermove=1");
967     gui_send(GUI,"feature nps=1");
968     if (XB->has_feature_memory){
969         gui_send(GUI,"feature memory=1");
970     }else{
971         gui_send(GUI,"feature memory=0");
972     }
973     if (XB->has_feature_smp){
974         gui_send(GUI,"feature smp=1");
975     }else{
976         gui_send(GUI,"feature smp=0");
977     }
978     egtfeature[0]='\0';
979     strncat(egtfeature,"feature egt=\"",StringSize);
980     if (XB->has_feature_egt_nalimov){
981         tbs++;
982         strncat(egtfeature,"nalimov",StringSize-strlen(egtfeature));
983     }
984     if (XB->has_feature_egt_gaviota){
985         if(tbs>0){
986             strncat(egtfeature,",",StringSize-strlen(egtfeature));
987         }
988         tbs++;
989         strncat(egtfeature,"gaviota",StringSize-strlen(egtfeature));
990     }
991     if (XB->has_feature_egt_syzygy){
992         if(tbs>0){
993             strncat(egtfeature,",",StringSize-strlen(egtfeature));
994         }
995         strncat(egtfeature,"syzygy",StringSize-strlen(egtfeature));
996     }
997     strncat(egtfeature,"\"",StringSize-strlen(egtfeature));
998     egtfeature[StringSize-1]='\0';
999     gui_send(GUI,egtfeature);
1000     
1001     if (option_find(Uci->option,"UCI_Chess960")) {
1002         gui_send(GUI,"feature variants=\"normal,fischerandom\"");
1003     } else {
1004         gui_send(GUI,"feature variants=\"normal\"");
1005     }
1006
1007     xboard2uci_send_options();
1008 }
1009
1010 void xboard2uci_send_options(){
1011   char option_line[StringSize]="";
1012   const char * name;
1013   option_t *opt;
1014   
1015   option_start_iter(Uci->option);
1016   while((opt=option_next(Uci->option))){
1017     if(my_string_case_equal(opt->name,"UCI_AnalyseMode")) continue;
1018     if(my_string_case_equal(opt->name,"UCI_Opponent")) continue;
1019     if(my_string_case_equal(opt->name,"UCI_Chess960")) continue;
1020     if(my_string_case_equal(opt->name,"UCI_ShowCurrLine")) continue;
1021     if(my_string_case_equal(opt->name,"UCI_ShowRefutations")) continue;
1022     if(my_string_case_equal(opt->name,"UCI_ShredderbasesPath")) continue;
1023     if(my_string_case_equal(opt->name,"UCI_SetPositionValue")) continue;
1024     if(my_string_case_equal(opt->name,"UCI_DrawOffers")) continue;
1025     if(my_string_case_equal(opt->name,"Ponder")) continue;
1026     if(my_string_case_equal(opt->name,"Hash")) continue;
1027     if(my_string_case_equal(opt->name,"NalimovPath")) continue;
1028     if(my_string_case_equal(opt->name,"GaviotaTbPath")) continue;
1029     if(my_string_case_equal(opt->name,"SyzygyPath")) continue;
1030     if((name=uci_thread_option(Uci))!=NULL &&
1031        my_string_case_equal(opt->name,name)) continue;
1032     format_xboard_option_line(option_line,opt);
1033     
1034     gui_send(GUI,"%s",option_line);
1035   }
1036   
1037   
1038   gui_send(GUI,"feature option=\"Polyglot exclude move -string \"");
1039
1040   option_start_iter(Option);
1041   while((opt=option_next(Option))){
1042     if(opt->mode &XBOARD){
1043       format_xboard_option_line(option_line,opt);
1044       gui_send(GUI,"%s",option_line);
1045     }
1046   }       
1047   gui_send(GUI,"feature done=1"); 
1048   
1049 }
1050
1051 // report_best_score()
1052
1053 static int report_best_score(){
1054     if(!option_get_bool(Option,"ScoreWhite") ||
1055        colour_is_white(Uci->board->turn)){
1056         return Uci->best_score;
1057     }else{
1058         return -Uci->best_score;
1059     }
1060 }
1061
1062 // comp_move()
1063
1064 static void comp_move(int move) {
1065
1066    board_t board[1];
1067    char string[256];
1068
1069    ASSERT(move_is_ok(move));
1070
1071    ASSERT(State->state==THINK);
1072    ASSERT(!XB->analyse);
1073
1074    if(option_get_bool(Option,"RepeatPV"))
1075            send_pv(); // to update time and nodes
1076
1077    // send the move
1078
1079    game_get_board(Game,board);
1080
1081    if (move_is_castle(move,board) && option_get_bool(Option,"Chess960")) {
1082       if (!move_to_san(move,board,string,256)) my_fatal("comp_move(): move_to_san() failed\n"); // O-O/O-O-O
1083    } else {
1084       if (!move_to_can(move,board,string,256)) my_fatal("comp_move(): move_to_can() failed\n");
1085    }
1086
1087    gui_send(GUI,"move %s",string);
1088
1089    // resign?
1090
1091    if (option_get_bool(Option,"Resign") && Uci->root_move_nb > 1) {
1092
1093        if (Uci->best_score <= -abs(option_get_int(Option,"ResignScore"))) {
1094
1095          State->resign_nb++;
1096          my_log("POLYGLOT %d move%s with resign score\n",State->resign_nb,(State->resign_nb>1)?"s":"");
1097
1098          if (State->resign_nb >= option_get_int(Option,"ResignMoves")) {
1099             if (!option_get_bool(Option,"QueenNeverResigns") || !board_has_queen(board, board->turn)) { // [HGM] suppress resignig with Queen
1100                 my_log("POLYGLOT *** RESIGN ***\n");
1101                 gui_send(GUI,"resign");
1102             }
1103          }
1104
1105       } else {
1106
1107          if (State->resign_nb > 0) my_log("POLYGLOT resign reset (State->resign_nb=%d)\n",State->resign_nb);
1108          State->resign_nb = 0;
1109       }
1110    }
1111
1112    // play the move
1113
1114    move_step(move);
1115    no_mess(move);
1116 }
1117
1118 // move_step()
1119
1120 static void move_step(int move) {
1121
1122    board_t board[1];
1123    char move_string[256];
1124
1125    ASSERT(move_is_ok(move));
1126
1127    // log
1128
1129    game_get_board(Game,board);
1130
1131    if (move != MoveNone && move_is_legal(move,board)) {
1132
1133       move_to_san(move,board,move_string,256);
1134       my_log("POLYGLOT MOVE %s\n",move_string);
1135
1136    } else {
1137
1138       move_to_can(move,board,move_string,256);
1139       my_log("POLYGLOT ILLEGAL MOVE \"%s\"\n",move_string);
1140       board_disp(board);
1141
1142       my_fatal("move_step(): illegal move \"%s\"\n",move_string);
1143    }
1144
1145    // play the move
1146
1147    game_add_move(Game,move);
1148    board_update();
1149 }
1150
1151 // board_update()
1152
1153 static void board_update() {
1154
1155    // handle game end
1156
1157    ASSERT(!XB->result);
1158
1159    switch (game_status(Game)) {
1160    case PLAYING:
1161       break;
1162    case WHITE_MATES:
1163       gui_send(GUI,"1-0 {White mates}");
1164       break;
1165    case BLACK_MATES:
1166       gui_send(GUI,"0-1 {Black mates}");
1167       break;
1168    case STALEMATE:
1169       gui_send(GUI,"1/2-1/2 {Stalemate}");
1170       break;
1171    case DRAW_MATERIAL:
1172       gui_send(GUI,"1/2-1/2 {Draw by insufficient material}");
1173       break;
1174    case DRAW_FIFTY:
1175       gui_send(GUI,"1/2-1/2 {Draw by fifty-move rule}");
1176       break;
1177    case DRAW_REPETITION:
1178       gui_send(GUI,"1/2-1/2 {Draw by repetition}");
1179       break;
1180    default:
1181       ASSERT(FALSE);
1182       break;
1183    }
1184 }
1185
1186 // mess()
1187
1188 static void mess() {
1189
1190    // clear state variables
1191
1192    State->resign_nb = 0;
1193    State->exp_move = MoveNone;
1194    my_timer_reset(State->timer);
1195
1196    // abort a possible search
1197
1198    stop_search();
1199
1200    // calculate the new state
1201
1202    if (FALSE) {
1203    } else if (!active()) {
1204       State->state = WAIT;
1205       my_log("POLYGLOT WAIT\n");
1206    } else if (XB->analyse) {
1207       State->state = ANALYSE;
1208       my_log("POLYGLOT ANALYSE\n");
1209    } else if (State->computer[game_turn(Game)]) {
1210       State->state = THINK;
1211       my_log("POLYGLOT THINK\n");
1212    } else {
1213       State->state = WAIT;
1214       my_log("POLYGLOT WAIT\n");
1215    }
1216
1217    search_update();
1218 }
1219
1220 // no_mess()
1221
1222 static void no_mess(int move) {
1223
1224    ASSERT(move_is_ok(move));
1225
1226    // just received a move, calculate the new state
1227
1228    if (FALSE) {
1229
1230    } else if (!active()) {
1231
1232       stop_search(); // abort a possible search
1233
1234       State->state = WAIT;
1235       State->exp_move = MoveNone;
1236
1237       my_log("POLYGLOT WAIT\n");
1238
1239    } else if (State->state == WAIT) {
1240
1241       ASSERT(State->computer[game_turn(Game)]);
1242       ASSERT(!State->computer[colour_opp(game_turn(Game))]);
1243       ASSERT(!XB->analyse);
1244
1245       my_log("POLYGLOT WAIT -> THINK\n");
1246
1247       State->state = THINK;
1248       State->exp_move = MoveNone;
1249
1250    } else if (State->state == THINK) {
1251
1252       ASSERT(!State->computer[game_turn(Game)]);
1253       ASSERT(State->computer[colour_opp(game_turn(Game))]);
1254       ASSERT(!XB->analyse);
1255
1256       if (ponder() && ponder_ok(Uci->ponder_move)) {
1257
1258          my_log("POLYGLOT THINK -> PONDER\n");
1259
1260          State->state = PONDER;
1261          State->exp_move = Uci->ponder_move;
1262
1263       } else {
1264
1265          my_log("POLYGLOT THINK -> WAIT\n");
1266
1267          State->state = WAIT;
1268          State->exp_move = MoveNone;
1269       }
1270
1271    } else if (State->state == PONDER) {
1272
1273       ASSERT(State->computer[game_turn(Game)]);
1274       ASSERT(!State->computer[colour_opp(game_turn(Game))]);
1275       ASSERT(!XB->analyse);
1276
1277       if (move == State->exp_move && Uci->searching) {
1278
1279          ASSERT(Uci->searching);
1280          ASSERT(Uci->pending_nb>=1);
1281
1282          my_timer_start(State->timer);//also resets
1283
1284          my_log("POLYGLOT PONDER -> THINK (*** HIT ***)\n");
1285          engine_send(Engine,"ponderhit");
1286
1287          State->state = THINK;
1288          State->exp_move = MoveNone;
1289
1290          send_pv(); // update display
1291
1292          return; // do not launch a new search
1293
1294       } else {
1295
1296          my_log("POLYGLOT PONDER -> THINK (miss)\n");
1297
1298          stop_search();
1299
1300          State->state = THINK;
1301          State->exp_move = MoveNone;
1302       }
1303
1304    } else if (State->state == ANALYSE) {
1305
1306       ASSERT(XB->analyse);
1307
1308       my_log("POLYGLOT ANALYSE -> ANALYSE\n");
1309
1310       stop_search();
1311
1312    } else {
1313
1314       ASSERT(FALSE);
1315    }
1316
1317    search_update();
1318 }
1319
1320 // start_protected_command()
1321
1322 static void start_protected_command(){
1323     stop_search();
1324 }
1325
1326 static void end_protected_command(){
1327     if(Uci->ready){ // not init faze
1328         uci_send_isready_sync(Uci); // gobble up spurious "bestmove"
1329     }
1330     update_remaining_time();
1331     search_update();   // relaunch search if necessary
1332 }
1333
1334 // update_remaining_time()
1335
1336 static void update_remaining_time(){
1337    double reduce;
1338    if(State->timer->running){
1339        my_timer_stop(State->timer);
1340        reduce = my_timer_elapsed_real(State->timer);
1341        my_log("POLYGLOT reducing remaing time by %f seconds\n",reduce);
1342        XB->my_time -= reduce;
1343        if(XB->my_time<0.0){
1344            XB->my_time=0.0;
1345        }
1346    }
1347 }
1348
1349
1350 // search_update()
1351
1352 static void search_update() {
1353
1354    int move;
1355    int move_nb;
1356    board_t board[1];
1357
1358    ASSERT(!Uci->searching);
1359
1360
1361
1362    
1363    // launch a new search if needed
1364
1365    
1366
1367    if (State->state == THINK || State->state == PONDER || State->state == ANALYSE) {
1368
1369       // [VdB] moved up as we need the move number
1370
1371        game_get_board(Game,Uci->board);
1372
1373       // opening book
1374
1375        if (State->state == THINK &&
1376            option_get_bool(Option,"Book") &&
1377            Uci->board->move_nb<option_get_int(Option,"BookDepth")
1378            ) {
1379
1380
1381          move = book_move(Uci->board,option_get_bool(Option,"BookRandom"));
1382
1383          if (move != MoveNone && move_is_legal(move,Uci->board)) {
1384
1385             my_log("POLYGLOT *BOOK MOVE*\n");
1386
1387             search_clear(); // clears Uci->ponder_move
1388             Uci->best_move = move;
1389
1390             board_copy(board,Uci->board);
1391             move_do(board,move);
1392             Uci->ponder_move = book_move(board,FALSE); // expected move = best book move
1393
1394             Uci->best_pv[0] = Uci->best_move;
1395             Uci->best_pv[1] = Uci->ponder_move; // can be MoveNone
1396             Uci->best_pv[2] = MoveNone;
1397
1398             comp_move(Uci->best_move);
1399
1400             return;
1401          }
1402       }
1403
1404       // engine search
1405
1406       my_log("POLYGLOT START SEARCH\n");
1407
1408       // options
1409
1410       uci_send_option(Uci,"UCI_Chess960","%s",
1411                       option_get_bool(Option,"Chess960")?"true":"false");
1412
1413       if (option_get_int(Option,"UCIVersion") >= 2) {
1414          uci_send_option(Uci,"UCI_Opponent","none none %s %s",(XB->computer)?"computer":"human",XB->name);
1415          uci_send_option(Uci,"UCI_AnalyseMode","%s",(XB->analyse)?"true":"false");
1416       }
1417
1418       uci_send_option(Uci,"Ponder","%s",ponder()?"true":"false");
1419
1420       // position
1421
1422       move = (State->state == PONDER) ? State->exp_move : MoveNone;
1423       send_board(move); // updates Uci->board global variable
1424
1425       // search
1426
1427       if (State->state == THINK || State->state == PONDER) {
1428
1429          engine_send_queue(Engine,"go");
1430
1431          if (XB->time_limit) {
1432
1433             // fixed time per move
1434              
1435              if(XB->node_rate > 0){
1436                  engine_send_queue(Engine,
1437                                    " nodes %.0f",
1438                                    XB->time_max*((double)XB->node_rate));
1439              }else{
1440                  double computed_time;
1441                  double st_fudge;
1442                  st_fudge=(double) option_get_int(Option,"STFudge");
1443                  my_log("POLYGLOT Giving engine %.0fmsec extra time.\n",st_fudge);
1444                  computed_time=XB->time_max*1000.0-st_fudge;
1445                  if(computed_time< 1.0){
1446                      computed_time=1.0;
1447                  }
1448                  engine_send_queue(Engine,
1449                                    " movetime %.0f",
1450                                    computed_time);
1451              }
1452
1453          } else {
1454
1455             // time controls
1456
1457                  if(XB->node_rate > 0) {
1458                      double time;
1459                      move_nb = 40;
1460                      if (XB->mps != 0){
1461                          move_nb = XB->mps - (Uci->board->move_nb % XB->mps);
1462                      }
1463                      time = XB->my_time / move_nb;
1464                      if(XB->inc != 0){
1465                          time += XB->inc;
1466                      }
1467                      if(time > XB->my_time){
1468                          time = XB->my_time;
1469                      }
1470                      engine_send_queue(Engine,
1471                                        " nodes %.0f",
1472                                        time*XB->node_rate);
1473                  } else {
1474                      
1475                      if (colour_is_white(Uci->board->turn)) {
1476                          engine_send_queue(Engine,
1477                                            " wtime %.0f btime %.0f",
1478                                            XB->my_time*1000.0,XB->opp_time*1000.0);
1479                      } else {
1480                          engine_send_queue(Engine,
1481                                            " wtime %.0f btime %.0f",
1482                                            XB->opp_time*1000.0,XB->my_time*1000.0);
1483                      }
1484                      
1485                      if (XB->inc != 0.0){
1486                          engine_send_queue(Engine,
1487                                            " winc %.0f binc %.0f",
1488                                            XB->inc*1000.0,XB->inc*1000.0);
1489                      }
1490                      if (XB->mps != 0) {
1491
1492                          move_nb = XB->mps - (Uci->board->move_nb % XB->mps);
1493                          ASSERT(move_nb>=1&&move_nb<=XB->mps);
1494                          
1495                          engine_send_queue(Engine," movestogo %d",move_nb);
1496                      }
1497                  }
1498          }
1499          if (XB->depth_limit) engine_send_queue(Engine," depth %d",XB->depth_max);
1500
1501          if (State->state == PONDER) engine_send_queue(Engine," ponder");
1502
1503          engine_send(Engine,""); // newline
1504
1505       } else if (State->state == ANALYSE) {
1506          int i;
1507          char move_string[256];
1508
1509          engine_send_queue(Engine,"go infinite");
1510
1511          if(list_size(move_list)) {
1512                 board_t board[1];
1513                 game_get_board(Game,board);
1514             engine_send_queue(Engine," searchmoves");
1515             for(i=0; i<list_size(move_list); i++) {
1516                if(!move_list->value[i]) {
1517                   move_to_can(move_list->move[i],board,move_string,256);
1518                   engine_send_queue(Engine," %s",move_string);
1519                }
1520             }
1521          }
1522          engine_send(Engine,""); // newline
1523
1524       } else {
1525
1526          ASSERT(FALSE);
1527       }
1528
1529       // init search info
1530
1531       ASSERT(!Uci->searching);
1532
1533       search_clear();
1534
1535       Uci->searching = TRUE;
1536       Uci->pending_nb++;
1537    }
1538 }
1539
1540 // search_clear()
1541
1542 static void search_clear() {
1543
1544    uci_clear(Uci);
1545
1546    // TODO: MOVE ME
1547
1548    my_timer_start(State->timer);//also resets
1549 }
1550
1551 // active()
1552
1553 static bool active() {
1554
1555    // position state
1556
1557    if (game_status(Game) != PLAYING) return FALSE; // game ended
1558
1559    // xboard state
1560
1561    if (XB->analyse) return TRUE; // analysing
1562    if (!State->computer[White] && !State->computer[Black]) return FALSE; // force mode
1563    if (XB->new_hack || XB->result) return FALSE; // unstarted or ended game
1564
1565    return TRUE; // playing
1566 }
1567
1568 // ponder()
1569
1570 static bool ponder() {
1571
1572     return XB->ponder && (option_get_bool(Option,"CanPonder") ||
1573                           option_find(Uci->option,"Ponder"));
1574 }
1575 // ponder_ok()
1576
1577 static bool ponder_ok(int move) {
1578    int status;
1579    board_t board[1];
1580
1581    ASSERT(move==MoveNone||move_is_ok(move));
1582
1583    // legal ponder move?
1584
1585    if (move == MoveNone) return FALSE;
1586
1587    game_get_board(Game,board);
1588    if (!move_is_legal(move,board)) return FALSE;
1589
1590    // UCI-legal resulting position?
1591
1592    game_add_move(Game,move);
1593
1594    game_get_board(Game,board);
1595    status = game_status(Game);
1596
1597    game_rem_move(Game);
1598
1599    if (status != PLAYING) return FALSE; // game ended
1600
1601    if (option_get_bool(Option,"Book") && is_in_book(board)) {
1602       return FALSE;
1603    }
1604
1605    return TRUE;
1606 }
1607
1608 // stop_search()
1609
1610 static void stop_search() {
1611
1612    if (Uci->searching) {
1613
1614       ASSERT(Uci->searching);
1615       ASSERT(Uci->pending_nb>=1);
1616
1617       my_log("POLYGLOT STOP SEARCH\n");
1618
1619 /*
1620       engine_send(Engine,"stop");
1621       Uci->searching = FALSE;
1622 */
1623
1624       if (option_get_bool(Option,"SyncStop")) {
1625          uci_send_stop_sync(Uci);
1626       } else {
1627          uci_send_stop(Uci);
1628       }
1629         }
1630 }
1631
1632 // send_board()
1633
1634 static void send_board(int extra_move) {
1635
1636    char fen[256];
1637    int start, end;
1638    board_t board[1];
1639    int pos;
1640    int move;
1641    char string[256];
1642
1643    ASSERT(extra_move==MoveNone||move_is_ok(extra_move));
1644
1645    ASSERT(!Uci->searching);
1646
1647    // init
1648
1649    game_get_board(Game,Uci->board);
1650    if (extra_move != MoveNone) move_do(Uci->board,extra_move);
1651
1652    board_to_fen(Uci->board,fen,256);
1653    my_log("POLYGLOT FEN %s\n",fen);
1654
1655    ASSERT(board_can_play(Uci->board));
1656
1657    // more init
1658
1659    start = 0;
1660    end = game_pos(Game);
1661    ASSERT(end>=start);
1662
1663    // position
1664
1665    game_get_board_ex(Game,board,start);
1666    board_to_fen(board,string,256);
1667
1668    engine_send_queue(Engine,"position");
1669
1670    if (my_string_equal(string,StartFen)) {
1671       engine_send_queue(Engine," startpos");
1672    } else {
1673       engine_send_queue(Engine," fen %s",string);
1674    }
1675
1676    // move list
1677
1678    if (end > start || extra_move != MoveNone) engine_send_queue(Engine," moves");
1679
1680    for (pos = start; pos < end; pos++) { // game moves
1681
1682       move = game_move(Game,pos);
1683
1684       move_to_can(move,board,string,256);
1685       engine_send_queue(Engine," %s",string);
1686
1687       move_do(board,move);
1688    }
1689
1690    if (extra_move != MoveNone) { // move to ponder on
1691       move_to_can(extra_move,board,string,256);
1692       engine_send_queue(Engine," %s",string);
1693    }
1694
1695    // end
1696
1697    engine_send(Engine,""); // newline
1698 }
1699
1700 // send_info()
1701
1702 static void send_info() {
1703     int min_depth;
1704     if(option_get_bool(Option,"WbWorkArounds2")){
1705             // Silly bug in some versions of WinBoard.
1706             // depth <=1 clears the engine output window.
1707             // Why shouldn't an engine be allowed to send info at depth 1?
1708         min_depth=2;
1709     }else{
1710         min_depth=1;
1711     }
1712     if(!strncmp(Uci->info, "xboard ", 7)) gui_send(GUI,"%s",Uci->info+7); else // kludge to allow UCI engines to use WB protocol
1713     gui_send(GUI,"%d %+d %.0f "S64_FORMAT" %s",Uci->best_depth>min_depth?Uci->best_depth:min_depth,
1714              0,0.0,U64(0),Uci->info);  
1715 }
1716
1717 // send_pv()
1718
1719 static void send_pv() {
1720
1721    char pv_string[StringSize];
1722    board_t board[1];
1723    int move;
1724    char move_string[StringSize];
1725
1726    ASSERT(State->state!=WAIT);
1727
1728    if (Uci->best_depth == 0) return;
1729
1730    // xboard search information
1731
1732    if (XB->post) {
1733
1734       if (State->state == THINK || State->state == ANALYSE) {
1735
1736          line_to_san(Uci->best_pv,Uci->board,pv_string,StringSize);
1737
1738                  if(Uci->depth==-1) //hack to clear the engine output window
1739              gui_send(GUI,"%d %+d %.0f "S64_FORMAT" ",0,report_best_score(),Uci->time*100.0,Uci->node_nb);
1740                 if(option_get_bool(Option,"ShowTbHits"))
1741                  gui_send(GUI,"%d %+d %.0f "S64_FORMAT" {%d,%.0f,"S64_FORMAT"} %s%c",Uci->best_depth,report_best_score(),
1742                         Uci->time*100.0,Uci->node_nb,Uci->sel_depth,Uci->speed/1e3,Uci->tbhit_nb,pv_string,Uci->bound_type);
1743                 else
1744                  gui_send(GUI,"%d %+d %.0f "S64_FORMAT" %s%c",Uci->best_depth,report_best_score(),Uci->time*100.0,Uci->node_nb,pv_string,Uci->bound_type);
1745
1746       } else if (State->state == PONDER &&
1747                  option_get_bool(Option,"ShowPonder")) {
1748
1749          game_get_board(Game,board);
1750          move = State->exp_move;
1751
1752          if (move != MoveNone && move_is_legal(move,board)) {
1753             move_to_san(move,board,move_string,256);
1754             line_to_san(Uci->best_pv,Uci->board,pv_string,StringSize);
1755             if(option_get_bool(Option,"ShowTbHits"))
1756                  gui_send(GUI,"%d %+d %.0f "S64_FORMAT" {%d,%.0f,"S64_FORMAT"} (%s) %s%c",Uci->best_depth,report_best_score(),
1757                         Uci->time*100.0,Uci->node_nb,Uci->sel_depth,Uci->speed/1e3,Uci->tbhit_nb,move_string,pv_string,Uci->bound_type);
1758             else
1759                 gui_send(GUI,"%d %+d %.0f "S64_FORMAT" (%s) %s%c",Uci->best_depth,report_best_score(),
1760                         Uci->time*100.0,Uci->node_nb,move_string,pv_string,Uci->bound_type);
1761          }
1762       }
1763    }
1764
1765    // kibitz
1766
1767    if ((Uci->searching &&
1768         option_get_bool(Option,"KibitzPV") &&
1769         Uci->time >= option_get_double(Option,"KibitzDelay"))
1770        || (!Uci->searching && option_get_bool(Option,"KibitzMove"))) {
1771
1772       if (State->state == THINK || State->state == ANALYSE) {
1773
1774          line_to_san(Uci->best_pv,Uci->board,pv_string,StringSize);
1775          if(kibitz_throttle(Uci->searching)){
1776              gui_send(GUI,"%s depth=%d time=%.2f node="S64_FORMAT" speed=%.0f score=%+.2f pv=\"%s\"",option_get_string(Option,"KibitzCommand"),Uci->best_depth,Uci->time,Uci->node_nb,Uci->speed,((double)report_best_score())/100.0,pv_string);
1777          }
1778       } else if (State->state == PONDER) {
1779
1780          game_get_board(Game,board);
1781          move = State->exp_move;
1782
1783          if (move != MoveNone && move_is_legal(move,board)) {
1784             move_to_san(move,board,move_string,256);
1785             line_to_san(Uci->best_pv,Uci->board,pv_string,StringSize);
1786             if(kibitz_throttle(Uci->searching)){
1787                 gui_send(GUI,"%s depth=%d time=%.2f node="S64_FORMAT" speed=%.0f score=%+.2f pv=\"(%s) %s\"",option_get_string(Option,"KibitzCommand"),Uci->best_depth,Uci->time,Uci->node_nb,Uci->speed,((double)report_best_score())/100.0,move_string,pv_string);
1788             }
1789          }
1790       }
1791    }
1792 }
1793
1794 // kibitz_throttle()
1795
1796 static bool kibitz_throttle(bool searching){
1797     time_t curr_time;
1798     static time_t lastKibitzMove=0;
1799     static time_t lastKibitzPV=0;
1800     curr_time = time(NULL);
1801     if(searching){   // KibitzPV
1802         if(curr_time >=
1803            (option_get_int(Option,"KibitzInterval") + lastKibitzPV)){
1804             lastKibitzPV=curr_time;
1805             return TRUE;
1806         }
1807     }else{       // KibitzMove
1808         if(curr_time >=
1809            (option_get_int(Option,"KibitzInterval") + lastKibitzMove)){
1810             lastKibitzPV=curr_time;
1811             lastKibitzMove=curr_time;
1812             return TRUE;
1813         }        
1814     }
1815     return FALSE;
1816 }
1817
1818 // learn()
1819
1820 static void learn(int result) {
1821
1822    int pos;
1823    board_t board[1];
1824    int move;
1825
1826    ASSERT(result>=-1&&result<=+1);
1827
1828    ASSERT(XB->result);
1829 //   ASSERT(State->computer[White]||State->computer[Black]);
1830
1831    // init
1832
1833    pos = 0;
1834
1835    // [HGM] does not account for the hypothetical possibility we played both sides!
1836    if (State->playedAllMoves[White]) {
1837       pos = 0;
1838    } else if (State->playedAllMoves[Black]) {
1839       pos = 1;
1840       result = -result;
1841    } else {
1842       return; // [HGM] if we did not play all moves for some side, do not learn, but don't make a fuss!
1843    }
1844
1845    if (FALSE) {
1846    } else if (result > 0) {
1847       my_log("POLYGLOT *LEARN WIN*\n");
1848    } else if (result < 0) {
1849       my_log("POLYGLOT *LEARN LOSS*\n");
1850    } else {
1851       my_log("POLYGLOT *LEARN DRAW*\n");
1852    }
1853
1854    // loop
1855
1856    for (; pos < Game->size; pos += 2) {
1857
1858       game_get_board_ex(Game,board,pos);
1859       move = game_move(Game,pos);
1860
1861       book_learn_move(board,move,result);
1862    }
1863
1864    book_flush();
1865 }
1866
1867 // end of xboard2uci.c