Change StopPonder() into more general StopSearch()
[uci2wb.git] / UCI2WB.c
blob871527648fc5ef53504ce3ce2ddd25b424415feb
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 "3.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"
34 #define STDVARS "chess,chess960,crazyhouse,3check,giveaway,suicide,losers,atomic,seirawan,shogi,xiangqi"
35 #define EGT ",gaviotaTbPath,syzygyPath,nalimovPath,robbotripleBaseDirectory,robbototalBaseDirectory,bitbases path,"
37 #define DPRINT if(debug) printf
38 #define EPRINT(X) { char f[999]; sprintf X; DPRINT("%s", f); fprintf(toE, "%s", f + 2*(*f == '#')); /* strip optional # prefix */ }
40 #define WHITE 0
41 #define BLACK 1
42 #define NONE 2
43 #define ANALYZE 3
45 char move[2000][10], iniPos[256], hashOpt[20], suspended, ponder, post, hasHash, c, sc='c', suffix[81], varOpt, searching, *binary;
46 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;
47 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp;
48 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000], anaOpt[20], checkOptions[8192] = "Ponder";
49 char pvs[99][999], board[100]; // XQ board for UCCI
50 char *nameWord = "name ", *valueWord = "value ", *wTime = "w", *bTime = "b", *wInc = "winc", *bInc = "binc", newGame; // keywords that differ in UCCI
51 int unit = 1, drawOffer, scores[99], mpvSP, maxDepth, ponderAlways;
53 FILE *toE, *fromE, *fromF;
54 int pid;
56 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; }
58 #ifdef WIN32
59 WinPipe(HANDLE *hRd, HANDLE *hWr)
61 SECURITY_ATTRIBUTES saAttr;
63 /* Set the bInheritHandle flag so pipe handles are inherited. */
64 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
65 saAttr.bInheritHandle = TRUE;
66 saAttr.lpSecurityDescriptor = NULL;
68 /* Create a pipe */
69 return CreatePipe(hRd, hWr, &saAttr, 0);
71 #endif
73 #define INIT 0
74 #define WAKEUP 1
75 #define PAUSE 2
77 void
78 Sync (int action)
80 #ifdef WIN32
81 static HANDLE hWr, hRd; DWORD d; char c;
82 switch(action) {
83 case INIT: WinPipe(&hRd, &hWr); break;
84 case WAKEUP: WriteFile(hWr, "\n", 1, &d, NULL); break;
85 case PAUSE: ReadFile(hRd, &c, 1, &d, NULL);
87 #else
88 static int syncPipe[2]; char c;
89 switch(action) {
90 case INIT: pipe(syncPipe); break;
91 case WAKEUP: write(syncPipe[1], "\n", 1); break;
92 case PAUSE: read(syncPipe[0], &c, 1);
94 #endif
97 void
98 FromFEN(char *fen)
99 { int i=0;
100 while(*fen) {
101 char c = *fen++;
102 if(c >= 'A') board[i++] = c; else
103 if(c == '/') i++; else
104 if(c == ' ') break; else
105 while(c-- > '0' && i < 99) board[i++] = 0;
106 if(i >= 99) break;
110 char *
111 ToFEN(int stm)
113 int i, n=0; static char fen[200]; char *p = fen;
114 for(i=0; i<99; i++) {
115 char c = board[i];
116 if(c >= 'A') { if(n) *p++ = '0' + n; n = 0; *p++ = c; } else n ++;
117 if(i%10 == 8) { if(n) *p++ = '0' + n; n = -1; *p++ = '/'; }
119 sprintf(p-1, " %c - - 0 1", stm);
120 return fen;
124 Sqr(char *m, int j)
126 int n = m[j] - 'a' + 10*('9' - m[j+1]);
127 if(n < 0) n = 0; else if(n > 99) n = 99; return n;
131 Play(int nr)
133 int i, last = -1;
134 FromFEN(iniPos + 4); // in XQ iniPos always has just "fen " prefix
135 for(i=0; i<nr; i++) {
136 int from=Sqr(move[i], 0), to=Sqr(move[i], 2);
137 if(board[to] || (board[from]|32) == 'p' && move[i][1] != move[i][3]) last = i;
138 board[to] = board[from]; board[from] = 0;
140 return last;
143 void
144 StartSearch(char *ponder)
145 { // send the 'go' command to engine. Suffix by ponder.
146 int x = (ponder[0] != 0); // during ponder stm is the opponent
147 int black = (stm == BLACK ^ x ^ sc == 's'); // set if our color is what the engine calls black
148 int nr = moveNr + x; // we ponder for one move ahead!
149 int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time
150 if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent
151 if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering
152 EPRINT((f, "# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t))
153 if(sTime > 0) EPRINT((f, " movetime %d", sTime)) else
154 if(mps) EPRINT((f, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2))
155 if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi
156 if(inc && !*suffix) EPRINT((f, " %s %d %s %d", wInc, inc, bInc, inc))
157 if(depth > 0) EPRINT((f, " depth %d", depth))
158 if(*suffix) EPRINT((f, suffix, inc))
159 EPRINT((f, "\n")); maxDepth = mpvSP = 0;
162 void
163 StopSearch(int discard)
165 if(!searching) return;
166 if(discard) searching = 0; // this causes bestmove to be ignored
167 EPRINT((f, "# stop\n")) fflush(toE); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
170 void
171 LoadPos(int moveNr)
173 int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;
174 if(sc == 'x') { // UCCI: send only reversible moves
175 lastCapt = Play(moveNr); // find last capture (returns -1 if none!)
176 Play(++lastCapt); // reconstruct board after last capture
177 stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b');
178 sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)
180 EPRINT((f, "# %s moves", pos))
181 for(j=lastCapt; j<moveNr; j++) EPRINT((f, " %s", move[j]))
182 EPRINT((f, "\n"))
185 void
186 StartPonder(int moveNr)
188 if(!move[moveNr][0]) return; // no ponder move
189 LoadPos(moveNr+1);
190 searching = 1; lastDepth = 1;
191 StartSearch(" ponder");
194 void
195 Analyze(char *val)
197 if(*anaOpt) EPRINT((f, "# setoption %s%s %s%s\n", nameWord, anaOpt, valueWord, val));
200 char *Convert(char *pv)
201 { // convert Shogi coordinates to WB
202 char *p, *q, c;
203 static char buf[10000];
204 if(sc != 's') return pv;
205 p = pv; q = buf;
206 while(c = *p++) {
207 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
209 *q++ = 0;
210 return buf;
213 void
214 Move4GUI(char *m)
216 if(sc == 's') {
217 // convert USI move to WB format
218 m[2] = 'a'+'0'+size - m[2];
219 m[3] = 'a'+'0'+size - m[3];
220 if(m[1] == '*') { // drop
221 m[1] = '@';
222 } else {
223 m[0] = 'a'+'0'+size - m[0];
224 m[1] = 'a'+'0'+size - m[1];
225 if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)
226 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')
227 m[4] = '=', m[5] = 0;
233 ReadLine (FILE *f, char *line)
235 int x, i = 0;
236 while((x = fgetc(f)) != EOF && (line[i] = x) != '\n') i++; line[++i] = 0;
237 return (x != EOF);
240 void
241 HandleEngineOutput()
243 char line[1024], command[256]; static char egts[999];
245 while(1) {
246 int i=0, x; char *p, dummy, len;
248 fflush(stdout); fflush(toE);
249 if(fromF && !ReadLine(fromF, line)) fromF = 0, printf("# end fake\n");
250 if(!fromF && !ReadLine(fromE, line)) printf("tellusererror UCI2WB: %s died on me\n", binary), exit(0);
251 DPRINT("# engine said: %s", line), fflush(stdout);
252 if(sscanf(line, "%s", command) != 1) continue;
253 if(!strcmp(command, "bestmove")) {
254 if(searching == 1) { searching = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); return; } // ignore ponder search
255 else if(searching != 3) { searching = 0; return; } // ponder miss or analysis result; ignore.
256 // move was a move to be played
257 if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI
258 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
259 if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI
260 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
261 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
262 sscanf(line, "bestmove %s", move[moveNr++]);
263 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
264 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
265 stm = WHITE+BLACK - stm;
266 // first start a new ponder search, if pondering is on and we have a move to ponder on
267 if(p = strstr(line+9, "ponder")) {
268 sscanf(p+7, "%s", move[moveNr]);
269 if(computer != NONE && ponder) {
270 DPRINT("# ponder on %s\n", move[moveNr]);
271 StartPonder(moveNr);
273 p[-1] = '\n'; *p = 0; // strip off ponder move
274 } else move[moveNr][0] = 0;
275 Move4GUI(line+9);
276 printf("move %s\n", line+9); // send move to GUI
277 if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);
278 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }
279 return;
281 else if(!strcmp(command, "info")) {
282 int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;
283 char *pv, varName[80];
284 if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }
285 if(sscanf(line+5, "string variant %s", varName) == 1) {
286 if(!strstr(STDVARS, varName)) {
287 int files = 8, ranks = 8, hand = 0; char parent[80];
288 if(p = strstr(line+18, " files ")) sscanf(p+7, "%d", &files);
289 if(p = strstr(line+18, " ranks ")) sscanf(p+7, "%d", &ranks);
290 if(p = strstr(line+18, " pocket ")) sscanf(p+8, "%d", &hand);
291 if(p = strstr(line+18, " template ")) sscanf(p+10, "%s", parent); else strcpy(parent, "fairy");
292 if(p = strstr(line+18, " startpos "))
293 printf("setup (-) %dx%d+%d_%s %s", files, ranks, hand, parent, p+10);
295 continue;
297 if(collect && (pv = strstr(line+5, "currmove "))) {
298 if(p = strstr(line+5, "currmovenumber ")) {
299 n = atoi(p+15);
300 if(collect == 1 && n != 1) continue; // wait for move 1
301 if(collect + (n == 1) > 2) { // done collecting
302 if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);
303 collect = 3; continue;
305 collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move
308 if(!post) continue;
309 if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {
310 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
311 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
312 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
313 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
314 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
315 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
316 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
317 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
318 if(pv = strstr(line+4, " pv ")) { // convert PV info to WB thinking output
319 if(d > maxDepth) maxDepth = d, mpvSP = 0; else if(d < maxDepth) continue; // ignore depth regressions
320 if(p = strstr(line+4, " upperbound ")) strcat(p, "?\n"); else
321 if(p = strstr(line+4, " lowerbound ")) strcat(p, "!\n");
322 for(i=0; i<mpvSP; i++) if(s == scores[i] && !strcmp(pvs[i], pv+4)) break; // check if duplicat
323 if(i >= mpvSP) strncpy(pvs[mpvSP], pv+4, 998), scores[mpvSP++] = s, // emit as thinking output if not
324 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
325 } else if(s == -100000) lastScore = s; // when checkmated score is valid even without PV (which might not come)
328 else if(!strcmp(command, "option")) { // USI option: extract data fields
329 char name[80], type[80], buf[1024], val[256], *q;
330 int min=0, max=1e9; *val = 0;
331 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
332 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
333 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
334 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
335 if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI
336 if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }
337 if(!strcasecmp(name, "UCI_Variant")) { if(p = strstr(line+6, " var ")) strcpy(varList, p); varOpt = 1; continue; }
338 if(!strcasecmp(name, "UCI_Opponent")) { namOpt = 1; continue; }
339 if(!strcasecmp(name+2, "I_AnalyseMode")) { strcpy(anaOpt, name); continue; }
340 if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {
341 EPRINT((f, "# setoption name %s value true\n", name)) strcpy(val, "true"); // set non-standard suspected FRC options
343 if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }
344 if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }
345 if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {
346 memory = oldMem = atoi(val); hasHash = 1;
347 strcpy(hashOpt, name);
348 continue;
350 if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }
351 if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }
352 sprintf(buf, ",%s,", name); if(p = strcasestr(EGT, buf)) { // collect EGT formats
353 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
355 // pass on engine-defined option as WB option feature
356 if(!strcmp(type, "filename")) type[4] = 0;
357 else if(sc == 'c' && !strcmp(type, "string")) { // in UCI try to guess which strings are file or directory names
358 if(strcasestr(name, "file")) strcpy(type, "file"); else
359 if(strcasestr(name, "path") || strcasestr(name, "directory") || strcasestr(name, "folder")) strcpy(type, "path");
361 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
362 if( !strcmp(type, "file")
363 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
364 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
365 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
366 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
367 else if(!strcmp(type, "combo")) {
368 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
369 min = 0; p = line+6;
370 while(p = strstr(p, " var ")) {
371 sscanf(p += 5, "%s", val); // next choice
372 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
374 strcat(q, "\"\n");
376 else buf[0] = 0; // ignore unrecognized option types
377 if(buf[0]) printf("%s", buf);
379 else if(!strcmp(command, "id")) {
380 static char name[256], version[256];
381 if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
382 if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);
384 else if(!strcmp(command, "readyok")) return; // resume processing of GUI commands
385 else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {
386 char *p = varList, *q = varList;
387 while(*q && *q != '\n') if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas
388 else if(!strncmp(q-1, " chess ", 7)) strcpy(p, "normal"), p += 6, q += 5; // 'chess' is called 'normal' in CECP
389 else *p++ = *q++; // copy other variant names unmodified
390 if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling
391 if(*varList) printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options
392 if(*egts) printf("feature egt=\"%s\"\n", egts+1);
393 printf("feature smp=1 memory=%d done=1\n", hasHash);
394 if(unit == 2) { unit = 1; EPRINT((f, "# setoption usemillisec true\n")) }
395 return; // done with options
400 void
401 Move4Engine(char *m)
403 if(sc == 's') {
404 // convert input move to USI format
405 if(m[1] == '@') { // drop
406 m[1] = '*';
407 } else {
408 m[0] = 'a'+'0'+size - m[0];
409 m[1] = 'a'+'0'+size - m[1];
411 m[2] = 'a'+'0'+size - m[2];
412 m[3] = 'a'+'0'+size - m[3];
413 if(m[4] == '=') m[4] = 0; // no '=' in USI format!
414 else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(
418 int DoCommand ();
419 char mySide;
420 volatile char queue[10000], *qStart, *qEnd;
422 void
423 LaunchSearch()
425 int i;
427 if((computer == stm || computer == ANALYZE && !searching) && !suspended) {
428 DPRINT("# start search\n");
429 LoadPos(moveNr); fflush(stdout); // load position
430 // and set engine thinking (note USI swaps colors!)
431 startTime = GetTickCount(); mySide = stm; // remember side we last played for
432 if(computer == ANALYZE) {
433 EPRINT((f, "# go infinite")); maxDepth = mpvSP = 0;
434 if(sm & 1) { // some moves are disabled
435 EPRINT((f, " searchmoves"))
436 for(i=1; i<nr; i++) if(on[i]) EPRINT((f, " %s", moveMap[i]))
438 EPRINT((f, "\n")) searching = 2; // suppresses spurious commands during analysis starting new searches
439 } else searching = 3, StartSearch(""); // request suspending of input processing while thinking
440 } else if(ponderAlways && computer == NONE) move[moveNr][0] = 0, StartPonder(moveNr-1);
443 void
444 GUI2Engine()
446 char line[256], command[256], *p;
448 while(1) {
449 int i, difficult;
451 for(difficult=0; !difficult; ) { // read and handle commands that can (or must) be handled during thinking
452 fflush(toE); fflush(stdout);
453 if(!ReadLine(stdin, line)) printf("# EOF\n"), sprintf(line, "quit -1\n");
454 sscanf(line, "%s", command);
455 if(!strcmp(command, "usermove")) { difficult--; break; } // for efficiency during game play, moves, time & otim are tried first
456 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime = (10*myTime)/unit;
457 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;
458 else if(!strcmp(command, "offer")) drawOffer = 1; // backlogged anyway, so this can be done instantly
459 else if(!strcmp(command, "post")) post = 1;
460 else if(!strcmp(command, "nopost"))post = 0;
461 else if(!strcmp(command, "pause")) {
462 if(computer == stm) myTime -= GetTickCount() - startTime;
463 suspended = 1 + (searching == 1); // remember if we were pondering, and stop search ignoring bestmove
464 StopSearch(1);
466 else { //convert easy & hard to "option" after treating their effect on the adapter
467 if(!strcmp(command, "easy")) {
468 if(*canPonder) ponder = 0, sprintf(command, "option"), sprintf(line, "option %s=0\n", canPonder); else continue;
470 else if(!strcmp(command, "hard")) {
471 if(*canPonder) ponder = 1, sprintf(command, "option"), sprintf(line, "option %s=1\n", canPonder); else continue;
473 else if(!strcmp(command, "option")) {
474 if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else
475 if(sscanf(line+7, "ponder always=%d", &ponderAlways) == 1) ; else
476 if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else
477 if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else
478 difficult = 1;
480 else difficult = 1; // difficult command; terminate loop for easy ones
482 } // next command
484 // some commands that should never come during thinking can be safely processed here
485 if(difficult < 0) { // used as kludge to signal "usermove" was already matched
486 sscanf(line, "usermove %s", command); // strips off linefeed
487 Move4Engine(command);
488 stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;
489 // when pondering we either continue the ponder search as normal search, or abort it
490 if(searching) { // move cannot come during think, so we are pondering or analysing
491 if(searching == 1 && !strcmp(command, move[moveNr])) { // ponder hit
492 char *draw = drawOffer ? " draw" : ""; drawOffer = 0;
493 searching = 3; moveNr++; startTime = GetTickCount(); // clock starts running now
494 EPRINT((f, "# ponderhit%s\n", draw)) fflush(toE); fflush(stdout);
495 continue;
497 StopSearch(1);
499 strcpy(move[moveNr++], command); // possibly overwrites ponder move
500 *qEnd++ = '\n'; Sync(WAKEUP); // make sure engine thread considers starting a search
501 } else
502 if(!strcmp(command, "resume")) {
503 if(suspended == 2) StartPonder(moveNr); // restart interrupted ponder search
504 suspended = 0; *qEnd++ = '\n'; Sync(WAKEUP); // causes search to start in normal way if on move or analyzing
505 } else
507 if(searching == 3) { // command arrived during thinking; order abort for 'instant commands'
508 if(!strcmp(command, "?") || !strcmp(command, "quit") ||
509 !strcmp(command, "force") || !strcmp(command, "result")) StopSearch(0);
510 } else StopSearch(1); // always abort pondering or analysis
512 // queue command for execution by engine thread
513 if(qStart == qEnd) qStart = qEnd = queue;
514 p = line; while(qEnd < queue+10000 && (*qEnd++ = *p++) != '\n') {}
515 Sync(WAKEUP);
521 DoCommand ()
523 char line[1024], command[256], *p, *q, *r, type[99];
524 int i;
526 p=line; while(qStart < qEnd && (*p++ = *qStart++) != '\n') {} *p = 0;
527 if(line[0] == '\n') return 0;
528 sscanf(line, "%s", command);
530 if(!strcmp(command, "new")) {
531 computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;
532 stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;
533 if(memory != oldMem && hasHash) EPRINT((f, "# setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory))
534 oldMem = memory;
535 // we can set other options here
536 if(sc == 'x') { if(newGame) EPRINT((f, "# setoption newgame\n")) } else // optional in UCCI
537 if(varOpt) EPRINT((f, "# setoption name UCI_Variant value chess\n"))
538 EPRINT((f, "# isready\n")) fflush(toE);
539 HandleEngineOutput(); // wait for readyok
540 EPRINT((f, "# u%cinewgame\n", sc)) fflush(toE);
542 else if(!strcmp(command, "option")) {
543 char *p;
544 if(p = strchr(line, '=')) {
545 *p++ = 0;
546 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
547 EPRINT((f, "# setoption %s%s %s%s", nameWord, line+7, valueWord, p));
548 } else EPRINT((f, "# setoption %s%s\n", nameWord, line+7));
550 else if(!strcmp(command, "level")) {
551 int sec = 0;
552 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
553 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
554 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;
556 else if(!strcmp(command, "protover")) {
557 if(!varList[0]) strcpy(varList, sc=='s' ? ",shogi,5x5+5_shogi" : VARIANTS);
558 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");
559 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);
560 printf("feature option=\"ponder always -check %d\"\n", ponderAlways);
561 if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);
562 EPRINT((f, sc == 'x' ? "# ucci\n" : "# u%ci\n", sc)) fflush(toE); // prompt UCI engine for options
563 HandleEngineOutput(); // wait for uciok
565 else if(!strcmp(command, "setboard")) {
566 stm = (strstr(line+9, " b ") ? BLACK : WHITE);
567 if((p = strchr(line+9, '[')) && !varOpt) { char c;
568 *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4;
569 if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color
570 else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
571 *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);
572 } else strcpy(command, line+9);
573 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC
574 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);
575 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);
577 else if(!strcmp(command, "variant")) {
578 if(varOpt) {
579 EPRINT((f, "# setoption name UCI_Variant value %sucinewgame\nisready\n", line+8))
580 fflush(toE); HandleEngineOutput(); // wait for readyok
582 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
583 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
584 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
585 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) EPRINT((f, "# setoption name UCI_Chess960 value true\n")) }
587 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
588 moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;
590 else if(!strcmp(command, ".")) {
591 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
592 return 1;
594 else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude
595 int all = !strcmp(line+8, "all"), in = command[1] == 'n';
596 inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag
597 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
598 if(!(sm & 2)) return 1; // no moves enabled; continue current search
600 else if(!strcmp(command, "xboard")) ;
601 else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0, Analyze("true");
602 else if(!strcmp(command, "exit")) computer = NONE, Analyze("false");
603 else if(!strcmp(command, "force")) computer = NONE;
604 else if(!strcmp(command, "go")) computer = stm;
605 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); }
606 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
607 else if(!strcmp(command, "cores")&& !!*threadOpt) { sscanf(line, "cores %d", &cores); EPRINT((f, "# setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores)) }
608 else if(!strcmp(command, "egtpath")){
609 sscanf(line+8, "%s %[^\n]", type, command);
610 if(p = strstr(EGT, type)) strcpy(type, p), p = strchr(type, ','), *p = 0; else strcpy(type, "bitbases path");
611 EPRINT((f, "# setoption name %s value %s\n", type, command));
613 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
614 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;
615 else if(!strcmp(command, "name")) { if(namOpt) EPRINT((f, "# setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5)) }
616 else if(!strcmp(command, "computer")) comp = 1;
617 else if(!strcmp(command, "result")) {
618 if(sc == 's') EPRINT((f, "# gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"))
619 computer = NONE;
621 else if(!strcmp(command, "quit")) { EPRINT((f, "# quit\n")) fflush(toE), exit(atoi(line+4)); }
623 return 0;
626 void *
627 Engine2GUI()
629 if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
630 while(1) {
631 if(searching > 1) HandleEngineOutput(); // this could leave us (or fall through) pondering
632 while(qStart == qEnd && searching) HandleEngineOutput(); // relay ponder output until command arrives
633 Sync(PAUSE); // possibly wait for command silently if engine is idle
634 if(!DoCommand()) LaunchSearch();
639 StartEngine(char *cmdLine, char *dir)
641 #ifdef WIN32
642 HANDLE hChildStdinRd, hChildStdinWr,
643 hChildStdoutRd, hChildStdoutWr;
644 BOOL fSuccess;
645 PROCESS_INFORMATION piProcInfo;
646 STARTUPINFO siStartInfo;
647 DWORD err;
649 /* Create a pipe for the child's STDOUT. */
650 if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();
652 /* Create a pipe for the child's STDIN. */
653 if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();
655 SetCurrentDirectory(dir); // go to engine directory
657 /* Now create the child process. */
658 siStartInfo.cb = sizeof(STARTUPINFO);
659 siStartInfo.lpReserved = NULL;
660 siStartInfo.lpDesktop = NULL;
661 siStartInfo.lpTitle = NULL;
662 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
663 siStartInfo.cbReserved2 = 0;
664 siStartInfo.lpReserved2 = NULL;
665 siStartInfo.hStdInput = hChildStdinRd;
666 siStartInfo.hStdOutput = hChildStdoutWr;
667 siStartInfo.hStdError = hChildStdoutWr;
669 fSuccess = CreateProcess(NULL,
670 cmdLine, /* command line */
671 NULL, /* process security attributes */
672 NULL, /* primary thread security attrs */
673 TRUE, /* handles are inherited */
674 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
675 NULL, /* use parent's environment */
676 NULL,
677 &siStartInfo, /* STARTUPINFO pointer */
678 &piProcInfo); /* receives PROCESS_INFORMATION */
680 if (! fSuccess) return GetLastError();
682 // if (0) { // in the future we could trigger this by an argument
683 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
684 // }
686 /* Close the handles we don't need in the parent */
687 CloseHandle(piProcInfo.hThread);
688 CloseHandle(hChildStdinRd);
689 CloseHandle(hChildStdoutWr);
691 process = piProcInfo.hProcess;
692 pid = piProcInfo.dwProcessId;
693 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
694 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
695 #else
696 char *argv[10], *p, buf[200];
697 int i, toEngine[2], fromEngine[2];
699 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
700 pipe(toEngine); pipe(fromEngine); // create two pipes
702 if ((pid = fork()) == 0) { // Child
703 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
704 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
705 dup2(1, fileno(stderr)); // stderr into frome pipe
707 strcpy(buf, cmdLine); p = buf;
708 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
709 argv[i] = NULL;
710 execvp(argv[0], argv); // startup engine
712 perror(argv[0]); exit(1); // could not start engine; quit.
714 signal(SIGPIPE, SIG_IGN);
715 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
717 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
718 toE = (FILE*) fdopen(toEngine[1], "w");
719 #endif
720 return NO_ERROR;
723 main(int argc, char **argv)
725 char *dir = NULL, *p, *q; int e;
728 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
729 if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }
730 if(argc > 1 && !strcmp(argv[1], "-var")) { strcpy(varList+1, argv[2]); *varList = ','; argc-=2; argv+=2; }
731 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
732 if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
733 if(argc > 2) dir = argv[2];
734 if(argc > 3) strncpy(suffix, argv[3], 80);
736 if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords
737 else if(sc == 'f' ) frc = -1, sc = 'c'; // UCI for unannounced Chess960
738 else if(sc == 'n') sc = 'c'; // UCI for normal Chess
740 // spawn engine proc
741 if(StartEngine(binary = argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
743 Sync(INIT);
745 // create separate thread to handle engine->GUI traffic
746 #ifdef WIN32
747 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
748 #else
749 { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
750 #endif
752 // handle GUI->engine traffic in original thread
753 GUI2Engine();