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