1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use self::params::SearchParams;
use super::stats::SearchStats;
use super::*;
use crate::cache::counters::CMTable;
use crate::cache::history::HTable;
use crate::cache::killers::KTable;
use crate::cache::pawns::PHTable;
use crate::cache::search::TTable;
use crate::engine::clock;
use crate::state::movescan::Move;
use crate::state::representation::Board;
use crate::utils::panic_fast;
use std::cmp;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::RwLock;
use std::thread;
use std::time::SystemTime;

pub struct SearchContext {
    pub board: Board,
    pub params: SearchParams,
    pub search_id: u8,
    pub time: u32,
    pub inc_time: u32,
    pub current_depth: i8,
    pub forced_depth: i8,
    pub max_nodes_count: u64,
    pub max_move_time: u32,
    pub moves_to_go: u32,
    pub moves_to_search: Vec<Move>,
    pub search_time_start: SystemTime,
    pub deadline: u32,
    pub multipv: bool,
    pub lines: Vec<SearchResultLine>,
    pub search_done: bool,
    pub uci_debug: bool,
    pub ponder_mode: bool,
    pub syzygy_enabled: bool,
    pub syzygy_probe_limit: u32,
    pub syzygy_probe_depth: i8,
    pub ttable: Arc<TTable>,
    pub phtable: Arc<PHTable>,
    pub ktable: KTable,
    pub htable: HTable,
    pub cmtable: CMTable,
    pub helper_contexts: Arc<RwLock<Vec<SearchContext>>>,
    pub abort_flag: Arc<AtomicBool>,
    pub ponder_flag: Arc<AtomicBool>,
    pub stats: SearchStats,
    pub last_score: i16,
}

pub struct SearchResult {
    pub time: u32,
    pub depth: i8,
}

pub struct SearchResultLine {
    pub score: i16,
    pub pv_line: Vec<Move>,
}

impl SearchContext {
    /// Constructs a new instance of [SearchContext] with parameters as follows:
    ///  - `board` - initial position of the board
    ///  - `ttable` - transposition table
    ///  - `phtable` - pawn hash table
    ///  - `abort_flag` - flag used to abort search from the outside of the context
    ///  - `ponder_flag` - flag used to change a search mode from pondering to the regular one
    pub fn new(board: Board, ttable: Arc<TTable>, phtable: Arc<PHTable>, abort_flag: Arc<AtomicBool>, ponder_flag: Arc<AtomicBool>) -> Self {
        Self {
            board,
            params: SearchParams::default(),
            search_id: 0,
            time: 0,
            inc_time: 0,
            current_depth: 1,
            forced_depth: 0,
            max_nodes_count: 0,
            max_move_time: 0,
            moves_to_go: 0,
            moves_to_search: Vec::new(),
            search_time_start: SystemTime::now(),
            deadline: 0,
            multipv: false,
            lines: Vec::new(),
            search_done: false,
            uci_debug: false,
            ponder_mode: false,
            syzygy_enabled: false,
            syzygy_probe_limit: 0,
            syzygy_probe_depth: 0,
            ttable,
            phtable,
            ktable: KTable::default(),
            htable: HTable::default(),
            cmtable: CMTable::default(),
            helper_contexts: Arc::default(),
            abort_flag,
            ponder_flag,
            stats: SearchStats::default(),
            last_score: 0,
        }
    }
}

impl Iterator for SearchContext {
    type Item = SearchResult;

