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