1 /************************* UCI2WB by H.G.Muller ****************************/
\r
3 #define VERSION "1.5"
\r
8 # include <windows.h>
\r
13 # include <pthread.h>
\r
14 # include <signal.h>
\r
16 # include <sys/time.h>
\r
17 int GetTickCount() // with thanks to Tord
\r
18 { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }
\r
24 #define SLEEP() Sleep(1)
\r
26 #define SLEEP() usleep(10)
\r
29 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)
\r
30 # define VARIANTS "normal,xiangqi"
\r
37 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, ponder, post, hasHash, c, sc='c', *suffix;
\r
38 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime;
\r
39 int statDepth, statScore, statNodes, statTime, currNr, size; char currMove[20]; // for analyze mode
\r
52 if(action == PAUSE) while(pause) SLEEP(); // in Windows we still rely on polling. :-(
\r
54 static int syncPipe[2]; char c;
\r
56 case INIT: pipe(syncPipe); break;
\r
57 case WAKEUP: write(syncPipe[1], "\n", 1); break;
\r
58 case PAUSE: read(syncPipe[0], &c, 1);
\r
64 StartSearch(char *ponder)
\r
65 { // send the 'go' command to engine. Suffix by ponder.
\r
66 int nr = moveNr + (ponder[0] != 0); // we ponder for one move ahead!
\r
67 fprintf(toE, "\ngo btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);
\r
68 printf( "\n# go btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);
\r
69 if(sTime > 0) fprintf(toE, " movetime %d", sTime),printf(" movetime %d", sTime); else
\r
70 if(mps) fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2),printf(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2);
\r
71 if(inc && !suffix) fprintf(toE, " winc %d binc %d", inc, inc),printf(" winc %d binc %d", inc, inc);
\r
72 if(depth > 0) fprintf(toE, " depth %d", depth),printf(" depth %d", depth);
\r
73 if(suffix) fprintf(toE, suffix, inc),printf(suffix, inc);
\r
74 fprintf(toE, "%s\n", ponder);
\r
75 printf("%s\n", ponder);
\r
79 StopPonder(int pondering)
\r
81 if(!pondering) return;
\r
83 fprintf(toE, "stop\n"); fflush(toE); printf("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
\r
84 Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.
\r
91 fprintf(toE, "%s moves", iniPos);
\r
92 printf( "# %s moves", iniPos);
\r
93 for(j=0; j<moveNr; j++) fprintf(toE, " %s", move[j]),printf(" %s", move[j]);
\r
96 char *Convert(char *pv)
\r
97 { // convert Shogi coordinates to WB
\r
99 static char buf[10000];
\r
100 if(sc != 's') return pv;
\r
103 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
\r
112 char line[1024], command[256];
\r
115 int i=0, x; char *p;
\r
117 fflush(stdout); fflush(toE);
\r
118 while((line[i] = x = fgetc(fromE)) != EOF && line[i] != '\n') i++;
\r
120 if(x == EOF) exit(0);
\r
121 printf("# engine said: %s", line); fflush(stdout);
\r
122 sscanf(line, "%s", command);
\r
123 if(!strcmp(command, "bestmove")) {
\r
124 if(pause) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
\r
125 // move was a move to be played
\r
126 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
\r
127 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
\r
128 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
\r
129 sscanf(line, "bestmove %s", move[moveNr++]);
\r
130 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
\r
131 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
\r
132 // first start a new ponder search, if pondering is on and we have a move to ponder on
\r
133 if(p = strstr(line+9, "ponder")) {
\r
134 if(computer != NONE && ponder) {
\r
135 sscanf(p+7, "%s", move[moveNr]);
\r
136 printf("# ponder on %s\n", move[moveNr]);
\r
137 LoadPos(moveNr+1); // load position
\r
138 // and set engine pondering
\r
139 pondering = 1; lastDepth = 1;
\r
140 StartSearch(" ponder");
\r
142 p[-1] = '\n'; *p = 0; // strip off ponder move
\r
145 // convert USI move to WB format
\r
146 line[11] = 'a'+'0'+size - line[11];
\r
147 line[12] = 'a'+'0'+size - line[12];
\r
148 if(line[10] == '*') { // drop
\r
151 line[9] = 'a'+'0'+size - line[9];
\r
152 line[10] = 'a'+'0'+size - line[10];
\r
153 if((stm == WHITE ? (line[10]>'0'+size-size/3 || line[12]>'0'+size-size/3)
\r
154 : (line[10] <= '0'+size/3 || line[12] <= '0'+size/3)) && line[13] != '+')
\r
155 line[13] = '=', line[14] = 0;
\r
158 printf("move %s\n", line+9); // send move to GUI
\r
159 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == WHITE ? "1-0" : "0-1"); computer = NONE; }
\r
160 stm = WHITE+BLACK - stm;
\r
162 else if(!strcmp(command, "info")) {
\r
163 int d=0, s=0, t=0, n=0;
\r
165 if(!post) continue;
\r
166 if(strstr(line, "info string ") == line) printf("%d 0 0 0 %s", lastDepth, line+12); else {
\r
167 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
\r
168 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
\r
169 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
\r
170 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
\r
171 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
\r
172 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
\r
173 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
\r
174 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
\r
175 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output
\r
176 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
\r
179 else if(!strcmp(command, "option")) { // USI option: extract data fields
\r
180 char name[80], type[80], buf[1024], val[256], *q;
\r
181 int min=0, max=1e9;
\r
182 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
\r
183 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
\r
184 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
\r
185 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
\r
186 if(p = strstr(line+6, " name ")) sscanf(p+1, "name %[^\n]*", name);
\r
187 if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {
\r
188 memory = oldMem = atoi(val); hasHash = 1;
\r
189 strcpy(hashOpt, name);
\r
192 // pass on engine-defined option as WB option feature
\r
193 if(!strcmp(type, "filename")) type[4] = 0;
\r
194 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
\r
195 if( !strcmp(type, "file")
\r
196 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
\r
197 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
\r
198 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
\r
199 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
\r
200 else if(!strcmp(type, "combo")) {
\r
201 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
\r
202 min = 0; p = line+6;
\r
203 while(p = strstr(p, " var ")) {
\r
204 sscanf(p += 5, "%s", val); // next choice
\r
205 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
\r
209 else buf[0] = 0; // ignore unrecognized option types
\r
210 if(buf[0]) printf("%s", buf);
\r
212 else if(!strcmp(command, "id")) {
\r
214 if(sscanf(line, "id name %s", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
\r
216 else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands
\r
217 else if(sscanf(command, "u%ciok", &c)==1 && c==sc) printf("feature smp=1 memory=%d done=1\n", hasHash); // done with options
\r
224 char line[256], command[256], *p, *q;
\r
229 if(computer == stm || computer == ANALYZE) {
\r
230 printf("# start search\n");
\r
231 LoadPos(moveNr); // load position
\r
232 // and set engine thinking (note USI swaps colors!)
\r
233 startTime = GetTickCount();
\r
234 if(computer == ANALYZE) fprintf(toE, "\ngo infinite\n"), printf("\ngo infinite\n");
\r
235 else StartSearch("");
\r
238 fflush(toE); fflush(stdout);
\r
239 i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;
\r
240 line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }
\r
241 sscanf(line, "%s", command);
\r
242 if(!strcmp(command, "new")) {
\r
243 computer = BLACK; moveNr = 0; depth = -1;
\r
244 stm = WHITE; strcpy(iniPos, "position startpos");
\r
245 if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s value %d\n", hashOpt, memory);
\r
247 // we can set other options here
\r
248 pause = 1; // wait for option settings to take effect
\r
249 fprintf(toE, "isready\n");
\r
250 fprintf(toE, "u%cinewgame\n", sc); fflush(toE);
\r
251 Sync(PAUSE); // wait for readyok
\r
253 else if(!strcmp(command, "usermove")) {
\r
255 // convert input move to USI format
\r
256 if(line[10] == '@') { // drop
\r
259 line[9] = 'a'+'0'+size - line[9];
\r
260 line[10] = 'a'+'0'+size - line[10];
\r
262 line[11] = 'a'+'0'+size - line[11];
\r
263 line[12] = 'a'+'0'+size - line[12];
\r
264 if(line[13] == '=') line[13] = 0; // no '=' in USI format!
\r
265 else if(line[13] != '\n') line[13] = '+'; // cater to WB 4.4 bug :-(
\r
267 sscanf(line, "usermove %s", command); // strips off linefeed
\r
268 stm = WHITE+BLACK - stm;
\r
269 // when pondering we either continue the ponder search as normal search, or abort it
\r
270 if(pondering || computer == ANALYZE) {
\r
271 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit
\r
272 pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now
\r
273 fprintf(toE, "ponderhit\n"); printf("# ponderhit\n");
\r
278 sscanf(line, "usermove %s", move[moveNr++]); // possibly overwrites ponder move
\r
280 else if(!strcmp(command, "level")) {
\r
282 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
\r
283 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
\r
284 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0;
\r
286 else if(!strcmp(command, "option")) {
\r
288 if(p = strchr(line, '=')) {
\r
290 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
\r
291 fprintf(toE, "setoption name %s value %s", line+7, p), printf("# setoption name %s value %s", line+7, p);
\r
292 } else fprintf(toE, "setoption name %s\n", line+7), printf("# setoption name %s\n", line+7);
\r
294 else if(!strcmp(command, "protover")) {
\r
295 printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 done=0\n", sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS);
\r
296 fprintf(toE, "u%ci\n", sc); // this prompts UCI engine for options
\r
298 else if(!strcmp(command, "setboard")) {
\r
299 if(strstr(line+9, " b ")) stm = BLACK;
\r
300 if(sc == 's' && (p = strchr(line+9, '['))) { char c;
\r
301 *p++ = ' '; q = strchr(p, ']'); c = 'w' + 'b' - q[2]; strcpy(q+2, " 1\n"); while(*--q != ' ') q[2] = *q; *p = c; p[1] = ' ';
\r
303 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", line+9);
\r
304 iniPos[strlen(iniPos)-1] = 0;
\r
306 else if(!strcmp(command, "variant")) {
\r
307 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
\r
308 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
\r
309 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
\r
311 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
\r
312 if(pondering || computer == ANALYZE) StopPonder(1);
\r
313 moveNr = moveNr > i ? moveNr - i : 0;
\r
315 else if(!strcmp(command, ".")) {
\r
316 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
\r
319 else if(!strcmp(command, "xboard")) ;
\r
320 else if(!strcmp(command, "analyze"))computer = ANALYZE;
\r
321 else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);
\r
322 else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);
\r
323 else if(!strcmp(command, "go")) computer = stm;
\r
324 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime *= 10;
\r
325 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime *= 10;
\r
326 else if(!strcmp(command, "post")) post = 1;
\r
327 else if(!strcmp(command, "nopost")) post = 0;
\r
328 else if(!strcmp(command, "easy")) ponder = 0;
\r
329 else if(!strcmp(command, "hard")) ponder = 1;
\r
330 else if(!strcmp(command, "ping")) pause = 1, fprintf(toE, "isready\n"), fflush(toE), Sync(PAUSE), printf("pong %s", line+5);
\r
331 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
\r
332 else if(!strcmp(command, "cores")) sscanf(line, "cores %d", &cores);
\r
333 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
\r
334 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime *= 1000, inc = 0;
\r
335 else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);
\r
340 StartEngine(char *cmdLine, char *dir)
\r
343 HANDLE hChildStdinRd, hChildStdinWr,
\r
344 hChildStdoutRd, hChildStdoutWr;
\r
345 SECURITY_ATTRIBUTES saAttr;
\r
347 PROCESS_INFORMATION piProcInfo;
\r
348 STARTUPINFO siStartInfo;
\r
351 /* Set the bInheritHandle flag so pipe handles are inherited. */
\r
352 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
\r
353 saAttr.bInheritHandle = TRUE;
\r
354 saAttr.lpSecurityDescriptor = NULL;
\r
356 /* Create a pipe for the child's STDOUT. */
\r
357 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return GetLastError();
\r
359 /* Create a pipe for the child's STDIN. */
\r
360 if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) return GetLastError();
\r
362 SetCurrentDirectory(dir); // go to engine directory
\r
364 /* Now create the child process. */
\r
365 siStartInfo.cb = sizeof(STARTUPINFO);
\r
366 siStartInfo.lpReserved = NULL;
\r
367 siStartInfo.lpDesktop = NULL;
\r
368 siStartInfo.lpTitle = NULL;
\r
369 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
\r
370 siStartInfo.cbReserved2 = 0;
\r
371 siStartInfo.lpReserved2 = NULL;
\r
372 siStartInfo.hStdInput = hChildStdinRd;
\r
373 siStartInfo.hStdOutput = hChildStdoutWr;
\r
374 siStartInfo.hStdError = hChildStdoutWr;
\r
376 fSuccess = CreateProcess(NULL,
\r
377 cmdLine, /* command line */
\r
378 NULL, /* process security attributes */
\r
379 NULL, /* primary thread security attrs */
\r
380 TRUE, /* handles are inherited */
\r
381 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
\r
382 NULL, /* use parent's environment */
\r
384 &siStartInfo, /* STARTUPINFO pointer */
\r
385 &piProcInfo); /* receives PROCESS_INFORMATION */
\r
387 if (! fSuccess) return GetLastError();
\r
389 // if (0) { // in the future we could trigger this by an argument
\r
390 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
\r
393 /* Close the handles we don't need in the parent */
\r
394 CloseHandle(piProcInfo.hThread);
\r
395 CloseHandle(hChildStdinRd);
\r
396 CloseHandle(hChildStdoutWr);
\r
398 process = piProcInfo.hProcess;
\r
399 pid = piProcInfo.dwProcessId;
\r
400 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
\r
401 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
\r
403 char *argv[10], *p, buf[200];
\r
404 int i, toEngine[2], fromEngine[2];
\r
406 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
\r
407 pipe(toEngine); pipe(fromEngine); // create two pipes
\r
409 if ((pid = fork()) == 0) { // Child
\r
410 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
\r
411 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
\r
412 dup2(1, fileno(stderr)); // stderr into frome pipe
\r
414 strcpy(buf, cmdLine); p = buf;
\r
415 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
\r
417 execvp(argv[0], argv); // startup engine
\r
419 perror(argv[0]); exit(1); // could not start engine; quit.
\r
421 signal(SIGPIPE, SIG_IGN);
\r
422 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
\r
424 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
\r
425 toE = (FILE*) fdopen(toEngine[1], "w");
\r
430 main(int argc, char **argv)
\r
432 char *dir = NULL, *p, *q; int e;
\r
434 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
\r
435 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
\r
436 if(argc < 2) { printf("usage is: U%cI2WB [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
\r
437 if(argc > 2) dir = argv[2];
\r
438 if(argc > 3) suffix = argv[3];
\r
440 // spawn engine proc
\r
441 if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
\r
445 // create separate thread to handle engine->GUI traffic
\r
447 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
\r
449 { pthread_t t; signal(SIGINT, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
\r
452 // handle GUI->engine traffic in original thread
\r