c6eb94960bce870a672ea9a578fed0c769bc1d0c
[uci2wb.git] / UCI2WB.c
1 /************************* UCI2WB by H.G.Muller ****************************/\r
2 \r
3 #define VERSION "1.5"\r
4 \r
5 #include <stdio.h>\r
6 #include <windows.h>\r
7 #include <io.h>\r
8 #include <fcntl.h>\r
9 \r
10 #ifdef _MSC_VER \r
11 #define SLEEP() Sleep(1) \r
12 #else \r
13 #define SLEEP() usleep(10) \r
14 #endif \r
15 \r
16 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
17 #  define VARIANTS "normal,xiangqi"\r
18 \r
19 #define WHITE 0\r
20 #define BLACK 1\r
21 #define NONE  2\r
22 #define ANALYZE 3\r
23 \r
24 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, ponder, post, hasHash, c, sc='c', *suffix;\r
25 int mps, tc, inc, stime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime;\r
26 int statDepth, statScore, statNodes, statTime, currNr, size; char currMove[20]; // for analyze mode\r
27 \r
28 FILE *toE, *fromE;\r
29 HANDLE process;\r
30 int pid;\r
31 DWORD thread_id;\r
32 \r
33 void\r
34 StartSearch(char *ponder)\r
35 {       // send the 'go' command to engine. Suffix by ponder.\r
36         int nr = moveNr + (ponder[0] != 0); // we ponder for one move ahead!\r
37         fprintf(toE, "\ngo btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);\r
38         printf(    "\n# go btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);\r
39         if(stime > 0) fprintf(toE, " movetime %d", stime),printf(" movetime %d", stime); else\r
40         if(mps) fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2),printf(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2);\r
41         if(inc && !suffix) fprintf(toE, " winc %d binc %d", inc, inc),printf(" winc %d binc %d", inc, inc);\r
42         if(depth > 0) fprintf(toE, " depth %d", depth),printf(" depth %d", depth);\r
43         if(suffix) fprintf(toE, suffix, inc),printf(suffix, inc);\r
44         fprintf(toE, "%s\n", ponder);\r
45         printf("%s\n", ponder);\r
46 }\r
47 \r
48 void\r
49 StopPonder(int pondering)\r
50 {\r
51         if(!pondering) return;\r
52         pause = 1;\r
53         fprintf(toE, "stop\n");printf("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
54         while(pause) SLEEP(); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
55 }\r
56 \r
57 void\r
58 LoadPos(int moveNr)\r
59 {\r
60         int j;\r
61         fprintf(toE, "%s moves", iniPos);\r
62         printf(    "# %s moves", iniPos);\r
63         for(j=0; j<moveNr; j++) fprintf(toE, " %s", move[j]),printf(" %s", move[j]);\r
64 }\r
65 \r
66 char *Convert(char *pv)\r
67 {   // convert Shogi coordinates to WB\r
68     char *p, *q, c;\r
69     static char buf[10000];\r
70     if(sc != 's') return pv;\r
71     p = pv; q = buf;\r
72     while(c = *p++) {\r
73         if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
74     }\r
75     *q++ = 0;\r
76     return buf;\r
77 }\r
78 \r
79 void\r
80 Engine2GUI()\r
81 {\r
82     char line[1024], command[256];\r
83 \r
84     while(1) {\r
85         int i=0, x; char *p;\r
86 \r
87         fflush(stdout); fflush(toE);\r
88         while((line[i] = x = fgetc(fromE)) != EOF && line[i] != '\n') i++;\r
89         line[++i] = 0;\r
90         if(x == EOF) exit(0);\r
91 printf("# engine said: %s", line);\r
92         sscanf(line, "%s", command);\r
93         if(!strcmp(command, "bestmove")) {\r
94             if(pause) { pondering = pause = 0; continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
95             // move was a move to be played\r
96             if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
97             if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
98                strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
99             sscanf(line, "bestmove %s", move[moveNr++]);\r
100             myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
101             if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(stime) myTime = stime; // new session or move starts\r
102             // first start a new ponder search, if pondering is on and we have a move to ponder on\r
103             if(p = strstr(line+9, "ponder")) {\r
104               if(computer != NONE && ponder) {\r
105                 sscanf(p+7, "%s", move[moveNr]);\r
106 printf("# ponder on %s\n", move[moveNr]);\r
107                 LoadPos(moveNr+1); // load position\r
108                 // and set engine pondering\r
109                 pondering = 1; lastDepth = 1;\r
110                 StartSearch(" ponder");\r
111               }\r
112               p[-1] = '\n'; *p = 0; // strip off ponder move\r
113             }\r
114             if(sc == 's') {\r
115               // convert USI move to WB format\r
116               line[11] = 'a'+'0'+size - line[11];\r
117               line[12] = 'a'+'0'+size - line[12];\r
118               if(line[10] == '*') { // drop\r
119                 line[10] = '@';\r
120               } else {\r
121                 line[9]  = 'a'+'0'+size - line[9];\r
122                 line[10] = 'a'+'0'+size - line[10];\r
123                 if((stm == WHITE ? (line[10]>'0'+size-size/3 || line[12]>'0'+size-size/3)\r
124                                  : (line[10] <= '0'+size/3 || line[12] <= '0'+size/3)) && line[13] != '+')\r
125                      line[13] = '=', line[14] = 0;\r
126               }\r
127             }\r
128             printf("move %s\n", line+9); // send move to GUI\r
129             if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == WHITE ? "1-0" : "0-1"); computer = NONE; }\r
130             stm = WHITE+BLACK - stm;\r
131         }\r
132         else if(!strcmp(command, "info")) {\r
133             int d=0, s=0, t=0, n=0;\r
134             char *pv;\r
135             if(!post) continue;\r
136             if(strstr(line, "info string ") == line) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
137                 if(p = strstr(line+4, " depth "))      sscanf(p+7, "%d", &d), statDepth = d;\r
138                 if(p = strstr(line+4, " score cp "))   sscanf(p+10, "%d", &s), statScore = s; else\r
139                 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else\r
140                 if(p = strstr(line+4, " score "))      sscanf(p+7, "%d", &s), statScore = s;\r
141                 if(p = strstr(line+4, " nodes "))      sscanf(p+7, "%d", &n), statNodes = n;\r
142                 if(p = strstr(line+4, " time "))       sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
143                 if(p = strstr(line+4, " currmove "))   sscanf(p+10,"%s", currMove);\r
144                 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);\r
145                 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output\r
146                     printf("%3d  %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
147             }\r
148         }\r
149         else if(!strcmp(command, "option")) { // USI option: extract data fields\r
150             char name[80], type[80], buf[1024], val[256], *q;\r
151             int min=0, max=1e9;\r
152             if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
153             if(p = strstr(line+6, " min "))  sscanf(p+1, "min %d", &min), *p = '\n';\r
154             if(p = strstr(line+6, " max "))  sscanf(p+1, "max %d", &max), *p = '\n';\r
155             if(p = strstr(line+6, " default "))  sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
156             if(p = strstr(line+6, " name ")) sscanf(p+1, "name %[^\n]*", name);\r
157             if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {\r
158                 memory = oldMem = atoi(val); hasHash = 1; \r
159                 strcpy(hashOpt, name);\r
160                 continue;\r
161             }\r
162             // pass on engine-defined option as WB option feature\r
163             if(!strcmp(type, "filename")) type[4] = 0;\r
164             sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
165             if(     !strcmp(type, "file")\r
166                  || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
167             else if(!strcmp(type, "spin"))   sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
168             else if(!strcmp(type, "check"))  sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
169             else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
170             else if(!strcmp(type, "combo")) {\r
171                 if(p = strstr(line+6, " default "))  sscanf(p+1, "default %s", type); // current setting\r
172                 min = 0; p = line+6;\r
173                 while(p = strstr(p, " var ")) {\r
174                     sscanf(p += 5, "%s", val); // next choice\r
175                     sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
176                 }\r
177                 strcat(q, "\"\n");\r
178             }\r
179             else buf[0] = 0; // ignore unrecognized option types\r
180             if(buf[0]) printf("%s", buf);\r
181         }\r
182         else if(!strcmp(command, "id")) {\r
183             char name[256];\r
184             if(sscanf(line, "id name %s", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
185         }\r
186         else if(!strcmp(command, "readyok")) pause = 0; // resume processing of GUI commands\r
187         else if(sscanf(command, "u%ciok", &c)==1 && c==sc)   printf("feature smp=1 memory=%d done=1\n", hasHash); // done with options\r
188     }\r
189 }\r
190 \r
191 void\r
192 GUI2Engine()\r
193 {\r
194     char line[256], command[256], *p, *q;\r
195 \r
196     while(1) {\r
197         int i, x;\r
198 \r
199         if(computer == stm || computer == ANALYZE) {\r
200 printf("# start search\n");\r
201             LoadPos(moveNr); // load position\r
202             // and set engine thinking (note USI swaps colors!)\r
203             startTime = GetTickCount();\r
204             if(computer == ANALYZE) fprintf(toE, "\ngo infinite\n"), printf("\ngo infinite\n");\r
205             else StartSearch("");\r
206         }\r
207       nomove:\r
208         fflush(toE); fflush(stdout);\r
209         i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
210         line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }\r
211         sscanf(line, "%s", command);\r
212         while(pause) SLEEP(); // wait for readyok\r
213         if(!strcmp(command, "new")) {\r
214             computer = BLACK; moveNr = 0; depth = -1;\r
215             stm = WHITE; strcpy(iniPos, "position startpos");\r
216             if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s value %d\n", hashOpt, memory);\r
217             oldMem = memory;\r
218             // we can set other options here\r
219             pause = 1; // wait for option settings to take effect\r
220             fprintf(toE, "isready\n");\r
221             fprintf(toE, "u%cinewgame\n", sc);\r
222         }\r
223         else if(!strcmp(command, "usermove")) {\r
224             if(sc == 's') {\r
225               // convert input move to USI format\r
226               if(line[10] == '@') { // drop\r
227                 line[10] = '*';\r
228               } else {\r
229                 line[9]  = 'a'+'0'+size - line[9];\r
230                 line[10] = 'a'+'0'+size - line[10];\r
231               }\r
232               line[11] = 'a'+'0'+size - line[11];\r
233               line[12] = 'a'+'0'+size - line[12];\r
234               if(line[13] == '=') line[13] = 0; // no '=' in USI format!\r
235               else if(line[13] != '\n') line[13] = '+'; // cater to WB 4.4 bug :-(\r
236             }\r
237             sscanf(line, "usermove %s", command); // strips off linefeed\r
238             stm = WHITE+BLACK - stm;\r
239             // when pondering we either continue the ponder search as normal search, or abort it\r
240             if(pondering || computer == ANALYZE) {\r
241                 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
242                     pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
243                     fprintf(toE, "ponderhit\n"); printf("# ponderhit\n");\r
244                     goto nomove;\r
245                 }\r
246                 StopPonder(1);\r
247             }\r
248             sscanf(line, "usermove %s", move[moveNr++]); // possibly overwrites ponder move\r
249         }\r
250         else if(!strcmp(command, "level")) {\r
251             int sec = 0;\r
252             sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
253             sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
254             tc = (60*tc + sec)*1000; inc *= 1000; stime = 0;\r
255         }\r
256         else if(!strcmp(command, "option")) {\r
257             char name[80], *p;\r
258             if(p = strchr(line, '=')) {\r
259                 *p++ = 0;\r
260                 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
261                 fprintf(toE, "setoption name %s value %s", line+7, p), printf("# setoption name %s value %s", line+7, p);\r
262             } else fprintf(toE, "setoption name %s\n", line+7), printf("# setoption name %s\n", line+7);\r
263         }\r
264         else if(!strcmp(command, "protover")) {\r
265             printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 reuse=0 done=0\n", sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS);\r
266             fprintf(toE, "u%ci\n", sc); // this prompts UCI engine for options\r
267         }\r
268         else if(!strcmp(command, "setboard")) {\r
269                 if(strstr(line+9, " b ")) stm = BLACK;\r
270                 if(sc == 's' && (p = strchr(line+9, '['))) { char c;\r
271                     *p++ = ' '; q = strchr(p, ']'); c = 'w' + 'b' - q[2]; strcpy(q+2, " 1\n"); while(*--q != ' ') q[2] = *q; *p = c; p[1] = ' '; \r
272                 }\r
273                 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", line+9);\r
274                 iniPos[strlen(iniPos)-1] = 0;\r
275         }\r
276         else if(!strcmp(command, "variant")) {\r
277                 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
278                 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
279                 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
280         }\r
281         else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
282             if(pondering || computer == ANALYZE) StopPonder(1);\r
283             moveNr = moveNr > i ? moveNr - i : 0;\r
284         }\r
285         else if(!strcmp(command, ".")) {\r
286             printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
287             goto nomove;\r
288         }\r
289         else if(!strcmp(command, "xboard")) ;\r
290         else if(!strcmp(command, "analyze"))computer = ANALYZE;\r
291         else if(!strcmp(command, "exit"))   computer = NONE, StopPonder(1);\r
292         else if(!strcmp(command, "force"))  computer = NONE, StopPonder(pondering);\r
293         else if(!strcmp(command, "go"))     computer = stm;\r
294         else if(!strcmp(command, "time"))   sscanf(line+4, "%d", &myTime),  myTime  *= 10;\r
295         else if(!strcmp(command, "otim"))   sscanf(line+4, "%d", &hisTime), hisTime *= 10;\r
296         else if(!strcmp(command, "post"))   post = 1;\r
297         else if(!strcmp(command, "nopost")) post = 0;\r
298         else if(!strcmp(command, "easy"))   ponder = 0;\r
299         else if(!strcmp(command, "hard"))   ponder = 1;\r
300         else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
301         else if(!strcmp(command, "cores"))  sscanf(line, "cores %d", &cores);\r
302         else if(!strcmp(command, "sd"))     sscanf(line, "sd %d", &depth);\r
303         else if(!strcmp(command, "st"))     sscanf(line, "st %d", &stime), stime *= 1000, inc = 0;\r
304         else if(!strcmp(command, "quit"))   fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
305     }\r
306 }\r
307 \r
308 int\r
309 StartEngine(char *cmdLine, char *dir)\r
310 {\r
311   HANDLE hChildStdinRd, hChildStdinWr,\r
312     hChildStdoutRd, hChildStdoutWr;\r
313   SECURITY_ATTRIBUTES saAttr;\r
314   BOOL fSuccess;\r
315   PROCESS_INFORMATION piProcInfo;\r
316   STARTUPINFO siStartInfo;\r
317   DWORD err;\r
318 \r
319   /* Set the bInheritHandle flag so pipe handles are inherited. */\r
320   saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
321   saAttr.bInheritHandle = TRUE;\r
322   saAttr.lpSecurityDescriptor = NULL;\r
323 \r
324   /* Create a pipe for the child's STDOUT. */\r
325   if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return GetLastError();\r
326 \r
327   /* Create a pipe for the child's STDIN. */\r
328   if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) return GetLastError();\r
329 \r
330   SetCurrentDirectory(dir); // go to engine directory\r
331 \r
332   /* Now create the child process. */\r
333   siStartInfo.cb = sizeof(STARTUPINFO);\r
334   siStartInfo.lpReserved = NULL;\r
335   siStartInfo.lpDesktop = NULL;\r
336   siStartInfo.lpTitle = NULL;\r
337   siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
338   siStartInfo.cbReserved2 = 0;\r
339   siStartInfo.lpReserved2 = NULL;\r
340   siStartInfo.hStdInput = hChildStdinRd;\r
341   siStartInfo.hStdOutput = hChildStdoutWr;\r
342   siStartInfo.hStdError = hChildStdoutWr;\r
343 \r
344   fSuccess = CreateProcess(NULL,\r
345                            cmdLine,        /* command line */\r
346                            NULL,           /* process security attributes */\r
347                            NULL,           /* primary thread security attrs */\r
348                            TRUE,           /* handles are inherited */\r
349                            DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
350                            NULL,           /* use parent's environment */\r
351                            NULL,\r
352                            &siStartInfo, /* STARTUPINFO pointer */\r
353                            &piProcInfo); /* receives PROCESS_INFORMATION */\r
354 \r
355   if (! fSuccess) return GetLastError();\r
356 \r
357 //  if (0) { // in the future we could trigger this by an argument\r
358 //    SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
359 //  }\r
360 \r
361   /* Close the handles we don't need in the parent */\r
362   CloseHandle(piProcInfo.hThread);\r
363   CloseHandle(hChildStdinRd);\r
364   CloseHandle(hChildStdoutWr);\r
365 \r
366   process = piProcInfo.hProcess;\r
367   pid = piProcInfo.dwProcessId;\r
368   fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
369   toE   = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
370 \r
371   return NO_ERROR;\r
372 }\r
373 \r
374 main(int argc, char **argv)\r
375 {\r
376         char *dir = NULL, *p, *q; int e;\r
377 \r
378         if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
379         if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
380         if(argc < 2) { printf("usage is: U%cI2WB [-s] <engine.exe> [<engine directory>]", sc-32); exit(-1); }\r
381         if(argc > 2) dir = argv[2];\r
382         if(argc > 3) suffix = argv[3];\r
383 \r
384         // spawn engine proc\r
385         if((errno = StartEngine(argv[1], dir)) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
386 \r
387         // create separate thread to handle engine->GUI traffic\r
388         CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
389 \r
390         // handle GUI->engine traffic in original thread\r
391         GUI2Engine();\r
392 }\r