--- /dev/null
+/************************* UCI2WB by H.G.Muller ****************************/\r
+\r
+#define VERSION "1.5"\r
+\r
+#include <stdio.h>\r
+#include <windows.h>\r
+#include <io.h>\r
+#include <fcntl.h>\r
+\r
+#ifdef _MSC_VER \r
+#define SLEEP() Sleep(1) \r
+#else \r
+#define SLEEP() usleep(10) \r
+#endif \r
+\r
+// Set VARIANTS for in WinBoard variant feature. (With -s option this will always be reset to use "shogi".)\r
+# define VARIANTS "normal,xiangqi"\r
+\r
+#define WHITE 0\r
+#define BLACK 1\r
+#define NONE 2\r
+#define ANALYZE 3\r
+\r
+char move[2000][10], checkOptions[8192], iniPos[256], hashOpt[20], pause, pondering, ponder, post, hasHash, c, sc='c', *suffix;\r
+int mps, tc, inc, stime, depth, myTime, hisTime, stm, computer = NONE, memory, oldMem=0, cores, moveNr, lastDepth, lastScore, startTime;\r
+int statDepth, statScore, statNodes, statTime, currNr, size; char currMove[20]; // for analyze mode\r
+\r
+FILE *toE, *fromE;\r
+HANDLE process;\r
+int pid;\r
+DWORD thread_id;\r
+\r
+void\r
+StartSearch(char *ponder)\r
+{ // send the 'go' command to engine. Suffix by ponder.\r
+ int nr = moveNr + (ponder[0] != 0); // we ponder for one move ahead!\r
+ fprintf(toE, "\ngo btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);\r
+ printf( "\n# go btime %d wtime %d", stm == BLACK ^ sc=='s' ? myTime : hisTime, stm == WHITE ^ sc=='s' ? myTime : hisTime);\r
+ if(stime > 0) fprintf(toE, " movetime %d", stime),printf(" movetime %d", stime); else\r
+ if(mps) fprintf(toE, " movestogo %d", mps*(nr/(2*mps)+1)-nr/2),printf(" movestogo %d", mps*(nr/(2*mps)+1)-nr/2);\r
+ if(inc && !suffix) fprintf(toE, " winc %d binc %d", inc, inc),printf(" winc %d binc %d", inc, inc);\r
+ if(depth > 0) fprintf(toE, " depth %d", depth),printf(" depth %d", depth);\r
+ if(suffix) fprintf(toE, suffix, inc),printf(suffix, inc);\r
+ fprintf(toE, "%s\n", ponder);\r
+ printf("%s\n", ponder);\r
+}\r
+\r
+void\r
+StopPonder(int pondering)\r
+{\r
+ if(!pondering) return;\r
+ pause = 1;\r
+ fprintf(toE, "stop\n");printf("# stop\n"); // note: 'pondering' remains set until engine acknowledges 'stop' with 'bestmove'\r
+ while(pause) SLEEP(); // wait for engine to acknowledge 'stop' with 'bestmove'.\r
+}\r
+\r
+void\r
+LoadPos(int moveNr)\r
+{\r
+ int j;\r
+ fprintf(toE, "%s moves", iniPos);\r
+ printf( "# %s moves", iniPos);\r
+ for(j=0; j<moveNr; j++) fprintf(toE, " %s", move[j]),printf(" %s", move[j]);\r
+}\r
+\r
+char *Convert(char *pv)\r
+{ // convert Shogi coordinates to WB\r
+ char *p, *q, c;\r
+ static char buf[10000];\r
+ if(sc != 's') return pv;\r
+ p = pv; q = buf;\r
+ while(c = *p++) {\r
+ if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') *q++ = 'a'+'0'+size - c; else *q++ = c;\r
+ }\r
+ *q++ = 0;\r
+ return buf;\r
+}\r
+\r
+void\r
+Engine2GUI()\r
+{\r
+ char line[1024], command[256];\r
+\r
+ while(1) {\r
+ int i=0, x; char *p;\r
+\r
+ fflush(stdout); fflush(toE);\r
+ while((line[i] = x = fgetc(fromE)) != EOF && line[i] != '\n') i++;\r
+ line[++i] = 0;\r
+ if(x == EOF) exit(0);\r
+printf("# engine said: %s", line);\r
+ sscanf(line, "%s", command);\r
+ if(!strcmp(command, "bestmove")) {\r
+ if(pause) { pondering = pause = 0; continue; } // bestmove was reply to ponder miss or analysis result; ignore.\r
+ // move was a move to be played\r
+ if(strstr(line+9, "resign")) { printf("resign\n"); computer = NONE; }\r
+ if(strstr(line+9, "(none)") || strstr(line+9, "null") ||\r
+ strstr(line+9, "0000")) { printf("%s\n", lastScore < -99999 ? "resign" : "1/2-1/2 {stalemate}"); computer = NONE; }\r
+ sscanf(line, "bestmove %s", move[moveNr++]);\r
+ myTime -= (GetTickCount() - startTime)*1.02 + inc; // update own clock, so we can give correct wtime, btime with ponder\r
+ if(mps && ((moveNr+1)/2) % mps == 0) myTime += tc; if(stime) myTime = stime; // new session or move starts\r
+ // first start a new ponder search, if pondering is on and we have a move to ponder on\r
+ if(p = strstr(line+9, "ponder")) {\r
+ if(computer != NONE && ponder) {\r
+ sscanf(p+7, "%s", move[moveNr]);\r
+printf("# ponder on %s\n", move[moveNr]);\r
+ LoadPos(moveNr+1); // load position\r
+ // and set engine pondering\r
+ pondering = 1; lastDepth = 1;\r
+ StartSearch(" ponder");\r
+ }\r
+ p[-1] = '\n'; *p = 0; // strip off ponder move\r
+ }\r
+ if(sc == 's') {\r
+ // convert USI move to WB format\r
+ line[11] = 'a'+'0'+size - line[11];\r
+ line[12] = 'a'+'0'+size - line[12];\r
+ if(line[10] == '*') { // drop\r
+ line[10] = '@';\r
+ } else {\r
+ line[9] = 'a'+'0'+size - line[9];\r
+ line[10] = 'a'+'0'+size - line[10];\r
+ if((stm == WHITE ? (line[10]>'0'+size-size/3 || line[12]>'0'+size-size/3)\r
+ : (line[10] <= '0'+size/3 || line[12] <= '0'+size/3)) && line[13] != '+')\r
+ line[13] = '=', line[14] = 0;\r
+ }\r
+ }\r
+ printf("move %s\n", line+9); // send move to GUI\r
+ if(lastScore == 100001 && iniPos[0] != 'f') { printf("%s {mate}\n", stm == WHITE ? "1-0" : "0-1"); computer = NONE; }\r
+ stm = WHITE+BLACK - stm;\r
+ }\r
+ else if(!strcmp(command, "info")) {\r
+ int d=0, s=0, t=0, n=0;\r
+ char *pv;\r
+ if(!post) continue;\r
+ if(strstr(line, "info string ") == line) printf("%d 0 0 0 %s", lastDepth, line+12); else {\r
+ if(p = strstr(line+4, " depth ")) sscanf(p+7, "%d", &d), statDepth = d;\r
+ if(p = strstr(line+4, " score cp ")) sscanf(p+10, "%d", &s), statScore = s; else\r
+ if(p = strstr(line+4, " score mate ")) sscanf(p+12, "%d", &s), s += s>0 ? 100000 : -100000, statScore = s; else\r
+ if(p = strstr(line+4, " score ")) sscanf(p+7, "%d", &s), statScore = s;\r
+ if(p = strstr(line+4, " nodes ")) sscanf(p+7, "%d", &n), statNodes = n;\r
+ if(p = strstr(line+4, " time ")) sscanf(p+6, "%d", &t), t /= 10, statTime = t;\r
+ if(p = strstr(line+4, " currmove ")) sscanf(p+10,"%s", currMove);\r
+ if(p = strstr(line+4, " currmovenumber ")) sscanf(p+16,"%d", &currNr);\r
+ if(pv = strstr(line+4, " pv ")) // convert PV info to WB thinking output\r
+ printf("%3d %6d %6d %10d %s", lastDepth=d, lastScore=s, t, n, Convert(pv+4));\r
+ }\r
+ }\r
+ else if(!strcmp(command, "option")) { // USI option: extract data fields\r
+ char name[80], type[80], buf[1024], val[256], *q;\r
+ int min=0, max=1e9;\r
+ if(p = strstr(line+6, " type ")) sscanf(p+1, "type %s", type), *p = '\n';\r
+ if(p = strstr(line+6, " min ")) sscanf(p+1, "min %d", &min), *p = '\n';\r
+ if(p = strstr(line+6, " max ")) sscanf(p+1, "max %d", &max), *p = '\n';\r
+ if(p = strstr(line+6, " default ")) sscanf(p+1, "default %[^\n]*", val), *p = '\n';\r
+ if(p = strstr(line+6, " name ")) sscanf(p+1, "name %[^\n]*", name);\r
+ if(!strcmp(name, "Hash") || !strcmp(name, "USI_Hash")) {\r
+ memory = oldMem = atoi(val); hasHash = 1; \r
+ strcpy(hashOpt, name);\r
+ continue;\r
+ }\r
+ // pass on engine-defined option as WB option feature\r
+ if(!strcmp(type, "filename")) type[4] = 0;\r
+ sprintf(buf, "feature option=\"%s -%s", name, type); q = buf + strlen(buf);\r
+ if( !strcmp(type, "file")\r
+ || !strcmp(type, "string")) sprintf(q, " %s\"\n", val);\r
+ else if(!strcmp(type, "spin")) sprintf(q, " %d %d %d\"\n", atoi(val), min, max);\r
+ else if(!strcmp(type, "check")) sprintf(q, " %d\"\n", strcmp(val, "true") ? 0 : 1), strcat(checkOptions, name);\r
+ else if(!strcmp(type, "button")) sprintf(q, "\"\n");\r
+ else if(!strcmp(type, "combo")) {\r
+ if(p = strstr(line+6, " default ")) sscanf(p+1, "default %s", type); // current setting\r
+ min = 0; p = line+6;\r
+ while(p = strstr(p, " var ")) {\r
+ sscanf(p += 5, "%s", val); // next choice\r
+ sprintf(buf + strlen(buf), "%s%s%s", min++ ? " /// " : " ", strcmp(type, val) ? "" : "*", val);\r
+ }\r
+ strcat(q, "\"\n");\r
+ }\r
+ else buf[0] = 0; // ignore unrecognized option types\r
+ if(buf[0]) printf("%s", buf);\r
+ }\r
+ else if(!strcmp(command, "id")) {\r
+ char name[256];\r
+ if(sscanf(line, "id name %s", name) == 1) printf("feature myname=\"%s (U%cI2WB)\"\n", name, sc-32);\r
+ }\r
+ else if(!strcmp(command, "readyok")) pause = 0; // resume processing of GUI commands\r
+ else if(sscanf(command, "u%ciok", &c)==1 && c==sc) printf("feature smp=1 memory=%d done=1\n", hasHash); // done with options\r
+ }\r
+}\r
+\r
+void\r
+GUI2Engine()\r
+{\r
+ char line[256], command[256], *p, *q;\r
+\r
+ while(1) {\r
+ int i, x;\r
+\r
+ if(computer == stm || computer == ANALYZE) {\r
+printf("# start search\n");\r
+ LoadPos(moveNr); // load position\r
+ // and set engine thinking (note USI swaps colors!)\r
+ startTime = GetTickCount();\r
+ if(computer == ANALYZE) fprintf(toE, "\ngo infinite\n"), printf("\ngo infinite\n");\r
+ else StartSearch("");\r
+ }\r
+ nomove:\r
+ fflush(toE); fflush(stdout);\r
+ i = 0; while((x = getchar()) != EOF && (line[i] = x) != '\n') i++;\r
+ line[++i] = 0; if(x == EOF) { printf("# EOF\n"); exit(-1); }\r
+ sscanf(line, "%s", command);\r
+ while(pause) SLEEP(); // wait for readyok\r
+ if(!strcmp(command, "new")) {\r
+ computer = BLACK; moveNr = 0; depth = -1;\r
+ stm = WHITE; strcpy(iniPos, "position startpos");\r
+ if(memory != oldMem && hasHash) fprintf(toE, "setoption name %s value %d\n", hashOpt, memory);\r
+ oldMem = memory;\r
+ // we can set other options here\r
+ pause = 1; // wait for option settings to take effect\r
+ fprintf(toE, "isready\n");\r
+ fprintf(toE, "u%cinewgame\n", sc);\r
+ }\r
+ else if(!strcmp(command, "usermove")) {\r
+ if(sc == 's') {\r
+ // convert input move to USI format\r
+ if(line[10] == '@') { // drop\r
+ line[10] = '*';\r
+ } else {\r
+ line[9] = 'a'+'0'+size - line[9];\r
+ line[10] = 'a'+'0'+size - line[10];\r
+ }\r
+ line[11] = 'a'+'0'+size - line[11];\r
+ line[12] = 'a'+'0'+size - line[12];\r
+ if(line[13] == '=') line[13] = 0; // no '=' in USI format!\r
+ else if(line[13] != '\n') line[13] = '+'; // cater to WB 4.4 bug :-(\r
+ }\r
+ sscanf(line, "usermove %s", command); // strips off linefeed\r
+ stm = WHITE+BLACK - stm;\r
+ // when pondering we either continue the ponder search as normal search, or abort it\r
+ if(pondering || computer == ANALYZE) {\r
+ if(pondering && !strcmp(command, move[moveNr])) { // ponder hit\r
+ pondering = 0; moveNr++; startTime = GetTickCount(); // clock starts running now\r
+ fprintf(toE, "ponderhit\n"); printf("# ponderhit\n");\r
+ goto nomove;\r
+ }\r
+ StopPonder(1);\r
+ }\r
+ sscanf(line, "usermove %s", move[moveNr++]); // possibly overwrites ponder move\r
+ }\r
+ else if(!strcmp(command, "level")) {\r
+ int sec = 0;\r
+ sscanf(line, "level %d %d:%d %d", &mps, &tc, &sec, &inc) == 4 ||\r
+ sscanf(line, "level %d %d %d", &mps, &tc, &inc);\r
+ tc = (60*tc + sec)*1000; inc *= 1000; stime = 0;\r
+ }\r
+ else if(!strcmp(command, "option")) {\r
+ char name[80], *p;\r
+ if(p = strchr(line, '=')) {\r
+ *p++ = 0;\r
+ if(strstr(checkOptions, line+7)) sprintf(p, "%s\n", atoi(p) ? "true" : "false");\r
+ fprintf(toE, "setoption name %s value %s", line+7, p), printf("# setoption name %s value %s", line+7, p);\r
+ } else fprintf(toE, "setoption name %s\n", line+7), printf("# setoption name %s\n", line+7);\r
+ }\r
+ else if(!strcmp(command, "protover")) {\r
+ printf("feature variants=\"%s\" setboard=1 usermove=1 debug=1 reuse=0 done=0\n", sc=='s' ? "shogi,5x5+5_shogi" : VARIANTS);\r
+ fprintf(toE, "u%ci\n", sc); // this prompts UCI engine for options\r
+ }\r
+ else if(!strcmp(command, "setboard")) {\r
+ if(strstr(line+9, " b ")) stm = BLACK;\r
+ if(sc == 's' && (p = strchr(line+9, '['))) { char c;\r
+ *p++ = ' '; q = strchr(p, ']'); c = 'w' + 'b' - q[2]; strcpy(q+2, " 1\n"); while(*--q != ' ') q[2] = *q; *p = c; p[1] = ' '; \r
+ }\r
+ sprintf(iniPos, "%s%sfen %s", iniPos[0]=='p' ? "position " : "", sc=='s' ? "s" : "", line+9);\r
+ iniPos[strlen(iniPos)-1] = 0;\r
+ }\r
+ else if(!strcmp(command, "variant")) {\r
+ if(!strcmp(line+8, "shogi\n")) size = 9, strcpy(iniPos, "position startpos");\r
+ if(!strcmp(line+8, "5x5+5_shogi\n")) size = 5, strcpy(iniPos, "position startpos");\r
+ if(!strcmp(line+8, "xiangqi\n")) strcpy(iniPos, "fen rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r");\r
+ }\r
+ else if(!strcmp(command, "undo") && (i=1) || !strcmp(command, "remove") && (i=2)) {\r
+ if(pondering || computer == ANALYZE) StopPonder(1);\r
+ moveNr = moveNr > i ? moveNr - i : 0;\r
+ }\r
+ else if(!strcmp(command, ".")) {\r
+ printf("stat01: %d %d %d %d 100 %s\n", statTime, statNodes, statDepth, 100-currNr, currMove);\r
+ goto nomove;\r
+ }\r
+ else if(!strcmp(command, "xboard")) ;\r
+ else if(!strcmp(command, "analyze"))computer = ANALYZE;\r
+ else if(!strcmp(command, "exit")) computer = NONE, StopPonder(1);\r
+ else if(!strcmp(command, "force")) computer = NONE, StopPonder(pondering);\r
+ else if(!strcmp(command, "go")) computer = stm;\r
+ else if(!strcmp(command, "time")) sscanf(line+4, "%d", &myTime), myTime *= 10;\r
+ else if(!strcmp(command, "otim")) sscanf(line+4, "%d", &hisTime), hisTime *= 10;\r
+ else if(!strcmp(command, "post")) post = 1;\r
+ else if(!strcmp(command, "nopost")) post = 0;\r
+ else if(!strcmp(command, "easy")) ponder = 0;\r
+ else if(!strcmp(command, "hard")) ponder = 1;\r
+ else if(!strcmp(command, "memory")) sscanf(line, "memory %d", &memory);\r
+ else if(!strcmp(command, "cores")) sscanf(line, "cores %d", &cores);\r
+ else if(!strcmp(command, "sd")) sscanf(line, "sd %d", &depth);\r
+ else if(!strcmp(command, "st")) sscanf(line, "st %d", &stime), stime *= 1000, inc = 0;\r
+ else if(!strcmp(command, "quit")) fprintf(toE, "quit\n"), fflush(toE), exit(0);\r
+ }\r
+}\r
+\r
+int\r
+StartEngine(char *cmdLine, char *dir)\r
+{\r
+ HANDLE hChildStdinRd, hChildStdinWr,\r
+ hChildStdoutRd, hChildStdoutWr;\r
+ SECURITY_ATTRIBUTES saAttr;\r
+ BOOL fSuccess;\r
+ PROCESS_INFORMATION piProcInfo;\r
+ STARTUPINFO siStartInfo;\r
+ DWORD err;\r
+\r
+ /* Set the bInheritHandle flag so pipe handles are inherited. */\r
+ saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);\r
+ saAttr.bInheritHandle = TRUE;\r
+ saAttr.lpSecurityDescriptor = NULL;\r
+\r
+ /* Create a pipe for the child's STDOUT. */\r
+ if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return GetLastError();\r
+\r
+ /* Create a pipe for the child's STDIN. */\r
+ if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) return GetLastError();\r
+\r
+ SetCurrentDirectory(dir); // go to engine directory\r
+\r
+ /* Now create the child process. */\r
+ siStartInfo.cb = sizeof(STARTUPINFO);\r
+ siStartInfo.lpReserved = NULL;\r
+ siStartInfo.lpDesktop = NULL;\r
+ siStartInfo.lpTitle = NULL;\r
+ siStartInfo.dwFlags = STARTF_USESTDHANDLES;\r
+ siStartInfo.cbReserved2 = 0;\r
+ siStartInfo.lpReserved2 = NULL;\r
+ siStartInfo.hStdInput = hChildStdinRd;\r
+ siStartInfo.hStdOutput = hChildStdoutWr;\r
+ siStartInfo.hStdError = hChildStdoutWr;\r
+\r
+ fSuccess = CreateProcess(NULL,\r
+ cmdLine, /* command line */\r
+ NULL, /* process security attributes */\r
+ NULL, /* primary thread security attrs */\r
+ TRUE, /* handles are inherited */\r
+ DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP,\r
+ NULL, /* use parent's environment */\r
+ NULL,\r
+ &siStartInfo, /* STARTUPINFO pointer */\r
+ &piProcInfo); /* receives PROCESS_INFORMATION */\r
+\r
+ if (! fSuccess) return GetLastError();\r
+\r
+// if (0) { // in the future we could trigger this by an argument\r
+// SetPriorityClass(piProcInfo.hProcess, GetWin32Priority(appData.niceEngines));\r
+// }\r
+\r
+ /* Close the handles we don't need in the parent */\r
+ CloseHandle(piProcInfo.hThread);\r
+ CloseHandle(hChildStdinRd);\r
+ CloseHandle(hChildStdoutWr);\r
+\r
+ process = piProcInfo.hProcess;\r
+ pid = piProcInfo.dwProcessId;\r
+ fromE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdoutRd, _O_TEXT|_O_RDONLY), "r");\r
+ toE = (FILE*) _fdopen( _open_osfhandle((long)hChildStdinWr, _O_WRONLY), "w");\r
+\r
+ return NO_ERROR;\r
+}\r
+\r
+main(int argc, char **argv)\r
+{\r
+ char *dir = NULL, *p, *q; int e;\r
+\r
+ if(argc == 2 && !strcmp(argv[1], "-v")) { printf("UCI2WB " VERSION " by H.G.Muller\n"); exit(0); }\r
+ if(argc > 1 && argv[1][0] == '-') { sc = argv[1][1]; argc--; argv++; }\r
+ if(argc < 2) { printf("usage is: U%cI2WB [-s] <engine.exe> [<engine directory>]", sc-32); exit(-1); }\r
+ if(argc > 2) dir = argv[2];\r
+ if(argc > 3) suffix = argv[3];\r
+\r
+ // spawn engine proc\r
+ if((errno = StartEngine(argv[1], dir)) != NO_ERROR) { perror(argv[1]), exit(-1); }\r
+\r
+ // create separate thread to handle engine->GUI traffic\r
+ CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Engine2GUI, (LPVOID) NULL, 0, &thread_id);\r
+\r
+ // handle GUI->engine traffic in original thread\r
+ GUI2Engine();\r
+}\r