Supply time and node count for engines that do not give it
[uci2wb.git] / UCI2WB.c
blob29d4040d253ca82a83282e7320b75ea60cd9a201
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.0"
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, *variants;
43 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug;
44 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc;
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(inc && !suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }
151 if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }
152 if(suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }
153 fprintf(toE, "\n"); DPRINT("\n");
156 void
157 StopPonder(int pondering)
159 if(!pondering) return;
160 pause = 1;
161 fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
162 Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.
165 void
166 LoadPos(int moveNr)
168 int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;
169 if(sc == 'x') { // UCCI: send only reversible moves
170 lastCapt = Play(moveNr); // find last capture (returns -1 if none!)
171 Play(++lastCapt); // reconstruct board after last capture
172 stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b');
173 sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)
175 fprintf(toE, "%s moves", pos);
176 DPRINT( "# %s moves", pos);
177 for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }
180 void
181 StartPonder()
183 if(!move[moveNr][0]) return; // no ponder move
184 LoadPos(moveNr+1);
185 pondering = 1; lastDepth = 1;
186 StartSearch(" ponder");
189 char *Convert(char *pv)
190 { // convert Shogi coordinates to WB
191 char *p, *q, c;
192 static char buf[10000];
193 if(sc != 's') return pv;
194 p = pv; q = buf;
195 while(c = *p++) {
196 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
198 *q++ = 0;
199 return buf;
202 void
203 Move4GUI(char *m)
205 if(sc == 's') {
206 // convert USI move to WB format
207 m[2] = 'a'+'0'+size - m[2];
208 m[3] = 'a'+'0'+size - m[3];
209 if(m[1] == '*') { // drop
210 m[1] = '@';
211 } else {
212 m[0] = 'a'+'0'+size - m[0];
213 m[1] = 'a'+'0'+size - m[1];
214 if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)
215 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')
216 m[4] = '=', m[5] = 0;
222 GetChar()
224 int c;
225 if(fromF) {
226 if((c = fgetc(fromF)) != EOF) return c;
227 fclose(fromF); fromF = 0; printf("# end fake\n");
229 return fgetc(fromE);
232 void *
233 Engine2GUI()
235 char line[1024], command[256];
237 if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
238 while(1) {
239 int i=0, x; char *p, dummy;
241 fflush(stdout); fflush(toE);
242 while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;
243 line[++i] = 0;
244 if(x == EOF) exit(0);
245 DPRINT("# engine said: %s", line), fflush(stdout);
246 if(sscanf(line, "%s", command) != 1) continue;
247 if(!strcmp(command, "bestmove")) {
248 if(pause == 1) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
249 else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search
250 // move was a move to be played
251 if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI
252 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
253 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
254 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
255 sscanf(line, "bestmove %s", move[moveNr++]);
256 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
257 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
258 stm = WHITE+BLACK - stm;
259 // first start a new ponder search, if pondering is on and we have a move to ponder on
260 if(p = strstr(line+9, "ponder")) {
261 sscanf(p+7, "%s", move[moveNr]);
262 if(computer != NONE && ponder) {
263 DPRINT("# ponder on %s\n", move[moveNr]);
264 StartPonder();
266 p[-1] = '\n'; *p = 0; // strip off ponder move
267 } else move[moveNr][0] = 0;
268 Move4GUI(line+9);
269 printf("move %s\n", line+9); // send move to GUI
270 if(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think
271 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }
273 else if(!strcmp(command, "info")) {
274 int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;
275 char *pv;
276 if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }
277 if(collect && (pv = strstr(line+5, "currmove "))) {
278 if(p = strstr(line+5, "currmovenumber ")) {
279 n = atoi(p+15);
280 if(collect == 1 && n != 1) continue; // wait for move 1
281 if(collect + (n == 1) > 2) { // done collecting
282 if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);
283 collect = 3; continue;
285 collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move
288 if(!post) continue;
289 if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {
290 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
291 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
292 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
293 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
294 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
295 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
296 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
297 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
298 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output
299 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
302 else if(!strcmp(command, "option")) { // USI option: extract data fields
303 char name[80], type[80], buf[1024], val[256], *q;
304 int min=0, max=1e9;
305 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
306 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
307 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
308 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
309 if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI
310 if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }
311 if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {
312 fprintf(toE, "setoption name %s value true\n", name); strcpy(val, "true"); // set non-standard suspected FRC options
314 if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }
315 if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }
316 if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {
317 memory = oldMem = atoi(val); hasHash = 1;
318 strcpy(hashOpt, name);
319 continue;
321 if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }
322 if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }
323 // pass on engine-defined option as WB option feature
324 if(!strcmp(type, "filename")) type[4] = 0;
325 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
326 if( !strcmp(type, "file")
327 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
328 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
329 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
330 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
331 else if(!strcmp(type, "combo")) {
332 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
333 min = 0; p = line+6;
334 while(p = strstr(p, " var ")) {
335 sscanf(p += 5, "%s", val); // next choice
336 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
338 strcat(q, "\"\n");
340 else buf[0] = 0; // ignore unrecognized option types
341 if(buf[0]) printf("%s", buf);
343 else if(!strcmp(command, "id")) {
344 static char name[256], version[256];
345 if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
346 if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);
348 else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands
349 else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {
350 if(frc) printf("feature variants=\"normal,fischerandom\" oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling
351 printf("feature smp=1 memory=%d done=1\n", hasHash);
352 if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");
353 Sync(WAKEUP); // done with options
358 void
359 Move4Engine(char *m)
361 if(sc == 's') {
362 // convert input move to USI format
363 if(m[1] == '@') { // drop
364 m[1] = '*';
365 } else {
366 m[0] = 'a'+'0'+size - m[0];
367 m[1] = 'a'+'0'+size - m[1];
369 m[2] = 'a'+'0'+size - m[2];
370 m[3] = 'a'+'0'+size - m[3];
371 if(m[4] == '=') m[4] = 0; // no '=' in USI format!
372 else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(
376 void
377 GUI2Engine()
379 char line[256], command[256], *p, *q, *r;
381 while(1) {
382 int i, x;
384 if((computer == stm || computer == ANALYZE) && !suspended) {
385 DPRINT("# start search\n");
386 LoadPos(moveNr); fflush(stdout); // load position
387 // and set engine thinking (note USI swaps colors!)
388 startTime = GetTickCount();
389 if(computer == ANALYZE) {
390 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");
391 if(sm & 1) { // some moves are disabled
392 fprintf(toE, " searchmoves"); DPRINT(" searchmoves");
393 for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }
395 fprintf(toE, "\n"); DPRINT("\n");
396 // code for searchmoves goes here
397 } else { pause = 2; StartSearch(""); fflush(stdout); fflush(toE); Sync(PAUSE); } // block input during thinking
399 nomove:
400 fflush(toE); fflush(stdout);
401 i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;
402 line[++i] = 0; if(x == EOF) { printf("# EOF\n"); fprintf(toE, "quit\n"); exit(-1); }
403 sscanf(line, "%s", command);
404 if(!strcmp(command, "new")) {
405 computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;
406 stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;
407 if(memory != oldMem && hasHash) fprintf(toE, "setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory);
408 oldMem = memory;
409 // we can set other options here
410 if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI
411 pause = 1; // wait for option settings to take effect
412 fprintf(toE, "isready\n"); fflush(toE);
413 Sync(PAUSE); // wait for readyok
414 fprintf(toE, "u%cinewgame\n", sc); fflush(toE);
416 else if(!strcmp(command, "usermove")) {
417 sscanf(line, "usermove %s", command); // strips off linefeed
418 Move4Engine(command);
419 stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;
420 // when pondering we either continue the ponder search as normal search, or abort it
421 if(pondering || computer == ANALYZE) {
422 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit
423 char *draw = drawOffer ? " draw" : ""; drawOffer = 0;
424 pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now
425 fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw); fflush(toE); fflush(stdout);
426 Sync(PAUSE); // block input during thinking
427 goto nomove;
429 StopPonder(1);
431 strcpy(move[moveNr++], command); // possibly overwrites ponder move
433 else if(!strcmp(command, "level")) {
434 int sec = 0;
435 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
436 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
437 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;
439 else if(!strcmp(command, "option")) {
440 char name[80], *p;
441 if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else
442 if(p = strchr(line, '=')) {
443 *p++ = 0;
444 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
445 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);
446 } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }
448 else if(!strcmp(command, "protover")) {
449 if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;
450 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);
451 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);
452 fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options
453 Sync(PAUSE); // wait for uciok
455 else if(!strcmp(command, "setboard")) {
456 stm = (strstr(line+9, " b ") ? BLACK : WHITE);
457 if(p = strchr(line+9, '[')) { char c;
458 *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4;
459 if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color
460 else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
461 *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);
462 } else strcpy(command, line+9);
463 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC
464 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);
465 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);
467 else if(!strcmp(command, "variant")) {
468 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
469 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
470 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
471 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) fprintf(toE, "setoption name UCI_Chess960 value true\n"); }
473 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
474 if(pondering || computer == ANALYZE) StopPonder(1);
475 moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;
477 else if(!strcmp(command, ".")) {
478 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
479 goto nomove;
481 else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude
482 int all = !strcmp(line+8, "all"), in = command[1] == 'n';
483 inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag
484 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
485 if(!(sm & 2)) goto nomove; // no moves enabled; continue current search
486 if(computer == ANALYZE) StopPonder(1); // abort old analysis
488 else if(!strcmp(command, "pause")) {
489 if(computer == stm) myTime -= GetTickCount() - startTime;
490 suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove
491 StopPonder(pondering || computer == stm);
493 else if(!strcmp(command, "resume")) {
494 if(suspended == 2) StartPonder(); // restart interrupted ponder search
495 suspended = 0; // causes thinking to start in normal way if on move or analyzing
497 else if(!strcmp(command, "xboard")) ;
498 else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;
499 else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);
500 else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);
501 else if(!strcmp(command, "go")) computer = stm;
502 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime = (10*myTime)/unit;
503 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;
504 else if(!strcmp(command, "post")) post = 1;
505 else if(!strcmp(command, "nopost")) post = 0;
506 else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);
507 else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();
508 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); }
509 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
510 else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);
511 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
512 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;
513 else if(!strcmp(command, "offer")) drawOffer = 1;
514 else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);
519 StartEngine(char *cmdLine, char *dir)
521 #ifdef WIN32
522 HANDLE hChildStdinRd, hChildStdinWr,
523 hChildStdoutRd, hChildStdoutWr;
524 BOOL fSuccess;
525 PROCESS_INFORMATION piProcInfo;
526 STARTUPINFO siStartInfo;
527 DWORD err;
529 /* Create a pipe for the child's STDOUT. */
530 if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();
532 /* Create a pipe for the child's STDIN. */
533 if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();
535 SetCurrentDirectory(dir); // go to engine directory
537 /* Now create the child process. */
538 siStartInfo.cb = sizeof(STARTUPINFO);
539 siStartInfo.lpReserved = NULL;
540 siStartInfo.lpDesktop = NULL;
541 siStartInfo.lpTitle = NULL;
542 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
543 siStartInfo.cbReserved2 = 0;
544 siStartInfo.lpReserved2 = NULL;
545 siStartInfo.hStdInput = hChildStdinRd;
546 siStartInfo.hStdOutput = hChildStdoutWr;
547 siStartInfo.hStdError = hChildStdoutWr;
549 fSuccess = CreateProcess(NULL,
550 cmdLine, /* command line */
551 NULL, /* process security attributes */
552 NULL, /* primary thread security attrs */
553 TRUE, /* handles are inherited */
554 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
555 NULL, /* use parent's environment */
556 NULL,
557 &siStartInfo, /* STARTUPINFO pointer */
558 &piProcInfo); /* receives PROCESS_INFORMATION */
560 if (! fSuccess) return GetLastError();
562 // if (0) { // in the future we could trigger this by an argument
563 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
564 // }
566 /* Close the handles we don't need in the parent */
567 CloseHandle(piProcInfo.hThread);
568 CloseHandle(hChildStdinRd);
569 CloseHandle(hChildStdoutWr);
571 process = piProcInfo.hProcess;
572 pid = piProcInfo.dwProcessId;
573 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
574 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
575 #else
576 char *argv[10], *p, buf[200];
577 int i, toEngine[2], fromEngine[2];
579 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
580 pipe(toEngine); pipe(fromEngine); // create two pipes
582 if ((pid = fork()) == 0) { // Child
583 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
584 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
585 dup2(1, fileno(stderr)); // stderr into frome pipe
587 strcpy(buf, cmdLine); p = buf;
588 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
589 argv[i] = NULL;
590 execvp(argv[0], argv); // startup engine
592 perror(argv[0]); exit(1); // could not start engine; quit.
594 signal(SIGPIPE, SIG_IGN);
595 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
597 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
598 toE = (FILE*) fdopen(toEngine[1], "w");
599 #endif
600 return NO_ERROR;
603 main(int argc, char **argv)
605 char *dir = NULL, *p, *q; int e;
607 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
608 if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }
609 if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }
610 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
611 if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
612 if(argc > 2) dir = argv[2];
613 if(argc > 3) suffix = argv[3];
615 if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords
616 else if(sc == 'f' ) frc = -1, sc = 'c'; // UCI for unannounced Chess960
617 else if(sc == 'n') sc = 'c'; // UCI for normal Chess
619 // spawn engine proc
620 if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
622 Sync(INIT);
624 // create separate thread to handle engine->GUI traffic
625 #ifdef WIN32
626 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
627 #else
628 { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
629 #endif
631 // handle GUI->engine traffic in original thread
632 GUI2Engine();