    /// Performs the next iteration of the search, using data stored in the context. Returns [None] if any of the following conditions is true:
    ///  - the search has been done in the previous iteration or the current depth is about to exceed [MAX_DEPTH] value
    ///  - `self.forced_depth` is not 0 and the current depth is about to exceed this value
    ///  - instant move is possible
    ///  - Syzygy tablebase move is possible
    ///  - time allocated for the current search has expired
    ///  - mate score has detected and was recognized as reliable
    ///  - search was aborted
    fn next(&mut self) -> Option<Self::Item> {
        // This loop works here as goto, which allows restarting search when switching from pondering mode to regular search within the same iteration
        loop {
            if self.search_done || self.current_depth >= MAX_DEPTH {
                return None;
            }

            if self.forced_depth != 0 && self.current_depth > self.forced_depth {
                return None;
            }

            // If the max depth was reached, but search is in ponder mode, wait for "ponderhit" or "stop" command before executing the last iteration
            if self.ponder_mode && self.forced_depth != 0 && self.current_depth == self.forced_depth {
                loop {
                    if self.abort_flag.load(Ordering::Relaxed) {
                        break;
                    }
                }
            }

            // Check instant move and Syzygy tablebase move only if there's no forced depth to reach
            if self.forced_depth == 0 && self.current_depth == 1 {
                if let Some(r#move) = self.board.get_instant_move() {
                    self.search_done = true;
                    self.lines.push(SearchResultLine::new(0, vec![r#move]));

                    return Some(SearchResult::new(0, self.current_depth));
                }

                if self.syzygy_enabled {
                    if let Some((r#move, score)) = self.board.get_tablebase_move(self.syzygy_probe_limit) {
                        self.search_done = true;
                        self.stats.tb_hits = 1;
                        self.lines.push(SearchResultLine::new(score, vec![r#move]));

                        return Some(SearchResult::new(0, self.current_depth));
                    }
                }
            }

            let desired_time = if self.max_move_time != 0 {
                self.max_move_time
            } else {
                let desired_time = clock::get_time_for_move(self.board.fullmove_number, self.time, self.inc_time, self.moves_to_go);

                // Desired time can't exceed the whole available time
                cmp::min(desired_time, self.time)
            };

            self.deadline = if self.max_move_time != 0 {
                self.max_move_time
            } else if self.current_depth > 1 {
                let deadline = ((desired_time as f32) * DEADLINE_MULTIPLIER) as u32;

                // Deadline can't exceed the whole available time
                cmp::min(deadline, self.time)
            } else {
                u32::MAX
            };

            self.lines.clear();

            let helper_contexts_arc = self.helper_contexts.clone();
            let mut helper_contexts_lock = helper_contexts_arc.write().unwrap();

            thread::scope(|scope| {
                let depth = self.current_depth;
                let mut threads = Vec::new();

                for helper_context in helper_contexts_lock.iter_mut() {
                    helper_context.forced_depth = depth;
                    threads.push(scope.spawn(move || {
                        search::run(helper_context, depth);
                    }));
                }

                search::run(self, self.current_depth);

                let reset_abort_flag = !self.abort_flag.load(Ordering::Relaxed);
                self.abort_flag.store(true, Ordering::Relaxed);

                for thread in threads {
                    thread.join().unwrap();
                }

                if reset_abort_flag {
                    self.abort_flag.store(false, Ordering::Relaxed);
                }
            });

            for helper_context in helper_contexts_lock.iter() {
                self.stats += &helper_context.stats;
            }

            if self.abort_flag.load(Ordering::Relaxed) {
                // If ponder flag is set, the search is completly restarted within the same iteration
                if self.ponder_flag.load(Ordering::Relaxed) {
                    self.current_depth = 1;
                    self.forced_depth = 0;
                    self.search_time_start = SystemTime::now();
                    self.stats = SearchStats::default();

                    self.ponder_flag.store(false, Ordering::Relaxed);
                    self.abort_flag.store(false, Ordering::Relaxed);

                    continue;
                } else {
                    if self.uci_debug {
                        println!("info string Search aborted");
                    }

                    return None;
                }
            }

            if self.lines.is_empty() || self.lines[0].pv_line.is_empty() {
                println!("info string Invalid position");
                return None;
            }

            if self.lines[0].pv_line[0].is_empty() {
                panic_fast!("Invalid PV move: {}", self.lines[0].pv_line[0]);
            }

            let search_time = self.search_time_start.elapsed().unwrap().as_millis() as u32;

            self.lines.sort_by(|a, b| a.score.cmp(&b.score).reverse());
            self.current_depth += 1;

            if self.forced_depth == 0 && self.max_nodes_count == 0 {
                if search_time > ((desired_time as f32) * TIME_THRESHOLD_RATIO) as u32 {
                    self.search_done = true;
                }

                // Checkmate score must indicate that the depth it was found is equal or smaller than the current one, to prevent endless move sequences
                if is_score_near_checkmate(self.lines[0].score) && self.current_depth >= (CHECKMATE_SCORE - self.lines[0].score.abs()) as i8 {
                    self.search_done = true;
                }
            }

            return Some(SearchResult::new(search_time, self.current_depth - 1));
        }
    }
}

impl SearchResult {
    /// Constructs a new instance of [SearchResult] with stored `time` and `depth`.
    pub fn new(time: u32, depth: i8) -> Self {
        Self { time, depth }
    }
}

impl SearchResultLine {
    /// Constructs a new instance of [SearchResultLine] with stored `score` and `pv_line`.
    pub fn new(score: i16, pv_line: Vec<Move>) -> Self {
        Self { score, pv_line }
    }
}