]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Fix multiPV issue #502
[stockfish] / src / uci.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22 #include <iostream>
23 #include <sstream>
24 #include <string>
25
26 #include "evaluate.h"
27 #include "movegen.h"
28 #include "position.h"
29 #include "search.h"
30 #include "thread.h"
31 #include "timeman.h"
32 #include "uci.h"
33 #include "syzygy/tbprobe.h"
34
35 using namespace std;
36
37 extern void benchmark(const Position& pos, istream& is);
38
39 namespace {
40
41   // FEN string of the initial position, normal chess
42   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
43
44   // A list to keep track of the position states along the setup moves (from the
45   // start position to the position just before the search starts). Needed by
46   // 'draw by repetition' detection.
47   StateListPtr States(new std::deque<StateInfo>(1));
48
49
50   // position() is called when engine receives the "position" UCI command.
51   // The function sets up the position described in the given FEN string ("fen")
52   // or the starting position ("startpos") and then makes the moves given in the
53   // following move list ("moves").
54
55   void position(Position& pos, istringstream& is) {
56
57     Move m;
58     string token, fen;
59
60     is >> token;
61
62     if (token == "startpos")
63     {
64         fen = StartFEN;
65         is >> token; // Consume "moves" token if any
66     }
67     else if (token == "fen")
68         while (is >> token && token != "moves")
69             fen += token + " ";
70     else
71         return;
72
73     States = StateListPtr(new std::deque<StateInfo>(1));
74     pos.set(fen, Options["UCI_Chess960"], &States->back(), Threads.main());
75
76     // Parse move list (if any)
77     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
78     {
79         States->push_back(StateInfo());
80         pos.do_move(m, States->back());
81     }
82   }
83
84
85   // setoption() is called when engine receives the "setoption" UCI command. The
86   // function updates the UCI option ("name") to the given value ("value").
87
88   void setoption(istringstream& is) {
89
90     string token, name, value;
91
92     is >> token; // Consume "name" token
93
94     // Read option name (can contain spaces)
95     while (is >> token && token != "value")
96         name += string(" ", name.empty() ? 0 : 1) + token;
97
98     // Read option value (can contain spaces)
99     while (is >> token)
100         value += string(" ", value.empty() ? 0 : 1) + token;
101
102     if (Options.count(name))
103         Options[name] = value;
104     else
105         sync_cout << "No such option: " << name << sync_endl;
106   }
107
108
109   // go() is called when engine receives the "go" UCI command. The function sets
110   // the thinking time and other parameters from the input string, then starts
111   // the search.
112
113   void go(Position& pos, istringstream& is) {
114
115     Search::LimitsType limits;
116     string token;
117
118     limits.startTime = now(); // As early as possible!
119
120     while (is >> token)
121         if (token == "searchmoves")
122             while (is >> token)
123                 limits.searchmoves.push_back(UCI::to_move(pos, token));
124
125         else if (token == "wtime")     is >> limits.time[WHITE];
126         else if (token == "btime")     is >> limits.time[BLACK];
127         else if (token == "winc")      is >> limits.inc[WHITE];
128         else if (token == "binc")      is >> limits.inc[BLACK];
129         else if (token == "movestogo") is >> limits.movestogo;
130         else if (token == "depth")     is >> limits.depth;
131         else if (token == "nodes")     is >> limits.nodes;
132         else if (token == "movetime")  is >> limits.movetime;
133         else if (token == "mate")      is >> limits.mate;
134         else if (token == "infinite")  limits.infinite = 1;
135         else if (token == "ponder")    limits.ponder = 1;
136
137     Threads.start_thinking(pos, States, limits);
138   }
139
140 } // namespace
141
142
143 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
144 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
145 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
146 /// run 'bench', once the command is executed the function returns immediately.
147 /// In addition to the UCI ones, also some additional debug commands are supported.
148
149 void UCI::loop(int argc, char* argv[]) {
150
151   Position pos;
152   string token, cmd;
153
154   pos.set(StartFEN, false, &States->back(), Threads.main());
155
156   for (int i = 1; i < argc; ++i)
157       cmd += std::string(argv[i]) + " ";
158
159   do {
160       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input or EOF
161           cmd = "quit";
162
163       istringstream is(cmd);
164
165       token.clear(); // getline() could return empty or blank line
166       is >> skipws >> token;
167
168       // The GUI sends 'ponderhit' to tell us to ponder on the same move the
169       // opponent has played. In case Signals.stopOnPonderhit is set we are
170       // waiting for 'ponderhit' to stop the search (for instance because we
171       // already ran out of time), otherwise we should continue searching but
172       // switching from pondering to normal search.
173       if (    token == "quit"
174           ||  token == "stop"
175           || (token == "ponderhit" && Search::Signals.stopOnPonderhit))
176       {
177           Search::Signals.stop = true;
178           Threads.main()->start_searching(true); // Could be sleeping
179       }
180       else if (token == "ponderhit")
181           Search::Limits.ponder = 0; // Switch to normal search
182
183       else if (token == "uci")
184           sync_cout << "id name " << engine_info(true)
185                     << "\n"       << Options
186                     << "\nuciok"  << sync_endl;
187
188       else if (token == "ucinewgame")
189       {
190           Search::clear();
191           Tablebases::init(Options["SyzygyPath"]);
192           Time.availableNodes = 0;
193       }
194       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
195       else if (token == "go")         go(pos, is);
196       else if (token == "position")   position(pos, is);
197       else if (token == "setoption")  setoption(is);
198
199       // Additional custom non-UCI commands, useful for debugging
200       else if (token == "flip")       pos.flip();
201       else if (token == "bench")      benchmark(pos, is);
202       else if (token == "d")          sync_cout << pos << sync_endl;
203       else if (token == "eval")       sync_cout << Eval::trace(pos) << sync_endl;
204       else if (token == "perft")
205       {
206           int depth;
207           stringstream ss;
208
209           is >> depth;
210           ss << Options["Hash"]    << " "
211              << Options["Threads"] << " " << depth << " current perft";
212
213           benchmark(pos, ss);
214       }
215       else
216           sync_cout << "Unknown command: " << cmd << sync_endl;
217
218   } while (token != "quit" && argc == 1); // Passed args have one-shot behaviour
219
220   Threads.main()->wait_for_search_finished();
221 }
222
223
224 /// UCI::value() converts a Value to a string suitable for use with the UCI
225 /// protocol specification:
226 ///
227 /// cp <x>    The score from the engine's point of view in centipawns.
228 /// mate <y>  Mate in y moves, not plies. If the engine is getting mated
229 ///           use negative values for y.
230
231 string UCI::value(Value v) {
232
233   assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
234
235   stringstream ss;
236
237   if (abs(v) < VALUE_MATE - MAX_PLY)
238       ss << "cp " << v * 100 / PawnValueEg;
239   else
240       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
241
242   return ss.str();
243 }
244
245
246 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
247
248 std::string UCI::square(Square s) {
249   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
250 }
251
252
253 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
254 /// The only special case is castling, where we print in the e1g1 notation in
255 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
256 /// castling moves are always encoded as 'king captures rook'.
257
258 string UCI::move(Move m, bool chess960) {
259
260   Square from = from_sq(m);
261   Square to = to_sq(m);
262
263   if (m == MOVE_NONE)
264       return "(none)";
265
266   if (m == MOVE_NULL)
267       return "0000";
268
269   if (type_of(m) == CASTLING && !chess960)
270       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
271
272   string move = UCI::square(from) + UCI::square(to);
273
274   if (type_of(m) == PROMOTION)
275       move += " pnbrqk"[promotion_type(m)];
276
277   return move;
278 }
279
280
281 /// UCI::to_move() converts a string representing a move in coordinate notation
282 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
283
284 Move UCI::to_move(const Position& pos, string& str) {
285
286   if (str.length() == 5) // Junior could send promotion piece in uppercase
287       str[4] = char(tolower(str[4]));
288
289   for (const auto& m : MoveList<LEGAL>(pos))
290       if (str == UCI::move(m, pos.is_chess960()))
291           return m;
292
293   return MOVE_NONE;
294 }