Implement CECP 'setup' command
[uci2wb.git] / UCI2WB.c
blob2370615efc58cbe28ac88ae8bb0df9e356918507
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.2"
14 #include <stdio.h>
15 #include <stdlib.h>
16 #ifdef WIN32
17 # include <windows.h>
18 # include <io.h>
19 HANDLE process;
20 DWORD thread_id;
21 #else
22 # include <pthread.h>
23 # include <signal.h>
24 # define NO_ERROR 0
25 # include <sys/time.h>
26 int GetTickCount() // with thanks to Tord
27 { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec*1000 + t.tv_usec/1000; }
28 #endif
29 #include <fcntl.h>
30 #include <string.h>
32 // Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)
33 # define VARIANTS "normal,xiangqi"
35 #define DPRINT if(debug) printf
37 #define WHITE 0
38 #define BLACK 1
39 #define NONE 2
40 #define ANALYZE 3
42 char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, suspended, ponder, post, hasHash, c, sc='c', suffix[81], *variants, varOpt;
43 int mps, tc, inc, sTime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime, debug, flob;
44 int statDepth, statScore, statNodes, statTime, currNr, size, collect, nr, sm, inex, on[500], frc, byo = -1, namOpt, comp;
45 char currMove[20], moveMap[500][10], /* for analyze mode */ canPonder[20], threadOpt[20], varList[8000];
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 int t = (flob ? inc + myTime/40 : 1000*byo*(byo>0)); // byoyomi time
145 if(sc == 'x') black = 1; else drawOffer = 0;// in UCCI 'black' refers to us and 'white' to opponent
146 if(!x && drawOffer) ponder = " draw", drawOffer = 0; //pass draw offer only when not pondering
147 fprintf(toE, "\ngo%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t);
148 DPRINT( "\n# go%s %stime %d %stime %d", ponder, bTime, (black ? myTime : hisTime) - t, wTime, (!black ? myTime : hisTime) - t);
149 if(sTime > 0) { fprintf(toE, " movetime %d", sTime); DPRINT(" movetime %d", sTime); } else
150 if(mps) { fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2); DPRINT(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2); }
151 if(flob || byo >= 0) sprintf(suffix, " byoyomi %d", t); // for engines running purely on byoyomi
152 if(inc && !*suffix) { fprintf(toE, " %s %d %s %d", wInc, inc, bInc, inc); DPRINT(" %s %d %s %d", wInc, inc, bInc, inc); }
153 if(depth > 0) { fprintf(toE, " depth %d", depth); DPRINT(" depth %d", depth); }
154 if(*suffix) { fprintf(toE, suffix, inc); DPRINT(suffix, inc); }
155 fprintf(toE, "\n"); DPRINT("\n");
158 void
159 StopPonder(int pondering)
161 if(!pondering) return;
162 pause = 1;
163 fprintf(toE, "stop\n"); fflush(toE); DPRINT("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'
164 Sync(PAUSE); // wait for engine to acknowledge 'stop' with 'bestmove'.
167 void
168 LoadPos(int moveNr)
170 int j, lastCapt = 0; char *pos = iniPos, buf[200], stm;
171 if(sc == 'x') { // UCCI: send only reversible moves
172 lastCapt = Play(moveNr); // find last capture (returns -1 if none!)
173 Play(++lastCapt); // reconstruct board after last capture
174 stm = (!strstr(iniPos+4, " b ") ^ lastCapt & 1 ? 'w' : 'b');
175 sprintf(buf, "position fen %s", ToFEN(stm)); pos = buf; // send it as FEN (with "position" in UCCI!)
177 fprintf(toE, "%s moves", pos);
178 DPRINT( "# %s moves", pos);
179 for(j=lastCapt; j<moveNr; j++) { fprintf(toE, " %s", move[j]); DPRINT(" %s", move[j]); }
182 void
183 StartPonder()
185 if(!move[moveNr][0]) return; // no ponder move
186 LoadPos(moveNr+1);
187 pondering = 1; lastDepth = 1;
188 StartSearch(" ponder");
191 char *Convert(char *pv)
192 { // convert Shogi coordinates to WB
193 char *p, *q, c;
194 static char buf[10000];
195 if(sc != 's') return pv;
196 p = pv; q = buf;
197 while(c = *p++) {
198 if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;
200 *q++ = 0;
201 return buf;
204 void
205 Move4GUI(char *m)
207 if(sc == 's') {
208 // convert USI move to WB format
209 m[2] = 'a'+'0'+size - m[2];
210 m[3] = 'a'+'0'+size - m[3];
211 if(m[1] == '*') { // drop
212 m[1] = '@';
213 } else {
214 m[0] = 'a'+'0'+size - m[0];
215 m[1] = 'a'+'0'+size - m[1];
216 if((stm == WHITE ? (m[1]>'0'+size-size/3 || m[3]>'0'+size-size/3)
217 : (m[1] <= '0'+size/3 || m[3] <= '0'+size/3)) && m[4] != '+')
218 m[4] = '=', m[5] = 0;
224 GetChar()
226 int c;
227 if(fromF) {
228 if((c = fgetc(fromF)) != EOF) return c;
229 fclose(fromF); fromF = 0; printf("# end fake\n");
231 return fgetc(fromE);
234 void *
235 Engine2GUI()
237 char line[1024], command[256];
239 if(fromF = fopen("DefectiveEngineOptions.ini", "r")) printf("# fake engine input\n");
240 while(1) {
241 int i=0, x; char *p, dummy;
243 fflush(stdout); fflush(toE);
244 while((line[i] = x = GetChar()) != EOF && line[i] != '\n') i++;
245 line[++i] = 0;
246 if(x == EOF) exit(0);
247 DPRINT("# engine said: %s", line), fflush(stdout);
248 if(sscanf(line, "%s", command) != 1) continue;
249 if(!strcmp(command, "bestmove")) {
250 if(pause == 1) { pondering = pause = 0; Sync(WAKEUP); continue; } // bestmove was reply to ponder miss or analysis result; ignore.
251 else if(pondering) { pondering = 0; printf("%d 0 0 0 UCI violation! Engine moves during ponder\n", lastDepth+1); continue; } // ignore ponder search
252 // move was a move to be played
253 if(p = strstr(line+8, " draw")) *p = 0, printf("offer draw\n"); // UCCI
254 if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }
255 if(strstr(line+9, "win")) { printf("%s {claim}\n", stm== WHITE ? "1-0" :"0-1"); computer = NONE; } // USI
256 if(strstr(line+9, "(none)") || strstr(line+9, "null") ||
257 strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }
258 sscanf(line, "bestmove %s", move[moveNr++]);
259 myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder
260 if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(sTime) myTime = sTime; // new session or move starts
261 stm = WHITE+BLACK - stm;
262 // first start a new ponder search, if pondering is on and we have a move to ponder on
263 if(p = strstr(line+9, "ponder")) {
264 sscanf(p+7, "%s", move[moveNr]);
265 if(computer != NONE && ponder) {
266 DPRINT("# ponder on %s\n", move[moveNr]);
267 StartPonder();
269 p[-1] = '\n'; *p = 0; // strip off ponder move
270 } else move[moveNr][0] = 0;
271 Move4GUI(line+9);
272 printf("move %s\n", line+9); // send move to GUI
273 if(move[moveNr][0]) printf("Hint: %s\n", move[moveNr]);
274 if(pause) { pause = 0; Sync(WAKEUP); } // release commands that came in during think
275 if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == BLACK ? "1-0" : "0-1"); computer = NONE; }
277 else if(!strcmp(command, "info")) {
278 int d=0, s=0, t=(GetTickCount() - startTime)/10, n=1;
279 char *pv, varName[80];
280 if(sscanf(line+5, "string times @ %c", &dummy) == 1) { printf("# %s", line+12); continue; }
281 if(sscanf(line+5, "string variant %s", varName) == 1) {
282 if(strcmp(varName,"chess") && (p = strstr(line+18, " startpos "))) printf("setup (-) 8x8+0_fairy %s", p+10);
283 continue;
285 if(collect && (pv = strstr(line+5, "currmove "))) {
286 if(p = strstr(line+5, "currmovenumber ")) {
287 n = atoi(p+15);
288 if(collect == 1 && n != 1) continue; // wait for move 1
289 if(collect + (n == 1) > 2) { // done collecting
290 if(inex && collect == 2) printf("%d 0 0 0 OK to exclude\n", lastDepth);
291 collect = 3; continue;
293 collect = 2; on[nr=n] = 1; sscanf(pv+9, "%s", moveMap[n]); continue; // store move
296 if(!post) continue;
297 if(sscanf(line+5, "string %c", &dummy) == 1) printf("%d 0 0 0 %s", lastDepth, line+12); else {
298 if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;
299 if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else
300 if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else
301 if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;
302 if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;
303 if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;
304 if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);
305 if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);
306 if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output
307 printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));
310 else if(!strcmp(command, "option")) { // USI option: extract data fields
311 char name[80], type[80], buf[1024], val[256], *q;
312 int min=0, max=1e9;
313 if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';
314 if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';
315 if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';
316 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';
317 if(!(p = strstr(line+6, " name "))) p = line+1; sscanf(p+6, "%[^\n]", name); // 'name' is omitted in UCCI
318 if(!strcasecmp(name, "UCI_Chess960")) { frc=2; continue; }
319 if(!strcasecmp(name, "UCI_Variant")) { if(p = strstr(line+6, " var ")) strcpy(varList, p); varOpt = 1; continue; }
320 if(!strcasecmp(name, "UCI_Opponent")) { namOpt = 1; continue; }
321 if(frc< 0 && (strstr(name, "960") || strcasestr(name, "frc")) && !strcmp(type, "check")) {
322 fprintf(toE, "setoption name %s value true\n", name); strcpy(val, "true"); // set non-standard suspected FRC options
324 if(!strcasecmp(name, "Threads")) { strcpy(threadOpt, name); continue; }
325 if(!strcasecmp(name, "Ponder") || !strcasecmp(name, "USI_Ponder")) { strcpy(canPonder, name); continue; }
326 if(!strcasecmp(name, "Hash") || !strcasecmp(name, "USI_Hash") || !strcasecmp(name, "hashsize")) {
327 memory = oldMem = atoi(val); hasHash = 1;
328 strcpy(hashOpt, name);
329 continue;
331 if(!strcasecmp(name, "newgame") && !strcmp(type, "button")) { newGame++; continue; }
332 if(!strcasecmp(name, "usemillisec")) { unit = (!strcmp(val, "false") ? 2 : 1); continue; }
333 // pass on engine-defined option as WB option feature
334 if(!strcmp(type, "filename")) type[4] = 0;
335 sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);
336 if( !strcmp(type, "file")
337 || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);
338 else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);
339 else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);
340 else if(!strcmp(type, "button")) sprintf(q, "\"\n");
341 else if(!strcmp(type, "combo")) {
342 if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting
343 min = 0; p = line+6;
344 while(p = strstr(p, " var ")) {
345 sscanf(p += 5, "%s", val); // next choice
346 sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);
348 strcat(q, "\"\n");
350 else buf[0] = 0; // ignore unrecognized option types
351 if(buf[0]) printf("%s", buf);
353 else if(!strcmp(command, "id")) {
354 static char name[256], version[256];
355 if(sscanf(line, "id name %[^\n]", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);
356 if(sscanf(line, "id version %[^\n]", version) == 1 && *name) printf("feature myname=\"%s %s (U%cI2WB)\"\n", name, version, sc-32);
358 else if(!strcmp(command, "readyok")) { pause = 0; Sync(WAKEUP); } // resume processing of GUI commands
359 else if(sc == 'x'&& !strcmp(command, "ucciok") || sscanf(command, "u%ciok", &c)==1 && c==sc) {
360 char *p = varList, *q = varList;
361 while(*q && *q != '\n') if(!strncmp(q, " var ", 5)) *p++ = ',', q +=5; // replace var keywords by commas
362 else if(!strncmp(q-1, " chess ", 7)) strcpy(p, "normal"), p += 6, q += 5; // 'chess' is called 'normal' in CECP
363 else if(!strncmp(q-1, " threecheck", 11)) *p++ = '3', q += 5; // 'threecheck' is written '3check' in CECP
364 else *p++ = *q++; // copy other variant names unmodified
365 if(frc) sprintf(p, ",normal,fischerandom"), printf("feature oocastle=%d\n", frc<0); // unannounced FRC uses O-O castling
366 if(*varList) printf("feature variants=\"%s\"\n", varList+1); // from UCI_Variant combo and/or UCI_Chess960 check options
367 printf("feature smp=1 memory=%d done=1\n", hasHash);
368 if(unit == 2) unit = 1, fprintf(toE, "setoption usemillisec true\n");
369 Sync(WAKEUP); // done with options
374 void
375 Move4Engine(char *m)
377 if(sc == 's') {
378 // convert input move to USI format
379 if(m[1] == '@') { // drop
380 m[1] = '*';
381 } else {
382 m[0] = 'a'+'0'+size - m[0];
383 m[1] = 'a'+'0'+size - m[1];
385 m[2] = 'a'+'0'+size - m[2];
386 m[3] = 'a'+'0'+size - m[3];
387 if(m[4] == '=') m[4] = 0; // no '=' in USI format!
388 else if(m[4]) m[4] = '+'; // cater to WB 4.4 bug :-(
392 void
393 GUI2Engine()
395 char line[256], command[256], *p, *q, *r, mySide;
397 while(1) {
398 int i, x;
400 if((computer == stm || computer == ANALYZE) && !suspended) {
401 DPRINT("# start search\n");
402 LoadPos(moveNr); fflush(stdout); // load position
403 // and set engine thinking (note USI swaps colors!)
404 startTime = GetTickCount(); mySide = stm; // remember side we last played for
405 if(computer == ANALYZE) {
406 fprintf(toE, "\ngo infinite"); DPRINT("\n# go infinite");
407 if(sm & 1) { // some moves are disabled
408 fprintf(toE, " searchmoves"); DPRINT(" searchmoves");
409 for(i=1; i<nr; i++) if(on[i]) { fprintf(toE, " %s", moveMap[i]); DPRINT(" %s", moveMap[i]); }
411 fprintf(toE, "\n"); DPRINT("\n");
412 // code for searchmoves goes here
413 } else { pause = 2; StartSearch(""); fflush(stdout); fflush(toE); Sync(PAUSE); } // block input during thinking
415 nomove:
416 fflush(toE); fflush(stdout);
417 i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;
418 line[++i] = 0; if(x == EOF) { printf("# EOF\n"); fprintf(toE, "quit\n"); exit(-1); }
419 sscanf(line, "%s", command);
420 if(!strcmp(command, "new")) {
421 computer = BLACK; moveNr = 0; depth = -1; move[0][0] = 0;
422 stm = WHITE; strcpy(iniPos, "position startpos"); frc &= ~1;
423 if(memory != oldMem && hasHash) fprintf(toE, "setoption %s%s %s%d\n", nameWord, hashOpt, valueWord, memory);
424 oldMem = memory;
425 // we can set other options here
426 if(sc == 'x') { if(newGame) fprintf(toE, "setoption newgame\n"); } else // optional in UCCI
427 if(varOpt) fprintf(toE, "setoption name UCI_Variant value chess\n");
428 pause = 1; // wait for option settings to take effect
429 fprintf(toE, "isready\n"); fflush(toE);
430 Sync(PAUSE); // wait for readyok
431 fprintf(toE, "u%cinewgame\n", sc); fflush(toE);
433 else if(!strcmp(command, "usermove")) {
434 sscanf(line, "usermove %s", command); // strips off linefeed
435 Move4Engine(command);
436 stm = WHITE+BLACK - stm; collect = (computer == ANALYZE); sm = 0;
437 // when pondering we either continue the ponder search as normal search, or abort it
438 if(pondering || computer == ANALYZE) {
439 if(pondering && !strcmp(command, move[moveNr])) { // ponder hit
440 char *draw = drawOffer ? " draw" : ""; drawOffer = 0;
441 pondering = 0; pause = 2; moveNr++; startTime = GetTickCount(); // clock starts running now
442 fprintf(toE, "ponderhit%s\n", draw); DPRINT("# ponderhit%s\n", draw); fflush(toE); fflush(stdout);
443 Sync(PAUSE); // block input during thinking
444 goto nomove;
446 StopPonder(1);
448 strcpy(move[moveNr++], command); // possibly overwrites ponder move
450 else if(!strcmp(command, "level")) {
451 int sec = 0;
452 sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||
453 sscanf(line, "level %d %d %d", &mps, &tc, &inc);
454 tc = (60*tc + sec)*1000; inc *= 1000; sTime = 0; tc /= unit; inc /= unit;
456 else if(!strcmp(command, "option")) {
457 char name[80], *p;
458 if(sscanf(line+7, "UCI2WB debug output=%d", &debug) == 1) ; else
459 if(sscanf(line+7, "Floating Byoyomi=%d", &flob) == 1) ; else
460 if(sscanf(line+7, "Byoyomi=%d", &byo) == 1) ; else
461 if(p = strchr(line, '=')) {
462 *p++ = 0;
463 if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");
464 fprintf(toE, "setoption name %s value %s", line+7, p); DPRINT("# setoption %s%s %s%s", nameWord, line+7, valueWord, p);
465 } else { fprintf(toE, "setoption %s%s\n", nameWord, line+7); DPRINT("# setoption %s%s\n", nameWord, line+7); }
467 else if(!strcmp(command, "protover")) {
468 if(!variants) variants = sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS;
469 printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 ping=1 name=1 reuse=0 exclude=1 pause=1 sigint=0 sigterm=0 done=0\n", variants);
470 printf("feature option=\"UCI2WB debug output -check %d\"\n", debug);
471 if(sc == 's') printf("feature option=\"Floating Byoyomi -check %d\"\nfeature option=\"Byoyomi -spin %d -1 1000\"\n", flob, byo);
472 fprintf(toE, sc == 'x' ? "ucci\n" : "u%ci\n", sc); fflush(toE); // prompt UCI engine for options
473 Sync(PAUSE); // wait for uciok
475 else if(!strcmp(command, "setboard")) {
476 stm = (strstr(line+9, " b ") ? BLACK : WHITE);
477 if((p = strchr(line+9, '[')) && !varOpt) { char c;
478 *p++ = 0; q = strchr(p, ']'); *q = 0; r = q + 4;
479 if(sc == 's') q[2] = 'w' + 'b' - q[2], strcpy(r=q+3, " 1\n"); // Shogi: reverse color
480 else r = strchr(strchr(q+4, ' ') + 1, ' '); // skip to second space (after e.p. square)
481 *r = 0; sprintf(command, "%s%s %s %s", line+9, q+1, p, r+1);
482 } else strcpy(command, line+9);
483 if(frc == -1 && (p = strchr(command, ' '))) strncpy(p+3, "KQkq", 4); // unannounced FRC
484 sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", command);
485 iniPos[strlen(iniPos)-1] = sm = 0; collect = (computer == ANALYZE);
487 else if(!strcmp(command, "variant")) {
488 if(varOpt) {
489 fprintf(toE, "setoption name UCI_Variant value %sucinewgame\nisready\n", strcmp(line+8, "3check\n") ? line+8 : "threecheck\n");
490 fflush(toE); Sync(PAUSE);
492 if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");
493 if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");
494 if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");
495 if(!strcmp(line+8, "fischerandom\n")) { frc |= 1; if(frc > 0) fprintf(toE, "setoption name UCI_Chess960 value true\n"); }
497 else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {
498 if(pondering || computer == ANALYZE) StopPonder(1);
499 moveNr = moveNr > i ? moveNr - i : 0; collect = (computer == ANALYZE); sm = 0;
501 else if(!strcmp(command, ".")) {
502 printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);
503 goto nomove;
505 else if(!strcmp(command+2, "clude") && collect > 2) { // include or exclude
506 int all = !strcmp(line+8, "all"), in = command[1] == 'n';
507 inex = 1; line[strlen(line)-1] = sm = 0; // strip LF and clear sm flag
508 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
509 if(!(sm & 2)) goto nomove; // no moves enabled; continue current search
510 if(computer == ANALYZE) StopPonder(1); // abort old analysis
512 else if(!strcmp(command, "pause")) {
513 if(computer == stm) myTime -= GetTickCount() - startTime;
514 suspended = 1 + pondering; // remember if we were pondering, and stop search ignoring bestmove
515 StopPonder(pondering || computer == stm);
517 else if(!strcmp(command, "resume")) {
518 if(suspended == 2) StartPonder(); // restart interrupted ponder search
519 suspended = 0; // causes thinking to start in normal way if on move or analyzing
521 else if(!strcmp(command, "xboard")) ;
522 else if(!strcmp(command, "analyze"))computer = ANALYZE, collect = 1, sm = 0;
523 else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);
524 else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);
525 else if(!strcmp(command, "go")) computer = stm;
526 else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime = (10*myTime)/unit;
527 else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime = (10*hisTime)/unit;
528 else if(!strcmp(command, "post")) post = 1;
529 else if(!strcmp(command, "nopost")) post = 0;
530 else if(!strcmp(command, "easy") && !!*canPonder) ponder = 0, StopPonder(pondering), fprintf(toE, "setoption %s%s %sfalse\n", nameWord, canPonder, valueWord);
531 else if(!strcmp(command, "hard") && !!*canPonder) ponder = 1, fprintf(toE, "setoption %s%s %strue\n", nameWord, canPonder, valueWord), StartPonder();
532 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); }
533 else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);
534 else if(!strcmp(command, "cores")&& !!*threadOpt) sscanf(line, "cores %d", &cores), fprintf(toE, "setoption %s%s %s%d\n", nameWord, threadOpt, valueWord, cores);
535 else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);
536 else if(!strcmp(command, "st")) sscanf(line, "st %d", &sTime), sTime = 1000*sTime - 30, inc = 0, sTime /= unit;
537 else if(!strcmp(command, "name")) { if(namOpt) fprintf(toE, "setoption name UCI_Opponent value none none %s %s", comp ? "computer" : "human", line+5); }
538 else if(!strcmp(command, "computer")) comp = 1;
539 else if(!strcmp(command, "offer")) drawOffer = 1;
540 else if(!strcmp(command, "result")) { if(sc == 's') fprintf(toE, "gameover %s\n", line[8] == '/' ? "draw" : (line[7] == '0') == mySide ? "win" : "lose"); }
541 else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);
546 StartEngine(char *cmdLine, char *dir)
548 #ifdef WIN32
549 HANDLE hChildStdinRd, hChildStdinWr,
550 hChildStdoutRd, hChildStdoutWr;
551 BOOL fSuccess;
552 PROCESS_INFORMATION piProcInfo;
553 STARTUPINFO siStartInfo;
554 DWORD err;
556 /* Create a pipe for the child's STDOUT. */
557 if (! WinPipe(&hChildStdoutRd, &hChildStdoutWr)) return GetLastError();
559 /* Create a pipe for the child's STDIN. */
560 if (! WinPipe(&hChildStdinRd, &hChildStdinWr)) return GetLastError();
562 SetCurrentDirectory(dir); // go to engine directory
564 /* Now create the child process. */
565 siStartInfo.cb = sizeof(STARTUPINFO);
566 siStartInfo.lpReserved = NULL;
567 siStartInfo.lpDesktop = NULL;
568 siStartInfo.lpTitle = NULL;
569 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
570 siStartInfo.cbReserved2 = 0;
571 siStartInfo.lpReserved2 = NULL;
572 siStartInfo.hStdInput = hChildStdinRd;
573 siStartInfo.hStdOutput = hChildStdoutWr;
574 siStartInfo.hStdError = hChildStdoutWr;
576 fSuccess = CreateProcess(NULL,
577 cmdLine, /* command line */
578 NULL, /* process security attributes */
579 NULL, /* primary thread security attrs */
580 TRUE, /* handles are inherited */
581 DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,
582 NULL, /* use parent's environment */
583 NULL,
584 &siStartInfo, /* STARTUPINFO pointer */
585 &piProcInfo); /* receives PROCESS_INFORMATION */
587 if (! fSuccess) return GetLastError();
589 // if (0) { // in the future we could trigger this by an argument
590 // SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));
591 // }
593 /* Close the handles we don't need in the parent */
594 CloseHandle(piProcInfo.hThread);
595 CloseHandle(hChildStdinRd);
596 CloseHandle(hChildStdoutWr);
598 process = piProcInfo.hProcess;
599 pid = piProcInfo.dwProcessId;
600 fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");
601 toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");
602 #else
603 char *argv[10], *p, buf[200];
604 int i, toEngine[2], fromEngine[2];
606 if (dir && dir[0] && chdir(dir)) { perror(dir); exit(1); }
607 pipe(toEngine); pipe(fromEngine); // create two pipes
609 if ((pid = fork()) == 0) { // Child
610 dup2(toEngine[0], 0); close(toEngine[0]); close(toEngine[1]); // stdin from toE pipe
611 dup2(fromEngine[1], 1); close(fromEngine[0]); close(fromEngine[1]); // stdout into fromE pipe
612 dup2(1, fileno(stderr)); // stderr into frome pipe
614 strcpy(buf, cmdLine); p = buf;
615 for (i=0;;) { argv[i++] = p; p = strchr(p, ' '); if (p == NULL) break; *p++ = 0; }
616 argv[i] = NULL;
617 execvp(argv[0], argv); // startup engine
619 perror(argv[0]); exit(1); // could not start engine; quit.
621 signal(SIGPIPE, SIG_IGN);
622 close(toEngine[0]); close(fromEngine[1]); // close engine ends of pipes in adapter
624 fromE = (FILE*) fdopen(fromEngine[0], "r"); // make into high-level I/O
625 toE = (FILE*) fdopen(toEngine[1], "w");
626 #endif
627 return NO_ERROR;
630 main(int argc, char **argv)
632 char *dir = NULL, *p, *q; int e;
634 if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }
635 if(argc > 1 && !strcmp(argv[1], "debug")) { debug = 1; argc--; argv++; }
636 if(argc > 1 && !strcmp(argv[1], "-var")) { variants = argv[2]; argc-=2; argv+=2; }
637 if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }
638 if(argc < 2) { printf("usage is: U%cI2WB [debug] [-s] <engine.exe> [<engine directory>]\n", sc-32); exit(-1); }
639 if(argc > 2) dir = argv[2];
640 if(argc > 3) strncpy(suffix, argv[3], 80);
642 if(sc == 'x') nameWord = valueWord = bTime = "", wTime = "opp", bInc = "increment", wInc = "oppincrement", unit = 1000; // switch to UCCI keywords
643 else if(sc == 'f' ) frc = -1, sc = 'c'; // UCI for unannounced Chess960
644 else if(sc == 'n') sc = 'c'; // UCI for normal Chess
646 // spawn engine proc
647 if(StartEngine(argv[1], dir) != NO_ERROR) { perror(argv[1]), exit(-1); }
649 Sync(INIT);
651 // create separate thread to handle engine->GUI traffic
652 #ifdef WIN32
653 CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);
654 #else
655 { pthread_t t; signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); pthread_create(&t, NULL, Engine2GUI, NULL); }
656 #endif
658 // handle GUI->engine traffic in original thread
659 GUI2Engine();