Bump version to 2.1
[uci2wb.git] / UCI2WB.c
blob94413109823e3e1baf315090729f6278f3911963
1 /****************************************************************************/
2 /* UCI2WB by H.G.Muller */
3 /* */
4 /* UCI2WB is an adapter to run engines that communicate in various dialects */
5 /* of the Universal Chess Interface in a GUI that supports XBoard protocol */
6 /* (CECP). It supports UCI (when used for Xiangqi: the 'Cyclone dialect'), */
7 /* as well as USI and UCCI when used with the flags -s or -x, respectively. */
8 /* This version of UCI2WB is released under the GNU General Public License, */
9 /* of which you should have received a copy together with this file. */
10 /****************************************************************************/
12 #define VERSION "2.1"
14 #include <stdio.h>
15 #include <stdlib.h>
16 #ifdef WIN32
17 # include <windows.h>
18 # include <io.h>
19 HANDLE process;
20 DWORD thread_id;
21 #else
22 # include <pthread.h>
23 # include <signal.h>
24 # define NO_ERROR 0
25 # include <sys/time.h>
26 int GetTickCount() // with thanks to Tord
27 { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }
28 #endif
29 #include <fcntl.h>
30 #include <string.h>
32 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)
33 # define VARIANTS "normal,xiangqi"
35 #define DPRINT if(debug) printf
37 #define WHITE 0
38 #define BLACK 1
39 #define NONE 2
40 #define ANALYZE 3
42 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], *variants;
43 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;
44 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1;
45 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20];
46 char board[100]; // XQ board for UCCI
47 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI
48 int unit = 1, drawOffer;
50 FILE *toE, *fromE, *fromF;
51 int pid;
53 #ifdef WIN32
54 WinPipe(HANDLE *hRd, HANDLE *hWr)
56 SECURITY_ATTRIBUTES saAttr;
58 /* Set the bInheritHandle flag so pipe handles are inherited. */
59 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
60 saAttr.bInheritHandle = TRUE;
61 saAttr.lpSecurityDescriptor = NULL;
63 /* Create a pipe */
64 return CreatePipe(hRd, hWr, &saAttr, 0);
66 #endif
68 #define INIT 0
69 #define WAKEUP 1
70 #define PAUSE 2
72 void
73 Sync (int action)
75 #ifdef WIN32
76 static HANDLE hWr, hRd; DWORD d; char c;
77 switch(action) {
78 case INIT: WinPipe(&hRd, &hWr); break;
79 case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;
80 case PAUSE: ReadFile(hRd, &c, 1, &d, NULL);
82 #else
83 static int syncPipe[2]; char c;
84 switch(action) {
85 case INIT: pipe(syncPipe); break;
86 case WAKEUP: write(syncPipe[1], "\n", 1); break;
87 case PAUSE: read(syncPipe[0], &c, 1);
89 #endif
92 void
93 FromFEN(char *fen)
94 { int i=0;
95 while(*fen) {
96 char c = *fen++;
97 if(c >= 'A') board[i++] = c; else
98 if(c == '/') i++; else
99 if(c == ' ') break; else
100 while(c-- > '0' && i < 99) board[i++] = 0;
101 if(i >= 99) break;
105 char *
106 ToFEN(int stm)
108 int i, n=0; static char fen[200]; char *p = fen;
109 for(i=0; i<99; i++) {
110 char c = board[i];
111 if(c >= 'A') { if(n) *p++ = '0' + n; n = 0; *p++ = c; } else n ++;
112 if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; }
114 sprintf(p-1, " %c - - 0 1", stm);
115 return fen;
119 Sqr(char *m, int j)
121 int n = m[j] - 'a' + 10*('9' - m[j+1]);
122 if(n < 0) n = 0; else if(n > 99) n = 99; return n;
126 Play(int nr)
128 int i, last = -1;
129 FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix
130 for(i=0; i<nr; i++) {
131 int from=Sqr(move[i], 0), to=Sqr(move[i], 2);
132 if(board[to] || (board[from]|32) == 'p' && move[i][1] != move[i][3]) last = i;
133 board[to] = board[from]; board[from] = 0;
135 return last;
138 void
139 StartSearch(char *ponder)
140 { // send the 'go' command to engine. Suffix by ponder.
141 int x = (ponder[0] != 0); // during ponder stm is the opponent
142 int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black
143 int nr = moveNr + x; // we ponder for one move ahead!
144 if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent
145 if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering
146 fprintf(toE, "\ngo%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);
147 DPRINT( "\n# go%s %stime %d %stime %d", ponder, bTime, black ? myTime : hisTime, wTime, !black ? myTime : hisTime);
148 if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else
149 if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }
150 if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", byo >=0 ? 1000*byo : inc + myTime/40); // for engines running purely on byoyomi
151 if(inc && !*suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }
152 if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }
153 if(*suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }
154 fprintf(toE, "\n"); DPRINT("\n");
157 void
158 StopPonder(int pondering)
160 if(!pondering) return;
161 pause = 1;
162 fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
163 Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.
166 void
167 LoadPos(int moveNr)
169 int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;
170 if(sc == 'x') { // UCCI: send only reversible moves
171 lastCapt = Play(moveNr); // find last capture (returns -1 if none!)
172 Play(++lastCapt); // reconstruct board after last capture
173 stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b');
174 sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)
176 fprintf(toE, "%s moves", pos);
177 DPRINT( "# %s moves", pos);
178 for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }
181 void
182 StartPonder()
184 if(!move[moveNr][0]) return; // no ponder move
185 LoadPos(moveNr+1);
186 pondering = 1; lastDepth = 1;
187 StartSearch(" ponder");
190 char *Convert(char *pv)
191 { // convert Shogi coordinates to WB
192 char *p, *q, c;
193 static char buf[10000];
194 if(sc != 's') return pv;
195 p = pv; q = buf;
196 while(c = *p++) {
197 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
199 *q++ = 0;
200 return buf;
203 void
204 Move4GUI(char *m)
206 if(sc == 's') {
207 // convert USI move to WB format
208 m[2] = 'a'+'0'+size - m[2];
209 m[3] = 'a'+'0'+size - m[3];
210 if(m[1] == '*') { // drop
211 m[1] = '@';
212 } else {
213 m[0] = 'a'+'0'+size - m[0];
214 m[1] = 'a'+'0'+size - m[1];
215 if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)
216 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')
217 m[4] = '=', m[5] = 0;
223 GetChar()
225 int c;
226 if(fromF) {
227 if((c = fgetc(fromF)) != EOF) return c;
228 fclose(fromF); fromF = 0; printf("# end fake\n");
230 return fgetc(fromE);
233 void *
234 Engine2GUI()
236 char line[1024], command[256];
238 if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
239 while(1) {
240 int i=0, x; char *p, dummy;
242 fflush(stdout); fflush(toE);
243 while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;
244 line[++i] = 0;
245 if(x == EOF) exit(0);
246 DPRINT("# engine said: %s", line), fflush(stdout);
247 if(sscanf(line, "%s", command) != 1) continue;
248 if(!strcmp(command, "bestmove")) {
249 if(pause == 1) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
250 else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search
251 // move was a move to be played
252 if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI
253 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
254 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
255 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
256 sscanf(line, "bestmove %s", move[moveNr++]);
257 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
258 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
259 stm = WHITE+BLACK - stm;
260 // first start a new ponder search, if pondering is on and we have a move to ponder on
261 if(p = strstr(line+9, "ponder")) {
262 sscanf(p+7, "%s", move[moveNr]);
263 if(computer != NONE && ponder) {
264 DPRINT("# ponder on %s\n", move[moveNr]);
265 StartPonder();
267 p[-1] = '\n'; *p = 0; // strip off ponder move
268 } else move[moveNr][0] = 0;
269 Move4GUI(line+9);
270 printf("move %s\n", line+9); // send move to GUI
271 if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);
272 if(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think
273 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }
275 else if(!strcmp(command, "info")) {
276 int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;
277 char *pv;
278 if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }
279 if(collect && (pv = strstr(line+5, "currmove "))) {
280 if(p = strstr(line+5, "currmovenumber ")) {
281 n = atoi(p+15);
282 if(collect == 1 && n != 1) continue; // wait for move 1
283 if(collect + (n == 1) > 2) { // done collecting
284 if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);
285 collect = 3; continue;
287 collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move
290 if(!post) continue;
291 if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {
292 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
293 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
294 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
295 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
296 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
297 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
298 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
299 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
300 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output
301 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
304 else if(!strcmp(command, "option")) { // USI option: extract data fields
305 char name[80], type[80], buf[1024], val[256], *q;
306 int min=0, max=1e9;
307 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
308 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
309 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
310 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
311 if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI
312 if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }
313 if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {
314 fprintf(toE, "setoption name %s value true\n", name); strcpy(val, "true"); // set non-standard suspected FRC options
316 if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }
317 if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }
318 if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {
319 memory = oldMem = atoi(val); hasHash = 1;
320 strcpy(hashOpt, name);
321 continue;
323 if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }
324 if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }
325 // pass on engine-defined option as WB option feature
326 if(!strcmp(type, "filename")) type[4] = 0;
327 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
328 if( !strcmp(type, "file")
329 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
330 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
331 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
332 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
333 else if(!strcmp(type, "combo")) {
334 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
335 min = 0; p = line+6;
336 while(p = strstr(p, " var ")) {
337 sscanf(p += 5, "%s", val); // next choice
338 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
340 strcat(q, "\"\n");
342 else buf[0] = 0; // ignore unrecognized option types
343 if(buf[0]) printf("%s", buf);
345 else if(!strcmp(command, "id")) {
346 static char name[256], version[256];
347 if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
348 if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);
350 else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands
351 else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {
352 if(frc) printf("feature variants=\"normal,fischerandom\" oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling
353 printf("feature smp=1 memory=%d done=1\n", hasHash);
354 if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");
355 Sync(WAKEUP); // done with options
360 void
361 Move4Engine(char *m)
363 if(sc == 's') {
364 // convert input move to USI format
365 if(m[1] == '@') { // drop
366 m[1] = '*';
367 } else {
368 m[0] = 'a'+'0'+size - m[0];
369 m[1] = 'a'+'0'+size - m[1];
371 m[2] = 'a'+'0'+size - m[2];
372 m[3] = 'a'+'0'+size - m[3];
373 if(m[4] == '=') m[4] = 0; // no '=' in USI format!
374 else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(
378 void
379 GUI2Engine()
381 char line[256], command[256], *p, *q, *r;
383 while(1) {
384 int i, x;
386 if((computer == stm || computer == ANALYZE) && !suspended) {
387 DPRINT("# start search\n");
388 LoadPos(moveNr); fflush(stdout); // load position
389 // and set engine thinking (note USI swaps colors!)
390 startTime = GetTickCount();
391 if(computer == ANALYZE) {
392 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");
393 if(sm & 1) { // some moves are disabled
394 fprintf(toE, " searchmoves"); DPRINT(" searchmoves");
395 for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }
397 fprintf(toE, "\n"); DPRINT("\n");
398 // code for searchmoves goes here
399 } else { pause = 2; StartSearch(""); fflush(stdout); fflush(toE); Sync(PAUSE); } // block input during thinking
401 nomove:
402 fflush(toE); fflush(stdout);
403 i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;
404 line[++i] = 0; if(x == EOF) { printf("# EOF\n"); fprintf(toE, "quit\n"); exit(-1); }
405 sscanf(line, "%s", command);
406 if(!strcmp(command, "new")) {
407 computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;
408 stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;
409 if(memory != oldMem && hasHash) fprintf(toE, "setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory);
410 oldMem = memory;
411 // we can set other options here
412 if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI
413 pause = 1; // wait for option settings to take effect
414 fprintf(toE, "isready\n"); fflush(toE);
415 Sync(PAUSE); // wait for readyok
416 fprintf(toE, "u%cinewgame\n", sc); fflush(toE);
418 else if(!strcmp(command, "usermove")) {
419 sscanf(line, "usermove %s", command); // strips off linefeed
420 Move4Engine(command);
421 stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;
422 // when pondering we either continue the ponder search as normal search, or abort it
423 if(pondering || computer == ANALYZE) {
424 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit
425 char *draw = drawOffer ? " draw" : ""; drawOffer = 0;
426 pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now
427 fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw); fflush(toE); fflush(stdout);
428 Sync(PAUSE); // block input during thinking
429 goto nomove;
431 StopPonder(1);
433 strcpy(move[moveNr++], command); // possibly overwrites ponder move
435 else if(!strcmp(command, "level")) {
436 int sec = 0;
437 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
438 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
439 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;
441 else if(!strcmp(command, "option")) {
442 char name[80], *p;
443 if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else
444 if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else
445 if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else
446 if(p = strchr(line, '=')) {
447 *p++ = 0;
448 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
449 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);
450 } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }
452 else if(!strcmp(command, "protover")) {
453 if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;
454 printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n", variants);
455 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);
456 if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\" option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);
457 fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options
458 Sync(PAUSE); // wait for uciok
460 else if(!strcmp(command, "setboard")) {
461 stm = (strstr(line+9, " b ") ? BLACK : WHITE);
462 if(p = strchr(line+9, '[')) { char c;
463 *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4;
464 if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color
465 else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
466 *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);
467 } else strcpy(command, line+9);
468 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC
469 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);
470 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);
472 else if(!strcmp(command, "variant")) {
473 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
474 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
475 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
476 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) fprintf(toE, "setoption name UCI_Chess960 value true\n"); }
478 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
479 if(pondering || computer == ANALYZE) StopPonder(1);
480 moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;
482 else if(!strcmp(command, ".")) {
483 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
484 goto nomove;
486 else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude
487 int all = !strcmp(line+8, "all"), in = command[1] == 'n';
488 inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag
489 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
490 if(!(sm & 2)) goto nomove; // no moves enabled; continue current search
491 if(computer == ANALYZE) StopPonder(1); // abort old analysis
493 else if(!strcmp(command, "pause")) {
494 if(computer == stm) myTime -= GetTickCount() - startTime;
495 suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove
496 StopPonder(pondering || computer == stm);
498 else if(!strcmp(command, "resume")) {
499 if(suspended == 2) StartPonder(); // restart interrupted ponder search
500 suspended = 0; // causes thinking to start in normal way if on move or analyzing
502 else if(!strcmp(command, "xboard")) ;
503 else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;
504 else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);
505 else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);
506 else if(!strcmp(command, "go")) computer = stm;
507 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime = (10*myTime)/unit;
508 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;
509 else if(!strcmp(command, "post")) post = 1;
510 else if(!strcmp(command, "nopost")) post = 0;
511 else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);
512 else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();
513 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); }
514 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
515 else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);
516 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
517 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;
518 else if(!strcmp(command, "offer")) drawOffer = 1;
519 else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);
524 StartEngine(char *cmdLine, char *dir)
526 #ifdef WIN32
527 HANDLE hChildStdinRd, hChildStdinWr,
528 hChildStdoutRd, hChildStdoutWr;
529 BOOL fSuccess;
530 PROCESS_INFORMATION piProcInfo;
531 STARTUPINFO siStartInfo;
532 DWORD err;
534 /* Create a pipe for the child's STDOUT. */
535 if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();
537 /* Create a pipe for the child's STDIN. */
538 if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();
540 SetCurrentDirectory(dir); // go to engine directory
542 /* Now create the child process. */
543 siStartInfo.cb = sizeof(STARTUPINFO);
544 siStartInfo.lpReserved = NULL;
545 siStartInfo.lpDesktop = NULL;
546 siStartInfo.lpTitle = NULL;
547 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
548 siStartInfo.cbReserved2 = 0;
549 siStartInfo.lpReserved2 = NULL;
550 siStartInfo.hStdInput = hChildStdinRd;
551 siStartInfo.hStdOutput = hChildStdoutWr;
552 siStartInfo.hStdError = hChildStdoutWr;
554 fSuccess = CreateProcess(NULL,
555 cmdLine, /* command line */
556 NULL, /* process security attributes */
557 NULL, /* primary thread security attrs */
558 TRUE, /* handles are inherited */
559 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
560 NULL, /* use parent's environment */
561 NULL,
562 &siStartInfo, /* STARTUPINFO pointer */
563 &piProcInfo); /* receives PROCESS_INFORMATION */
565 if (! fSuccess) return GetLastError();
567 // if (0) { // in the future we could trigger this by an argument
568 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
569 // }
571 /* Close the handles we don't need in the parent */
572 CloseHandle(piProcInfo.hThread);
573 CloseHandle(hChildStdinRd);
574 CloseHandle(hChildStdoutWr);
576 process = piProcInfo.hProcess;
577 pid = piProcInfo.dwProcessId;
578 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
579 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
580 #else
581 char *argv[10], *p, buf[200];
582 int i, toEngine[2], fromEngine[2];
584 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
585 pipe(toEngine); pipe(fromEngine); // create two pipes
587 if ((pid = fork()) == 0) { // Child
588 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
589 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
590 dup2(1, fileno(stderr)); // stderr into frome pipe
592 strcpy(buf, cmdLine); p = buf;
593 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
594 argv[i] = NULL;
595 execvp(argv[0], argv); // startup engine
597 perror(argv[0]); exit(1); // could not start engine; quit.
599 signal(SIGPIPE, SIG_IGN);
600 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
602 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
603 toE = (FILE*) fdopen(toEngine[1], "w");
604 #endif
605 return NO_ERROR;
608 main(int argc, char **argv)
610 char *dir = NULL, *p, *q; int e;
612 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
613 if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }
614 if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }
615 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
616 if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
617 if(argc > 2) dir = argv[2];
618 if(argc > 3) strncpy(suffix, argv[3], 80);
620 if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords
621 else if(sc == 'f' ) frc = -1, sc = 'c'; // UCI for unannounced Chess960
622 else if(sc == 'n') sc = 'c'; // UCI for normal Chess
624 // spawn engine proc
625 if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
627 Sync(INIT);
629 // create separate thread to handle engine->GUI traffic
630 #ifdef WIN32
631 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
632 #else
633 { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
634 #endif
636 // handle GUI->engine traffic in original thread
637 GUI2Engine();