]> git.sesse.net Git - stockfish/blob - src/main.cpp
Fix compilation after recent merge.
[stockfish] / src / main.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <deque>
20 #include <cstddef>
21 #include <iostream>
22 #include <stack>
23 #include <thread>
24
25 #include "bitboard.h"
26 #include "evaluate.h"
27 #include "misc.h"
28 #include "position.h"
29 #include "search.h"
30 #include "thread.h"
31 #include "tune.h"
32 #include "types.h"
33 #include "uci.h"
34
35 #include <grpc/grpc.h>
36 #include <grpc++/server.h>
37 #include <grpc++/server_builder.h>
38 #include "hashprobe.h"
39 #include "hashprobe.grpc.pb.h"
40 #include "tt.h"
41
42 using grpc::Server;
43 using grpc::ServerBuilder;
44 using grpc::ServerContext;
45 using grpc::Status;
46 using grpc::StatusCode;
47 using namespace hashprobe;
48 using namespace Stockfish;
49
50 Status HashProbeImpl::Probe(ServerContext* context,
51                             const HashProbeRequest* request,
52                             HashProbeResponse *response) {
53         Position pos;
54         StateInfo st;
55         pos.set(request->fen(), /*isChess960=*/false, &st, Threads.main());
56         if (!pos.pos_is_ok()) {
57                 return Status(StatusCode::INVALID_ARGUMENT, "Invalid FEN");
58         }
59
60         bool invert = (pos.side_to_move() == BLACK);
61         StateListPtr setup_states = StateListPtr(new std::deque<StateInfo>(1));
62
63         ProbeMove(&pos, setup_states.get(), invert, response->mutable_root());
64
65         MoveList<LEGAL> moves(pos);
66         for (const ExtMove* em = moves.begin(); em != moves.end(); ++em) {
67                 HashProbeLine *line = response->add_line();
68                 FillMove(&pos, em->move, line->mutable_move());
69                 setup_states->push_back(StateInfo());
70                 pos.do_move(em->move, setup_states->back());
71                 ProbeMove(&pos, setup_states.get(), !invert, line);
72                 pos.undo_move(em->move);
73         }
74
75         return Status::OK;
76 }
77
78 void HashProbeImpl::FillMove(Position *pos, Move move, HashProbeMove* decoded) {
79         if (!is_ok(move)) return;
80
81         Square from = from_sq(move);
82         Square to = to_sq(move);
83
84         if (type_of(move) == CASTLING) {
85                 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
86         }
87
88         Piece moved_piece = pos->moved_piece(move);
89         std::string pretty;
90         if (type_of(move) == CASTLING) {
91                 if (to > from) {
92                         pretty = "O-O";
93                 } else {
94                         pretty = "O-O-O";
95                 }
96         } else if (type_of(moved_piece) == PAWN) {
97                 if (type_of(move) == EN_PASSANT || pos->piece_on(to) != NO_PIECE) {
98                         // Capture.
99                         pretty = char('a' + file_of(from));
100                         pretty += "x";
101                 }
102                 pretty += UCI::square(to);
103                 if (type_of(move) == PROMOTION) {
104                         pretty += "=";
105                         pretty += " PNBRQK"[promotion_type(move)];
106                 }
107         } else {
108                 pretty = " PNBRQK"[type_of(moved_piece)];
109                 Bitboard attackers = pos->attackers_to(to) & pos->pieces(color_of(moved_piece), type_of(moved_piece));
110                 if (more_than_one(attackers)) {
111                         // Remove all illegal moves to disambiguate.
112                         Bitboard att_copy = attackers;
113                         while (att_copy) {
114                                 Square s = pop_lsb(att_copy);
115                                 Move m = make_move(s, to);
116                                 if (!pos->pseudo_legal(m) || !pos->legal(m)) {
117                                         attackers &= ~square_bb(s);
118                                 }
119                         }
120                 }
121                 if (more_than_one(attackers)) {
122                         // Disambiguate by file if possible.
123                         Bitboard attackers_this_file = attackers & file_bb(file_of(from));
124                         if (attackers != attackers_this_file) {
125                                 pretty += char('a' + file_of(from));
126                                 attackers = attackers_this_file;
127                         }
128                         if (more_than_one(attackers)) {
129                                 // Still ambiguous, so need to disambiguate by rank.
130                                 pretty += char('1' + rank_of(from));
131                         }
132                 }
133
134                 if (type_of(move) == EN_PASSANT || pos->piece_on(to) != NO_PIECE) {
135                         pretty += "x";
136                 }
137
138                 pretty += UCI::square(to);
139         }
140
141         if (pos->gives_check(move)) {
142                 // Check if mate.
143                 StateInfo si;
144                 pos->do_move(move, si, true);
145                 if (MoveList<LEGAL>(*pos).size() > 0) {
146                         pretty += "+";
147                 } else {
148                         pretty += "#";
149                 }
150                 pos->undo_move(move);
151         }
152
153         decoded->set_pretty(pretty);
154 }
155
156 void HashProbeImpl::ProbeMove(Position* pos, std::deque<StateInfo>* setup_states, bool invert, HashProbeLine* response) {
157         bool found;
158         TTEntry *entry = TT.probe(pos->key(), found);
159         response->set_found(found);
160         if (found) {
161                 TTEntry entry_copy = *entry;
162                 Value value = entry_copy.value();
163                 Value eval = entry_copy.eval();
164                 Bound bound = entry_copy.bound();
165
166                 if (invert) {
167                         value = -value;
168                         eval = -eval;
169                         if (bound == BOUND_UPPER) {
170                                 bound = BOUND_LOWER;
171                         } else if (bound == BOUND_LOWER) {
172                                 bound = BOUND_UPPER;
173                         }
174                 }
175
176                 response->set_depth(entry_copy.depth());
177                 FillValue(eval, response->mutable_eval());
178                 if (entry_copy.depth() > DEPTH_NONE) {
179                         FillValue(value, response->mutable_value());
180                 }
181                 response->set_bound(HashProbeLine::ValueBound(bound));
182
183                 // Follow the PV until we hit an illegal move.
184                 std::stack<Move> pv;
185                 std::set<Key> seen;
186                 while (is_ok(entry_copy.move()) &&
187                        pos->pseudo_legal(entry_copy.move()) &&
188                        pos->legal(entry_copy.move())) {
189                         FillMove(pos, entry_copy.move(), response->add_pv());
190                         if (seen.count(pos->key())) break;
191                         pv.push(entry_copy.move());
192                         seen.insert(pos->key());
193                         setup_states->push_back(StateInfo());
194                         pos->do_move(entry_copy.move(), setup_states->back());
195                         entry = TT.probe(pos->key(), found);
196                         if (!found) {
197                                 break;
198                         }
199                         entry_copy = *entry;
200                 }
201
202                 // Unroll the PV back again, so the Position object remains unchanged.
203                 while (!pv.empty()) {
204                         pos->undo_move(pv.top());
205                         pv.pop();
206                 }
207         }
208 }
209
210 void HashProbeImpl::FillValue(Value value, HashProbeScore* score) {
211         if (abs(value) < VALUE_MATE - MAX_PLY) {
212                 score->set_score_type(HashProbeScore::SCORE_CP);
213                 score->set_score_cp(value * 100 / UCI::NormalizeToPawnValue);
214         } else {
215                 score->set_score_type(HashProbeScore::SCORE_MATE);
216                 score->set_score_mate((value > 0 ? VALUE_MATE - value + 1 : -VALUE_MATE - value) / 2);
217         }
218 }
219
220 HashProbeThread::HashProbeThread(const std::string &server_address) {
221         builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
222         builder.RegisterService(&service);
223         server = std::move(builder.BuildAndStart());
224         std::cout << "Server listening on " << server_address << std::endl;
225         std::thread([this]{ server->Wait(); }).detach();
226 }
227
228 void HashProbeThread::Shutdown() {
229         server->Shutdown();
230 }
231
232 int main(int argc, char* argv[]) {
233
234     std::cout << engine_info() << std::endl;
235
236     CommandLine::init(argc, argv);
237     UCI::init(Options);
238     Tune::init();
239     Bitboards::init();
240     Position::init();
241     Threads.set(size_t(Options["Threads"]));
242     Search::clear();  // After threads are up
243     Eval::NNUE::init();
244
245     UCI::loop(argc, argv);
246
247     Threads.set(0);
248     return 0;
249 }