Pass command to DoCommand through global command queue
[uci2wb.git] / UCI2WB.c
1 /****************************************************************************/\r
2 /*                           UCI2WB by H.G.Muller                           */\r
3 /*                                                                          */\r
4 /* UCI2WB is an adapter to run engines that communicate in various dialects */\r
5 /* of the Universal Chess Interface in a GUI that supports XBoard protocol  */\r
6 /* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'),  */\r
7 /* as well as USI and UCCI when used with the flags -s or -x, respectively. */\r
8 /* This version of UCI2WB is released under the GNU General Public License, */\r
9 /* of which you should have received a copy together with this file.        */\r
10 /****************************************************************************/\r
11 \r
12 #define VERSION "3.0"\r
13 \r
14 #include <stdio.h>\r
15 #include <stdlib.h>\r
16 #ifdef WIN32\r
17 #  include <windows.h>\r
18 #  include <io.h>\r
19    HANDLE process;\r
20    DWORD thread_id;\r
21 #else\r
22 #  include <pthread.h>\r
23 #  include <signal.h>\r
24 #  define NO_ERROR 0\r
25 #  include <sys/time.h>\r
26    int GetTickCount() // with thanks to Tord\r
27    { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }\r
28 #endif\r
29 #include <fcntl.h>\r
30 #include <string.h>\r
31 \r
32 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
33 #define VARIANTS ",normal,xiangqi"\r
34 #define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"\r
35 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"\r
36 \r
37 #define DPRINT if(debug) printf\r
38 #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }\r
39 \r
40 #define WHITE 0\r
41 #define BLACK 1\r
42 #define NONE  2\r
43 #define ANALYZE 3\r
44 \r
45 char move[2000][10], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;\r
46 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;\r
47 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp;\r
48 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], backLog[10000], checkOptions[8192] = "Ponder";\r
49 char pvs[99][999], board[100];  // XQ board for UCCI\r
50 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI\r
51 int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways;\r
52 volatile int logLen, sentLen;\r
53 \r
54 FILE *toE, *fromE, *fromF;\r
55 int pid;\r
56 \r
57 char *strcasestr (char *p, char *q) { while(*p) { char *r=p++, *s=q; while(tolower(*r++) == tolower(*s) && *s) s++; if(!*s) return p-1; } return NULL; }\r
58 \r
59 #ifdef WIN32\r
60 WinPipe(HANDLE *hRd, HANDLE *hWr)\r
61 {\r
62   SECURITY_ATTRIBUTES saAttr;\r
63 \r
64   /* Set the bInheritHandle flag so pipe handles are inherited. */\r
65   saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
66   saAttr.bInheritHandle = TRUE;\r
67   saAttr.lpSecurityDescriptor = NULL;\r
68 \r
69   /* Create a pipe */\r
70   return CreatePipe(hRd, hWr, &saAttr, 0);\r
71 }\r
72 #endif\r
73 \r
74 #define INIT 0\r
75 #define WAKEUP 1\r
76 #define PAUSE 2\r
77 \r
78 void\r
79 Sync (int action)\r
80 {\r
81 #ifdef WIN32\r
82         static HANDLE hWr, hRd; DWORD d; char c;\r
83         switch(action) {\r
84             case INIT:   WinPipe(&hRd, &hWr); break;\r
85             case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;\r
86             case PAUSE:  ReadFile(hRd, &c, 1, &d, NULL);\r
87         }\r
88 #else\r
89         static int syncPipe[2]; char c;\r
90         switch(action) {\r
91             case INIT:   pipe(syncPipe); break;\r
92             case WAKEUP: write(syncPipe[1], "\n", 1); break;\r
93             case PAUSE:  read(syncPipe[0], &c, 1);\r
94         }\r
95 #endif\r
96 }\r
97 \r
98 void\r
99 FromFEN(char *fen)\r
100 {       int i=0;\r
101         while(*fen) {\r
102             char c = *fen++;\r
103             if(c >= 'A') board[i++] = c; else\r
104             if(c == '/') i++; else\r
105             if(c == ' ') break; else\r
106             while(c-- > '0' && i < 99) board[i++] = 0;\r
107             if(i >= 99) break;\r
108         }\r
109 }\r
110 \r
111 char *\r
112 ToFEN(int stm)\r
113 {\r
114         int i, n=0; static char fen[200]; char *p = fen;\r
115         for(i=0; i<99; i++) {\r
116             char c = board[i];\r
117             if(c >= 'A')  { if(n) *p++ = '0' + n; n = 0;  *p++ = c; } else n ++;\r
118             if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; }\r
119         }\r
120         sprintf(p-1, " %c - - 0 1", stm);\r
121         return fen;\r
122 }\r
123 \r
124 int\r
125 Sqr(char *m, int j)\r
126 {\r
127         int n = m[j] - 'a' + 10*('9' - m[j+1]);\r
128         if(n < 0) n = 0; else if(n > 99) n = 99; return n;\r
129 }\r
130 \r
131 int\r
132 Play(int nr)\r
133 {\r
134         int i, last = -1;\r
135         FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix\r
136         for(i=0; i<nr; i++) {\r
137             int from=Sqr(move[i], 0), to=Sqr(move[i], 2);\r
138             if(board[to] || (board[from]|32)  == 'p' && move[i][1] != move[i][3]) last = i;\r
139             board[to] = board[from]; board[from] = 0;\r
140         }\r
141         return last;\r
142 }\r
143 \r
144 void\r
145 StartSearch(char *ponder)\r
146 {       // send the 'go' command to engine. Suffix by ponder.\r
147         int x = (ponder[0] != 0);                   // during ponder stm is the opponent\r
148         int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black\r
149         int nr = moveNr + x;                        // we ponder for one move ahead!\r
150         int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time \r
151         if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent\r
152         if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering\r
153         EPRINT((f, "# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t))\r
154         if(sTime > 0) EPRINT((f, " movetime %d", sTime)) else\r
155         if(mps) EPRINT((f, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2))\r
156         if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi\r
157         if(inc && !*suffix) EPRINT((f, " %s %d %s %d", wInc, inc, bInc, inc))\r
158         if(depth > 0) EPRINT((f, " depth %d", depth))\r
159         if(*suffix) EPRINT((f, suffix, inc))\r
160         EPRINT((f, "\n")); maxDepth = mpvSP = 0;\r
161 }\r
162 \r
163 void\r
164 StopPonder(int pondering)\r
165 {\r
166         if(!pondering) return;\r
167         pause = 1;\r
168         EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
169         Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
170 }\r
171 \r
172 void\r
173 LoadPos(int moveNr)\r
174 {\r
175         int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;\r
176         if(sc == 'x') { // UCCI: send only reversible moves\r
177             lastCapt = Play(moveNr); // find last capture (returns -1 if none!)\r
178             Play(++lastCapt);        // reconstruct board after last capture\r
179             stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' :  'b');\r
180             sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)\r
181         }\r
182         EPRINT((f, "# %s moves", pos))\r
183         for(j=lastCapt; j<moveNr; j++) EPRINT((f, " %s", move[j]))\r
184         EPRINT((f, "\n"))\r
185 }\r
186 \r
187 void\r
188 StartPonder(int moveNr)\r
189 {\r
190         if(!move[moveNr][0]) return; // no ponder move\r
191         LoadPos(moveNr+1);\r
192         pondering = 1; lastDepth = 1;\r
193         StartSearch(" ponder");\r
194 }\r
195 \r
196 void\r
197 Analyze(char *val)\r
198 {\r
199     if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));\r
200 }\r
201 \r
202 int\r
203 Release()\r
204 {   // send setoption commands backlogged during thinking to engine, aborting ponder or analysis search if necessary\r
205     int len = logLen - sentLen, analyse = searching;\r
206     if(len <= 0) return 0;\r
207     StopPonder(pondering | searching); pondering = searching = 0; // force new search if settings change during analysis (multi-PV!)\r
208     fwrite(backLog + sentLen, 1, len, toE); sentLen += len; DPRINT("# release %d\n", len);\r
209     if(ponder && computer == 1 - stm) StartPonder(moveNr); // (re)start ponder search\r
210     return analyse; // return 1 if analysis search should be restarted\r
211 }\r
212 \r
213 char *Convert(char *pv)\r
214 {   // convert Shogi coordinates to WB\r
215     char *p, *q, c;\r
216     static char buf[10000];\r
217     if(sc != 's') return pv;\r
218     p = pv; q = buf;\r
219     while(c = *p++) {\r
220         if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
221     }\r
222     *q++ = 0;\r
223     return buf;\r
224 }\r
225 \r
226 void\r
227 Move4GUI(char *m)\r
228 {\r
229     if(sc == 's') {\r
230       // convert USI move to WB format\r
231       m[2] = 'a'+'0'+size - m[2];\r
232       m[3] = 'a'+'0'+size - m[3];\r
233       if(m[1] == '*') { // drop\r
234         m[1] = '@';\r
235       } else {\r
236         m[0] = 'a'+'0'+size - m[0];\r
237         m[1] = 'a'+'0'+size - m[1];\r
238         if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)\r
239                                 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')\r
240              m[4] = '=', m[5] = 0;\r
241       }\r
242     }\r
243 }\r
244 \r
245 int\r
246 ReadLine (FILE *f, char *line)\r
247 {\r
248     int x, i = 0;\r
249     while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;\r
250     return (x != EOF);\r
251 }\r
252 \r
253 void\r
254 HandleEngineOutput()\r
255 {\r
256     char line[1024], command[256]; static char egts[999];\r
257 \r
258     while(1) {\r
259         int i=0, x; char *p, dummy, len;\r
260 \r
261         fflush(stdout); fflush(toE);\r
262         if(fromF && !ReadLine(fromF, line))  fromF = 0, printf("# end fake\n");\r
263         if(!fromF && !ReadLine(fromE, line)) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);\r
264         DPRINT("# engine said: %s", line), fflush(stdout);\r
265         if(sscanf(line, "%s", command) != 1) continue;\r
266         if(!strcmp(command, "bestmove")) {\r
267             if(pause == 1) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
268             else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search\r
269             // move was a move to be played\r
270             if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI\r
271             if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
272             if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI\r
273             if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
274                strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
275             sscanf(line, "bestmove %s", move[moveNr++]);\r
276             Release(); // send setoption commands that arrived during search\r
277             myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
278             if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts\r
279             stm = WHITE+BLACK - stm;\r
280             // first start a new ponder search, if pondering is on and we have a move to ponder on\r
281             if(p = strstr(line+9, "ponder")) {\r
282               sscanf(p+7, "%s", move[moveNr]);\r
283               if(computer != NONE && ponder) {\r
284                 DPRINT("# ponder on %s\n", move[moveNr]);\r
285                 StartPonder(moveNr);\r
286               }\r
287               p[-1] = '\n'; *p = 0; // strip off ponder move\r
288             } else move[moveNr][0] = 0;\r
289             Move4GUI(line+9);\r
290             printf("move %s\n", line+9); // send move to GUI\r
291             if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);\r
292             if(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think\r
293             if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }\r
294         }\r
295         else if(!strcmp(command, "info")) {\r
296             int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;\r
297             char *pv, varName[80];\r
298             if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }\r
299             if(sscanf(line+5, "string variant %s", varName) == 1) {\r
300                 if(!strstr(STDVARS, varName)) {\r
301                     int files = 8, ranks = 8, hand = 0; char parent[80];\r
302                     if(p = strstr(line+18, " files ")) sscanf(p+7, "%d", &files);\r
303                     if(p = strstr(line+18, " ranks ")) sscanf(p+7, "%d", &ranks);\r
304                     if(p = strstr(line+18, " pocket ")) sscanf(p+8, "%d", &hand);\r
305                     if(p = strstr(line+18, " template ")) sscanf(p+10, "%s", parent); else strcpy(parent, "fairy");\r
306                     if(p = strstr(line+18, " startpos "))\r
307                         printf("setup (-) %dx%d+%d_%s %s", files, ranks, hand, parent, p+10);\r
308                 }\r
309                 continue;\r
310             }\r
311             if(collect && (pv = strstr(line+5, "currmove "))) {\r
312                 if(p = strstr(line+5, "currmovenumber ")) {\r
313                     n = atoi(p+15);\r
314                     if(collect == 1 && n != 1) continue; // wait for move 1\r
315                     if(collect + (n == 1) > 2) { // done collecting\r
316                         if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);\r
317                         collect = 3; continue;\r
318                     }\r
319                     collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move\r
320                 }\r
321             }\r
322             if(!post) continue;\r
323             if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
324                 if(p = strstr(line+4, " depth "))      sscanf(p+7, "%d", &d), statDepth = d;\r
325                 if(p = strstr(line+4, " score cp "))   sscanf(p+10, "%d", &s), statScore = s; else\r
326                 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else\r
327                 if(p = strstr(line+4, " score "))      sscanf(p+7, "%d", &s), statScore = s;\r
328                 if(p = strstr(line+4, " nodes "))      sscanf(p+7, "%d", &n), statNodes = n;\r
329                 if(p = strstr(line+4, " time "))       sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
330                 if(p = strstr(line+4, " currmove "))   sscanf(p+10,"%s", currMove);\r
331                 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);\r
332                 if(pv = strstr(line+4, " pv ")) { // convert PV info to WB thinking output\r
333                   if(d > maxDepth) maxDepth = d, mpvSP = 0; else if(d < maxDepth) continue; // ignore depth regressions\r
334                   if(p = strstr(line+4, " upperbound ")) strcat(p, "?\n"); else\r
335                   if(p = strstr(line+4, " lowerbound ")) strcat(p, "!\n");\r
336                   for(i=0; i<mpvSP; i++) if(s == scores[i] && !strcmp(pvs[i], pv+4)) break; // check if duplicat\r
337                   if(i >= mpvSP) strncpy(pvs[mpvSP], pv+4, 998), scores[mpvSP++] = s,       // emit as thinking output if not\r
338                     printf("%3d  %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
339                 } else if(s == -100000) lastScore = s; // when checkmated score is valid even without PV (which might not come)\r
340             }\r
341         }\r
342         else if(!strcmp(command, "option")) { // USI option: extract data fields\r
343             char name[80], type[80], buf[1024], val[256], *q;\r
344             int min=0, max=1e9; *val = 0;\r
345             if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
346             if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
347             if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
348             if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
349             if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI\r
350             if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }\r
351             if(!strcasecmp(name, "UCI_Variant")) { if(p = strstr(line+6, " var ")) strcpy(varList, p); varOpt = 1; continue; }\r
352             if(!strcasecmp(name, "UCI_Opponent")) { namOpt = 1; continue; }\r
353             if(!strcasecmp(name+2, "I_AnalyseMode")) { strcpy(anaOpt, name); continue; }\r
354             if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {\r
355                 EPRINT((f, "# setoption name %s value true\n", name)) strcpy(val, "true"); // set non-standard suspected FRC options\r
356             }\r
357             if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }\r
358             if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }\r
359             if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {\r
360                 memory = oldMem = atoi(val); hasHash = 1; \r
361                 strcpy(hashOpt, name);\r
362                 continue;\r
363             }\r
364             if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }\r
365             if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }\r
366             sprintf(buf, ",%s,", name); if(p = strcasestr(EGT, buf)) { // collect EGT formats\r
367                 strcpy(buf, p); for(p=buf; *++p >='a';){} if(*p == ' ') strcpy(buf, ",scorpio"); *p = 0; strcat(egts, buf); continue; // clip at first non-lower-case\r
368             }\r
369             // pass on engine-defined option as WB option feature\r
370             if(!strcmp(type, "filename")) type[4] = 0;\r
371             else if(sc == 'c' && !strcmp(type, "string")) { // in UCI try to guess which strings are file or directory names\r
372                 if(strcasestr(name, "file")) strcpy(type, "file"); else\r
373                 if(strcasestr(name, "path") || strcasestr(name, "directory") || strcasestr(name, "folder")) strcpy(type, "path");\r
374             }\r
375             sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
376             if(     !strcmp(type, "file")\r
377                  || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
378             else if(!strcmp(type, "spin"))   sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
379             else if(!strcmp(type, "check"))  sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
380             else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
381             else if(!strcmp(type, "combo")) {\r
382                 if(p = strstr(line+6, " default "))  sscanf(p+1, "default %s", type); // current setting\r
383                 min = 0; p = line+6;\r
384                 while(p = strstr(p, " var ")) {\r
385                     sscanf(p += 5, "%s", val); // next choice\r
386                     sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
387                 }\r
388                 strcat(q, "\"\n");\r
389             }\r
390             else buf[0] = 0; // ignore unrecognized option types\r
391             if(buf[0]) printf("%s", buf);\r
392         }\r
393         else if(!strcmp(command, "id")) {\r
394             static char name[256], version[256];\r
395             if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
396             if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);\r
397         }\r
398         else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands\r
399         else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {\r
400             char *p = varList, *q = varList;\r
401             while(*q && *q != '\n')  if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas\r
402                                 else if(!strncmp(q-1, " chess ", 7)) strcpy(p, "normal"), p += 6, q += 5; // 'chess' is called 'normal' in CECP\r
403                                 else *p++ = *q++; // copy other variant names unmodified\r
404             if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling\r
405             if(*varList) printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options\r
406             if(*egts) printf("feature egt=\"%s\"\n", egts+1);\r
407             printf("feature smp=1 memory=%d done=1\n", hasHash);\r
408             if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }\r
409             Sync(WAKEUP); // done with options\r
410         }\r
411     }\r
412 }\r
413 \r
414 void *\r
415 Engine2GUI()\r
416 {\r
417     if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");\r
418     HandleEngineOutput();\r
419 }\r
420 \r
421 void\r
422 Move4Engine(char *m)\r
423 {\r
424     if(sc == 's') {\r
425       // convert input move to USI format\r
426       if(m[1] == '@') { // drop\r
427         m[1] = '*';\r
428       } else {\r
429         m[0] = 'a'+'0'+size - m[0];\r
430         m[1] = 'a'+'0'+size - m[1];\r
431       }\r
432       m[2] = 'a'+'0'+size - m[2];\r
433       m[3] = 'a'+'0'+size - m[3];\r
434       if(m[4] == '=') m[4] = 0; // no '=' in USI format!\r
435       else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(\r
436     }\r
437 }\r
438 \r
439 int DoCommand ();\r
440 char mySide;\r
441 char queue[10000], *qStart, *qEnd;\r
442 \r
443 void\r
444 GUI2Engine()\r
445 {\r
446     char line[256], command[256], *p;\r
447 \r
448     while(1) {\r
449         int i, difficult, think=0;\r
450 \r
451         if((computer == stm || computer == ANALYZE && !searching) && !suspended) {\r
452             DPRINT("# start search\n");\r
453             LoadPos(moveNr); fflush(stdout); // load position\r
454             // and set engine thinking (note USI swaps colors!)\r
455             startTime = GetTickCount(); mySide = stm; // remember side we last played for\r
456             if(computer == ANALYZE) {\r
457                 EPRINT((f, "# go infinite")); maxDepth = mpvSP = 0;\r
458                 if(sm & 1) { // some moves are disabled\r
459                     EPRINT((f, " searchmoves"))\r
460                     for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))\r
461                 }\r
462                 EPRINT((f, "\n")) searching = 1; // suppresses spurious commands during analysis starting new searches\r
463             } else pause = think = 2, StartSearch(""); // request suspending of input processing while thinking\r
464         } else if(ponderAlways && computer == NONE) move[moveNr][0] = 0, StartPonder(moveNr-1);\r
465       nomove:\r
466        for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking\r
467         fflush(toE); fflush(stdout);\r
468         if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");\r
469         if(think && !pause) Sync(PAUSE), think = 0, Release(); // if no longer thinking, take dummy pause\r
470         sscanf(line, "%s", command); DPRINT("# '%s' think=%d pause=%d log=%d sent=%d\n", command, think, pause, logLen, sentLen);\r
471         if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first\r
472         else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  = (10*myTime)/unit;\r
473         else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;\r
474         else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly\r
475         else if(!strcmp(command, "post"))  post = 1;\r
476         else if(!strcmp(command, "nopost"))post = 0;\r
477         else if(!strcmp(command, "pause")) {\r
478             if(computer == stm) myTime -= GetTickCount() - startTime;\r
479             suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove\r
480             StopPonder(pondering || computer == stm);\r
481         }\r
482         else { //convert easy & hard to "option" after treating their effect on the adapter\r
483           if(!strcmp(command, "easy")) {\r
484             if(*canPonder) ponder = 0, sprintf(command, "option"), sprintf(line, "option %s=0\n", canPonder); else continue;\r
485           }\r
486           else if(!strcmp(command, "hard")) {\r
487             if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;\r
488           }\r
489           if(!strcmp(command, "option")) {\r
490             char *p;\r
491             if(logLen == sentLen) logLen = 0, sentLen = 0; // engine is up to date; reset buffer\r
492             if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else\r
493             if(sscanf(line+7, "ponder always=%d", &ponderAlways) == 1) ; else\r
494             if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else\r
495             if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else\r
496             if(p = strchr(line, '=')) {\r
497                 *p++ = 0;\r
498                 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
499                 snprintf(backLog+logLen, 9999-logLen, "setoption %s%s %s%s", nameWord, line+7, valueWord, p);\r
500             } else snprintf(backLog+logLen, 9999-logLen, "setoption %s%s\n", nameWord, line+7);\r
501             DPRINT("# backlog: %s", backLog+logLen); logLen += strlen(backLog+logLen);\r
502             if(!think && Release()) break; // break will restart analysis; pondering is restarted by Release itself\r
503           }\r
504           else difficult = 1; // difficult command; terminate loop for easy ones\r
505         }\r
506        } // next command\r
507 \r
508         // some commands that should never come during thinking can be safely processed here\r
509         if(difficult < 0) { // used as kludge to signal "usermove" was already matched\r
510             sscanf(line, "usermove %s", command); // strips off linefeed\r
511             Move4Engine(command);\r
512             stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;\r
513             // when pondering we either continue the ponder search as normal search, or abort it\r
514             if(pondering || computer == ANALYZE) {\r
515                 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
516                     char *draw = drawOffer ? " draw" : ""; drawOffer = 0;\r
517                     pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now\r
518                     EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);\r
519                     think = 2; // request blocking input during thinking\r
520                     goto nomove;\r
521                 }\r
522                 StopPonder(1); searching = 0;\r
523             }\r
524             strcpy(move[moveNr++], command); // possibly overwrites ponder move\r
525             continue;\r
526         }\r
527         if(!strcmp(command, "resume")) {\r
528             if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search\r
529             suspended = think = 0; continue;  // causes thinking to start in normal way if on move or analyzing\r
530         }\r
531         if(think) { // command arrived during thinking; order abort for 'instant commands'\r
532             if(!strcmp(command, "?") || !strcmp(command, "quit") ||\r
533                !strcmp(command, "force") || !strcmp(command, "result")) { EPRINT((f, "# stop\n")); fflush(toE); }\r
534             Sync(PAUSE); Release(); // block processing of difficult commands during thinking; send backlog left because of race\r
535         }\r
536         if(qStart == qEnd) qStart = qEnd = queue;\r
537         p = line; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}\r
538         if(DoCommand()) goto nomove;\r
539     }\r
540 }\r
541 \r
542 int\r
543 DoCommand ()\r
544 {\r
545     char line[1024], command[256], *p, *q, *r, type[99];\r
546     int i;\r
547 \r
548     p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;\r
549     sscanf(line, "%s", command);\r
550 \r
551         if(!strcmp(command, "new")) {\r
552             computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;\r
553             stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;\r
554             if(memory != oldMem && hasHash) EPRINT((f, "# setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory))\r
555             oldMem = memory;\r
556             // we can set other options here\r
557             if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI\r
558             if(varOpt) EPRINT((f, "# setoption name UCI_Variant value chess\n"))\r
559             pause = 1; // wait for option settings to take effect\r
560             EPRINT((f, "# isready\n")) fflush(toE);\r
561             Sync(PAUSE); // wait for readyok\r
562             EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);\r
563         }\r
564         else if(!strcmp(command, "level")) {\r
565             int sec = 0;\r
566             sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
567             sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
568             tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;\r
569         }\r
570         else if(!strcmp(command, "protover")) {\r
571             if(!varList[0]) strcpy(varList, sc=='s' ? ",shogi,5x5+5_shogi" : VARIANTS);\r
572             printf("feature setboard=1 usermove=1 debug=1 ping=1 name=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n");\r
573             printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);\r
574             printf("feature option=\"ponder always -check %d\"\n", ponderAlways);\r
575             if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);\r
576             EPRINT((f, sc == 'x' ? "# ucci\n" : "# u%ci\n", sc)) fflush(toE); // prompt UCI engine for options\r
577             Sync(PAUSE); // wait for uciok\r
578         }\r
579         else if(!strcmp(command, "setboard")) {\r
580                 stm = (strstr(line+9, " b ") ? BLACK : WHITE);\r
581                 if((p = strchr(line+9, '[')) && !varOpt) { char c;\r
582                     *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4; \r
583                     if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color\r
584                     else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)\r
585                     *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);\r
586                 } else strcpy(command, line+9);\r
587                 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC\r
588                 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);\r
589                 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);\r
590         }\r
591         else if(!strcmp(command, "variant")) {\r
592                 if(varOpt) {\r
593                     EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))\r
594                     fflush(toE); Sync(PAUSE);\r
595                 }\r
596                 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
597                 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
598                 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
599                 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) EPRINT((f, "# setoption name UCI_Chess960 value true\n")) }\r
600         }\r
601         else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
602             if(pondering || computer == ANALYZE) StopPonder(1), searching = 0;\r
603             moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;\r
604         }\r
605         else if(!strcmp(command, ".")) {\r
606             printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
607             return 1;\r
608         }\r
609         else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude\r
610             int all = !strcmp(line+8, "all"), in = command[1] == 'n';\r
611             inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag\r
612             for(i=1; i<nr; i++) { if(!strcmp(line+8, moveMap[i]) || all) on[i] = in; sm |= on[i]+1; } // sm: 2 = enabled, 1 = disabled\r
613             if(!(sm & 2)) return 1; // no moves enabled; continue current search\r
614             if(computer == ANALYZE) StopPonder(1), searching = 0; // abort old analysis\r
615         }\r
616         else if(!strcmp(command, "xboard")) ;\r
617         else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");\r
618         else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1), searching = 0, Analyze("false");\r
619         else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
620         else if(!strcmp(command, "go"))     computer = stm;\r
621         else if(!strcmp(command, "ping"))   { /* static int done; if(!done) pause = 1, fprintf(toE, "isready\n"), fflush(toE), printf("# send isready\n"), fflush(stdout), Sync(PAUSE); done = 1;*/ printf("po%s", line+2); }\r
622         else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
623         else if(!strcmp(command, "cores")&& !!*threadOpt) { sscanf(line, "cores %d", &cores); EPRINT((f, "# setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores)) }\r
624         else if(!strcmp(command, "egtpath")){\r
625             sscanf(line+8, "%s %[^\n]", type, command);\r
626             if(p = strstr(EGT, type)) strcpy(type, p), p = strchr(type, ','), *p = 0; else strcpy(type, "bitbases path");\r
627             EPRINT((f, "# setoption name %s value %s\n", type, command));\r
628         }\r
629         else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
630         else if(!strcmp(command, "st"))     sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;\r
631         else if(!strcmp(command, "name"))   { if(namOpt) EPRINT((f, "# setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5)) }\r
632         else if(!strcmp(command, "computer")) comp = 1;\r
633         else if(!strcmp(command, "result")) {\r
634             if(sc == 's') EPRINT((f, "# gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"))\r
635             computer = NONE;\r
636         }\r
637         else if(!strcmp(command, "quit"))   { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); }\r
638 \r
639     return 0;\r
640 }\r
641 \r
642 int\r
643 StartEngine(char *cmdLine, char *dir)\r
644 {\r
645 #ifdef WIN32\r
646   HANDLE hChildStdinRd, hChildStdinWr,\r
647     hChildStdoutRd, hChildStdoutWr;\r
648   BOOL fSuccess;\r
649   PROCESS_INFORMATION piProcInfo;\r
650   STARTUPINFO siStartInfo;\r
651   DWORD err;\r
652 \r
653   /* Create a pipe for the child's STDOUT. */\r
654   if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();\r
655 \r
656   /* Create a pipe for the child's STDIN. */\r
657   if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();\r
658 \r
659   SetCurrentDirectory(dir); // go to engine directory\r
660 \r
661   /* Now create the child process. */\r
662   siStartInfo.cb = sizeof(STARTUPINFO);\r
663   siStartInfo.lpReserved = NULL;\r
664   siStartInfo.lpDesktop = NULL;\r
665   siStartInfo.lpTitle = NULL;\r
666   siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
667   siStartInfo.cbReserved2 = 0;\r
668   siStartInfo.lpReserved2 = NULL;\r
669   siStartInfo.hStdInput = hChildStdinRd;\r
670   siStartInfo.hStdOutput = hChildStdoutWr;\r
671   siStartInfo.hStdError = hChildStdoutWr;\r
672 \r
673   fSuccess = CreateProcess(NULL,\r
674                            cmdLine,        /* command line */\r
675                            NULL,           /* process security attributes */\r
676                            NULL,           /* primary thread security attrs */\r
677                            TRUE,           /* handles are inherited */\r
678                            DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
679                            NULL,           /* use parent's environment */\r
680                            NULL,\r
681                            &siStartInfo, /* STARTUPINFO pointer */\r
682                            &piProcInfo); /* receives PROCESS_INFORMATION */\r
683 \r
684   if (! fSuccess) return GetLastError();\r
685 \r
686 //  if (0) { // in the future we could trigger this by an argument\r
687 //    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
688 //  }\r
689 \r
690   /* Close the handles we don't need in the parent */\r
691   CloseHandle(piProcInfo.hThread);\r
692   CloseHandle(hChildStdinRd);\r
693   CloseHandle(hChildStdoutWr);\r
694 \r
695   process = piProcInfo.hProcess;\r
696   pid = piProcInfo.dwProcessId;\r
697   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
698   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
699 #else\r
700     char *argv[10], *p, buf[200];\r
701     int i, toEngine[2], fromEngine[2];\r
702 \r
703     if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }\r
704     pipe(toEngine); pipe(fromEngine); // create two pipes\r
705 \r
706     if ((pid = fork()) == 0) { // Child\r
707         dup2(toEngine[0], 0);   close(toEngine[0]);   close(toEngine[1]);   // stdin from toE pipe\r
708         dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe\r
709         dup2(1, fileno(stderr)); // stderr into frome pipe\r
710 \r
711         strcpy(buf, cmdLine); p = buf;\r
712         for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }\r
713         argv[i] = NULL;\r
714         execvp(argv[0], argv); // startup engine\r
715         \r
716         perror(argv[0]); exit(1); // could not start engine; quit.\r
717     }\r
718     signal(SIGPIPE, SIG_IGN);\r
719     close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter\r
720     \r
721     fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O\r
722     toE   = (FILE*) fdopen(toEngine[1], "w");\r
723 #endif\r
724   return NO_ERROR;\r
725 }\r
726 \r
727 main(int argc, char **argv)\r
728 {\r
729         char *dir = NULL, *p, *q; int e;\r
730 \r
731 \r
732         if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
733         if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }\r
734         if(argc > 1 && !strcmp(argv[1], "-var")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; }\r
735         if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
736         if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }\r
737         if(argc > 2) dir = argv[2];\r
738         if(argc > 3) strncpy(suffix, argv[3], 80);\r
739 \r
740         if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords\r
741         else if(sc == 'f' ) frc = -1, sc = 'c';   // UCI for unannounced Chess960\r
742         else if(sc == 'n') sc = 'c'; // UCI for normal Chess\r
743 \r
744         // spawn engine proc\r
745         if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
746 \r
747         Sync(INIT);\r
748 \r
749         // create separate thread to handle engine->GUI traffic\r
750 #ifdef WIN32\r
751         CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
752 #else\r
753         { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }\r
754 #endif\r
755 \r
756         // handle GUI->engine traffic in original thread\r
757         GUI2Engine();\r
758 }\r