-
Notifications
You must be signed in to change notification settings - Fork 0
/
Engine.hpp
1772 lines (1657 loc) · 67.7 KB
/
Engine.hpp
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include "Piece.hpp"
#include <memory>
#include <algorithm>
#include <valarray>
#include <unordered_set>
#include <FEN.hpp>
#include <PGN.hpp>
#include <Board.hpp>
#include <Perft.hpp>
#include <DebugTracer.hpp>
#include <tbconfig.h>
class Engine : public Perft {
public:
static constexpr bool ENABLE_TT = true;
static constexpr bool ENABLE_TT_RETURN = true && ENABLE_TT;
static constexpr bool ENABLE_SELECTIVITY = true;
static constexpr bool ENABLE_SEL_BIGDELTA = true && ENABLE_SELECTIVITY,
ENABLE_SEL_DELTA = true && ENABLE_SELECTIVITY,
ENABLE_SEL_NMR = true && ENABLE_SELECTIVITY,
ENABLE_SEL_LMR = true && ENABLE_SELECTIVITY;
static constexpr bool ENABLE_IID = true;
static constexpr bool ENABLE_SYZYGY = true;
INLINE Board &as_board() { return (Board &)self; }
INLINE const Board &as_board() const { return (const Board &)self; }
// definitions and such
using score_t = int32_t;
using mval_t = float;
constexpr static score_t NOSCORE = INT32_MIN;
static constexpr score_t CENTIPAWN = 256,
MATERIAL_PAWN = 100*CENTIPAWN,
MATERIAL_KNIGHT = 325*CENTIPAWN,
MATERIAL_BISHOP = 325*CENTIPAWN,
MATERIAL_ROOK = 500*CENTIPAWN,
MATERIAL_QUEEN = 1000*CENTIPAWN,
MATERIAL_KING = 1000*MATERIAL_PAWN,
MATERIAL_KING_TB = MATERIAL_KING / 2;
std::vector<PIECE> MATERIAL_PIECE_ORDERING;
static constexpr score_t MATERIALS[] = {
MATERIAL_PAWN, MATERIAL_KNIGHT, MATERIAL_BISHOP,
MATERIAL_ROOK, MATERIAL_QUEEN, MATERIAL_KING, 0};
INLINE constexpr score_t material_of(PIECE p) const {
return MATERIALS[int(p)];
}
INLINE constexpr score_t material_of_capped(PIECE p) const {
if(p == KING)return 50*MATERIAL_PAWN;
return MATERIALS[int(p)];
}
INLINE score_t count_material(piece_bitboard_t mask) const {
score_t m = 0;
m += piece::size(mask & bits_pawns) * material_of(PAWN);
m += piece::size(mask & bits_slid_diag & ~bits_slid_orth) * material_of(BISHOP);
m += piece::size(mask & ~bits_slid_diag & bits_slid_orth) * material_of(ROOK);
m += piece::size(mask & bits_slid_diag & bits_slid_orth) * material_of(QUEEN);
m += piece::size(mask & get_knight_bits()) * material_of(KNIGHT);
return m;
}
INLINE bool tb_can_probe() const {
return ENABLE_SYZYGY && tb::can_probe(self);
}
INLINE score_t tb_probe_wdl() {
int8_t wdl = tb::probe_wdl(self);
++tb_probes;
if(wdl == -1) {
return NOSCORE;
}
++tb_hit;
switch(wdl) {
case TB_WIN:
return MATERIAL_KING_TB;
case TB_CURSED_WIN:
return 0;//MATERIAL_KING/4;
case TB_DRAW:
return 0;
case TB_BLESSED_LOSS:
return 0;//-MATERIAL_KING/4;
case TB_LOSS:
return -MATERIAL_KING_TB;
}
abort();
}
void list_probe_root_wdl() {
tb::probe_root_wdl(self, [&](move_t m, score_t approx_score, int32_t tb_rank) mutable -> void {
assert(check_valid_move(m));
str::print("WDL", "move:", pgn::_move_str(self, m),
"rank:", tb_rank, "score:", score_string(approx_score));
});
}
void list_probe_root_dtz() {
tb::probe_root_dtz(self, [&](move_t m, score_t approx_score, int32_t tb_rank) mutable -> void {
assert(check_valid_move(m));
str::print("DTZ", "move:", pgn::_move_str(self, m), "rank:", tb_rank, "score:", score_string(approx_score),
"SCORE", approx_score, "SCORE-MATE", approx_score-MATERIAL_KING, "SCORE_IS_MATE", score_is_mate(approx_score));
});
}
void list_probe_root() {
tb::probe_root(self, [&](move_t m, unsigned wdl, unsigned dtz) mutable -> void {
assert(check_valid_move(m));
str::print("DTZ", "move:", board::_move_str(m), "wdl:", tb::wdl_to_str(self, wdl), "dtz:", dtz);
});
}
INLINE score_t h_material(COLOR c) const {
score_t h = count_material(bits[c]);
const piece_bitboard_t bishops = bits[c] & bits_slid_diag & ~bits_slid_orth;
// bishop pair
if((bishops & bitmask::wcheckers) && (bishops & bitmask::bcheckers)) {
h += 10*CENTIPAWN;
}
if(bits_pawns & bits[c]) {
h += 10*CENTIPAWN;
} else {
const piece_bitboard_t side = piece::file_mask(A) | piece::file_mask(H);
h -= 2*CENTIPAWN * piece::size(bits[c] & bits_pawns & side);
h += 1*CENTIPAWN * piece::size(bits[c] & bits_pawns & ~side);
}
if(crazyhouse) {
h += MATERIAL_PAWN * n_subs[Piece::get_piece_index(PAWN, c)];
h += (MATERIAL_KNIGHT + 50*CENTIPAWN) * n_subs[Piece::get_piece_index(KNIGHT, c)];
h += MATERIAL_BISHOP * n_subs[Piece::get_piece_index(BISHOP, c)];
h += MATERIAL_ROOK * n_subs[Piece::get_piece_index(ROOK, c)];
h += MATERIAL_QUEEN * n_subs[Piece::get_piece_index(QUEEN, c)];
}
return h;
}
INLINE score_t h_attack_cells(COLOR c) const {
const piece_bitboard_t occupied = bits[WHITE] | bits[BLACK];
score_t h = 0;
decltype(auto) h_add = [&](pos_t i, score_t mat) mutable -> void {
auto a = state.attacks[i];
h += (piece::size(a & occupied) + piece::size(a)) * MATERIAL_PAWN / mat;
};
bitmask::foreach(bits[c] & bits_pawns, [&](pos_t i) mutable -> void {
h_add(i, MATERIAL_PAWN);
});
bitmask::foreach(bits[c] & bits_slid_diag & ~bits_slid_orth, [&](pos_t i) mutable -> void {
h_add(i, MATERIAL_BISHOP);
});
bitmask::foreach(bits[c] & get_knight_bits(), [&](pos_t i) mutable -> void {
h_add(i, MATERIAL_KNIGHT);
});
bitmask::foreach(bits[c] & ~bits_slid_diag & bits_slid_orth, [&](pos_t i) mutable -> void {
h_add(i, MATERIAL_ROOK);
});
bitmask::foreach(bits[c] & bits_slid_diag & bits_slid_orth, [&](pos_t i) mutable -> void {
h_add(i, MATERIAL_QUEEN);
});
h_add(pos_king[c], MATERIAL_KING);
return h;
}
// // TODO requires move generation on previous step
// INLINE score_t h_mobility(COLOR c) const {
// score_t h = 0;
// bitmask::foreach(bits[c] & ~bits_pawns, [&](pos_t i) mutable -> void {
// h += std::sqrt(piece::size(state.moves[i]));
// });
// return h;
// }
INLINE score_t h_pawn_structure(COLOR c) const {
score_t h = 0;
// zero/doubled/tripple pawns
for(pos_t f = 0; f < board::LEN; ++f) {
const piece_bitboard_t pawns_file = piece::file_mask(f) & bits_pawns & bits[c];
if(!pawns_file) {
h -= 2*CENTIPAWN;
} else {
h += 1*CENTIPAWN * (3 - piece::size(pawns_file) * 2);
}
}
for(pos_t f = A; f <= H; ++f) {
const piece_bitboard_t pawns_file = piece::file_mask(f) & bits_pawns & bits[c];
if(!pawns_file)continue;
const piece_bitboard_t furthest_pawn = (c == WHITE) ? bitmask::highest_bit(pawns_file) : bitmask::lowest_bit(pawns_file);
const pos_t pawnr = (c == WHITE) ? board::_y(bitmask::log2(pawns_file))
: board::_y(bitmask::log2_lsb(pawns_file));
piece_bitboard_t adjacent_files = piece::file_mask(f);
score_t sidepawn_decay = 1;
if(f != A)adjacent_files |= piece::file_mask(f - 1);
if(f != H)adjacent_files |= piece::file_mask(f + 1);
if(f == A || f == H) {
sidepawn_decay = 2;
}
// isolated pawns
if(!(adjacent_files & ~pawns_file & bits_pawns & bits[c])) {
h -= CENTIPAWN / 4 / sidepawn_decay;
} else {
h += CENTIPAWN / 4 / sidepawn_decay;
}
// pass-pawns
const piece_bitboard_t ahead = (c == WHITE) ? adjacent_files << (board::LEN * (1+pawnr))
: adjacent_files >> (board::LEN * (8-pawnr));
assert(~ahead & furthest_pawn);
if((ahead & bits_pawns & ~bits[c]))continue;
const score_t pawnr_abs = ((c == WHITE) ? pawnr : 7 - pawnr);
h += (CENTIPAWN / 10) * pawnr_abs * pawnr_abs / sidepawn_decay;
}
// pawn strucure coverage
h += (CENTIPAWN / 2) * piece::size(piece::get_pawn_attacks(bits_pawns & bits[c], c) & bits[c]);
return h;
}
INLINE score_t heuristic_of(COLOR c) const {
score_t h = 0;
h += h_material(c);
h += h_pawn_structure(c);
// h -= count_material(state.pins[c]);
// h += h_mobility(c);
h += h_attack_cells(c);
return h;
}
INLINE score_t evaluate(score_t wdl_score=NOSCORE) {
if(self.is_draw_nogenmoves()) {
return 0;
} else if(!self.can_skip_genmoves()) {
make_move_finalize();
if(self.is_draw_with_genmoves()){
return 0;
} else if(self.is_checkmate()) {
return -MATERIAL_KING;
}
}
const COLOR c = activePlayer();
if(self.tb_can_probe()) {
if(wdl_score == NOSCORE) {
wdl_score = self.tb_probe_wdl();
}
if(wdl_score == NOSCORE) {
wdl_score = 0;
} else if(wdl_score == 0) {
return 0;
}
} else {
wdl_score = 0;
}
return wdl_score + heuristic_of(c) - heuristic_of(enemy_of(c));
}
INLINE bool is_repeated_thought(const MoveLine &pline) {
assert(check_valid_sequence(pline));
const size_t thought_moves = pline.start;
const size_t no_iter = !crazyhouse ? std::min<size_t>(self.get_halfmoves(), thought_moves) : thought_moves;
if(no_iter < 3) {
return false;
}
for(size_t i = NO_COLORS - 1; i < no_iter; i += NO_COLORS) {
const auto &state_iter = state_hist[state_hist.size() - i - 1];
if(state.info == state_iter.info) {
return true;
}
}
return false;
}
INLINE bool is_path_dependent(const MoveLine &pline) {
return is_draw_halfmoves() || is_draw_repetition() || is_repeated_thought(pline);
}
INLINE mval_t move_heuristic_extra_material(pos_t i, pos_t j) const {
const pos_t _j = j & board::MOVEMASK;
if(crazyhouse && is_drop_move(i, j)) {
} else if(is_promotion_move(i, _j)) {
return mval_t(material_of(board::get_promotion_as(j)) - material_of(PAWN)) / MATERIAL_PAWN;
} else if(is_enpassant_take_move(i, _j)) {
return mval_t(material_of(PAWN)) / MATERIAL_PAWN;
}
return .0;
}
INLINE mval_t move_heuristic_check(pos_t i, pos_t j) const {
const pos_t _j = j & board::MOVEMASK;
if(crazyhouse && is_drop_move(i, j)) {
} else if(is_naively_checking_move(i, _j)) {
return .5;
}
return .0;
}
INLINE mval_t move_heuristic_recapture(pos_t i, pos_t j, move_t prevmove) const {
if(prevmove != board::nullmove && (bitmask::second(prevmove) & board::MOVEMASK) == (j & board::MOVEMASK)) {
return .1;
}
return .0;
}
INLINE mval_t move_heuristic_attacker_decay(pos_t i, pos_t j, piece_bitboard_t edefendmap) const {
mval_t val = .0;
const PIECE frompiece = self[i].value;
const mval_t mat_from = mval_t(material_of_capped(frompiece)) / MATERIAL_PAWN;
const pos_t _j = j & board::MOVEMASK;
if(self.empty_at_pos(_j) || (edefendmap & piece::pos_mask(_j))) {
const mval_t decay_i = (edefendmap & piece::pos_mask(_j)) ? .02 : .05;
val -= mat_from * decay_i;
} else {
val -= mat_from * .01;
}
return val;
}
INLINE mval_t move_heuristic_see(pos_t i, pos_t j, piece_bitboard_t edefendmap) const {
const pos_t _j = j & board::MOVEMASK;
mval_t val = .0;
const mval_t extra_val = move_heuristic_extra_material(i, j);
val += extra_val;
if(crazyhouse && is_drop_move(i, _j)) {
return .0;
} else if(val > 0 || is_castling_move(i, _j)) {
return val;
}
const mval_t mat_i = mval_t(material_of(self[i].value)) / MATERIAL_PAWN,
mat_j = mval_t(material_of(self[_j].value)) / MATERIAL_PAWN;
if(~edefendmap & piece::pos_mask(_j)) {
return mat_j;
} else if(mat_i < mat_j) {
return mat_j - mat_i - extra_val;
}
mval_t see = mval_t(static_exchange_evaluation(i, _j)) / MATERIAL_PAWN;
if(std::abs(see) > 100) {
see = (see < 0) ? -100 : 100;
}
val += see;
if(see < 0) {
val -= extra_val;
}
return val;
}
INLINE mval_t move_heuristic_mvv_lva(pos_t i, pos_t j, piece_bitboard_t edefendmap) const {
const pos_t _j = j & board::MOVEMASK;
mval_t val = .0;
if(is_drop_move(i, _j)) {
;
} else if(is_castling_move(i, _j)) {
;
} else if(is_naively_capture_move(i, _j)) {
const mval_t mat_to = mval_t(material_of_capped(self[_j].value)) / MATERIAL_PAWN;
val += mat_to;
const PIECE frompiece = self[i].value;
const mval_t mat_from = mval_t(material_of_capped(frompiece)) / MATERIAL_PAWN;
if(edefendmap & piece::pos_mask(_j)) {
val -= mat_from;
}
val += move_heuristic_attacker_decay(i, j, edefendmap);
}
val += move_heuristic_extra_material(i, j);
val += move_heuristic_check(i, j);
return val;
}
INLINE mval_t move_heuristic_pv(move_t m, const MoveLine &pline, move_t hashmove=board::nullmove, move_t my_threatmove=board::nullmove) const {
if(m == pline.front()) {
return 2000.;
} else if(m == hashmove || m == my_threatmove) {
return 1000.;
}
return .0;
}
INLINE size_t get_cmt_index(const MoveLine &pline, move_t m) const {
constexpr size_t NO_INDEX = SIZE_MAX;
const move_t p_m = pline.get_previous_move();
if(m != board::nullmove && p_m != board::nullmove && !(crazyhouse && is_drop_move(bitmask::first(m), bitmask::second(m)))) {
const pos_t i = bitmask::first(m), _j = bitmask::second(m);
const pos_t p_i = bitmask::first(p_m) & board::MOVEMASK;
const pos_t p_j = bitmask::second(p_m) & board::MOVEMASK;
// castling
if(self.empty_at_pos(p_j) || is_castling_move(p_i, p_j)) {
return NO_INDEX;
}
// crazyhouse, i is invalid
const size_t i_piecevalue = size_t(is_drop_move(i, _j) ? board::get_drop_as(i) : self[i].value);
const size_t cmt_outer = size_t(NO_PIECES) * size_t(board::SIZE);
const size_t cmt_index = cmt_outer * cmt_outer * size_t(activePlayer() == WHITE ? 0 : 1)
+ cmt_outer * (size_t(self[p_j].value) * size_t(board::SIZE) + p_j)
+ (i_piecevalue * size_t(board::SIZE) + _j);
return cmt_index;
}
return NO_INDEX;
}
INLINE mval_t move_heuristic_cmt(move_t m, const MoveLine &pline, const std::vector<float> &cmh_table) const {
const size_t cmt_index = get_cmt_index(pline, m);
if(cmt_index != SIZE_MAX) {
return cmh_table[cmt_index];
}
return .0;
}
static INLINE bool score_is_valid(score_t score) {
return score != NOSCORE && score != F_BREAK && score != F_CONTINUE;
}
static INLINE float score_float(score_t score) {
return float(score) / MATERIAL_PAWN;
}
static INLINE bool score_is_mate(score_t score) {
return std::abs(score) > MATERIAL_KING - 16000;
}
static INLINE bool score_is_tb(score_t score) {
return std::abs(score) > MATERIAL_KING_TB - 1000 && !score_is_mate(score);
}
static INLINE score_t score_material(score_t score) {
if(score_is_mate(score)) {
return score;
} else if(score_is_tb(score)) {
return score > 0 ? score - MATERIAL_KING_TB : score + MATERIAL_KING_TB;
}
return score;
}
static INLINE score_t score_decay(score_t score) {
if(score_is_mate(score)) {
score += (score > 0) ? -1 : 1;
}
return score;
}
static INLINE score_t score_decay(score_t score, depth_t depth) {
#ifndef NDEBUG
score_t sscore = score;
for(depth_t i = 0; i < depth; ++i) {
sscore = -score_decay(sscore);
}
#endif
if(score_is_mate(score)) {
score += (score > 0) ? -depth : depth;
}
score = (depth & 1) ? -score : score;
assert(score == sscore);
return score;
}
static INLINE depth_t score_mate_in(score_t score) {
assert(score_is_mate(score));
const int mate_in = int(MATERIAL_KING - std::abs(score));
return (score < 0) ? -mate_in : mate_in;
}
static INLINE std::string score_string(score_t score) {
char s[256];
if(score == NOSCORE) {
snprintf(s, sizeof(s), "noscore");
} else if(score_is_mate(score)) {
snprintf(s, sizeof(s), "MATE%s%d", score > 0 ? "+":(score_mate_in(score)==0?"-":""), (int)score_mate_in(score));
} else {
snprintf(s, sizeof(s), "%s%.05f", score>0?"+":(score==0?" ":""), score_float(score));
}
return s;
}
static INLINE bool mval_is_primary(mval_t mval) {
return mval > 999.;
}
static INLINE bool mval_is_tbwin(mval_t mval) {
return !mval_is_primary(mval) && mval > 800.;
}
static INLINE bool mval_is_tb_cursedwin(mval_t mval) {
return !mval_is_primary(mval) && !mval_is_tbwin(mval) && mval > 400.;
}
static INLINE bool mval_is_tb_windraw(mval_t mval) {
return mval_is_tbwin(mval) || mval_is_tb_cursedwin(mval);
}
INLINE score_t get_pvline_score(const MoveLine &pline) {
assert(check_valid_sequence(pline));
score_t score = NOSCORE;
walk_unfinalized_end(pline, [&](const ply_index_t d) mutable -> void {
score = score_decay(evaluate(), d);
});
return score;
}
INLINE bool check_pvline_score(const MoveLine &pline, score_t score) {
const score_t pvscore = get_pvline_score(pline);
return score == pvscore && (!pline.tb || (pvscore == 0 || score_is_tb(pvscore)));
}
decltype(auto) get_least_valuable_piece(piece_bitboard_t mask) const {
// short-hands for bits
const piece_bitboard_t diag = self.bits_slid_diag,
orth = self.bits_slid_orth;
// get some piece that is minimal
piece_bitboard_t found = 0x00ULL;
for(const auto p : MATERIAL_PIECE_ORDERING) {
switch(p) {
case PAWN: if(mask & self.bits_pawns) found = mask & self.bits_pawns; break;
case KNIGHT: if(mask & self.get_knight_bits()) found = mask & self.get_knight_bits(); break;
case BISHOP: if(mask & diag & ~orth) found = mask & diag & ~orth; break;
case ROOK: if(mask & ~diag & orth) found = mask & ~diag & orth; break;
case QUEEN: if(mask & diag & orth) found = mask & diag & orth; break;
case KING: if(mask & get_king_bits()) found = mask & get_king_bits(); break;
default: break;
}
if(found)return std::make_pair(bitmask::highest_bit(found), p);
}
return std::make_pair(UINT64_C(0), EMPTY);
}
score_t static_exchange_evaluation(pos_t i, pos_t j) const {
assert(j <= board::MOVEMASK);
std::array<score_t, 37> gain;
int8_t depth = 0;
const piece_bitboard_t may_xray = bits_slid_diag | bits_slid_orth | bits_pawns;
piece_bitboard_t from_set = piece::pos_mask(i);
piece_bitboard_t occupied = bits[WHITE] | bits[BLACK];
piece_bitboard_t attadef = get_attacks_to(j, BOTH, occupied);
// optional: remove pinned pieces (inaccurately)
if(!(attadef & get_king_bits())) {
attadef &= ~(state.pins[WHITE] | state.pins[BLACK]);
}
assert(self[j].value != KING);
gain[depth] = material_of(self[j].value);
PIECE curpiece = self[i].value;
do {
// const pos_t from = bitmask::log2_of_exp2(from_set);
++depth;
gain[depth] = material_of(curpiece) - gain[depth - 1];
// str::pdebug("SEE: depth:", depth, "piece:", board::_pos_str(from) + " "s + self[from].str(), "score:"s, gain[depth]);
if(std::max(-gain[depth-1], gain[depth]) < 0) {
// str::pdebug("SEE BREAK: max(", -gain[depth-1], ",", gain[depth], ") < 0");
break;
}
attadef &= ~from_set;
occupied &= ~from_set;
if(from_set & may_xray) {
if(from_set & bits_slid_diag) {
attadef |= get_sliding_diag_attacks_to(j, occupied);
}
if(from_set & bits_slid_orth) {
attadef |= get_sliding_orth_attacks_to(j, occupied);
}
}
const COLOR c = self.color_at_pos((depth & 1) ? j : i);
std::tie(from_set, curpiece) = get_least_valuable_piece(attadef & bits[c]);
} while(from_set);
// uint8_t maxdepth = depth;
while(--depth) {
gain[depth-1] = -std::max(-gain[depth-1], gain[depth]);
}
// for(uint8_t i = 0; i < maxdepth; ++i) {
// str::pdebug("gain[", i, "] = ", gain[i]);
// }
return gain[0];
}
struct tt_eval_entry {
board_info info;
score_t eval;
};
INLINE score_t e_ttable_probe(zobrist::ttable<tt_eval_entry> &e_ttable) {
return evaluate();
// const zobrist::key_t k = zb_hash();
// if(e_ttable[k].info == state.info) {
// return e_ttable[k].eval;
// }
// const score_t eval = evaluate();
// const bool overwrite = true;
// if(overwrite) {
// e_ttable[k] = { .info=state.info, .eval=eval };
// }
// return eval;
}
typedef enum { TT_EXACT, TT_ALLNODE, TT_CUTOFF } TT_NODE_TYPE;
struct tt_ab_entry {
TT_NODE_TYPE ndtype : 2;
depth_t depth : 15;
ply_index_t age : 15;
score_t score;
board_info info;
#ifndef NDEBUG
std::array<move_t, 3> m_hint;
MoveLine subpline;
#else
std::array<move_t, 20> m_hint;
#endif
INLINE bool can_apply(const board_info &_info, depth_t _depth, ply_index_t _age) const {
return !is_inactive(_age) && depth >= _depth && info == _info
// avoid stack overflow by limiting depth difference
&& !(_depth + (depth_t)m_hint.size() <= depth);
}
INLINE bool can_use_move(const board_info &_info, depth_t _depth, ply_index_t _age) const {
if(is_inactive(_age))return false;
if(depth <= 0) {
return info == _info;
}
return ((depth >= _depth - 1 && ndtype == TT_ALLNODE)
|| ndtype == TT_EXACT
|| (ndtype == TT_CUTOFF && depth >= depth - 3))
&& info == _info;
}
INLINE move_t front() const {
assert(m_hint.size() > 0);
return m_hint.front();
}
INLINE move_t back() const {
assert(m_hint.size() > 0);
return m_hint.back();
}
INLINE bool should_replace(depth_t _depth, TT_NODE_TYPE _ndtype, int16_t _age) const {
if(is_inactive(_age))return true;
switch(_ndtype) {
case TT_CUTOFF: return _depth >= depth && ndtype != TT_EXACT;
case TT_ALLNODE:return _depth >= depth && ndtype != TT_EXACT;
case TT_EXACT: return _depth >= depth;
default: break;
}
abort();
}
INLINE bool is_inactive(ply_index_t cur_age) const {
return info.is_unset() || cur_age != age;
}
INLINE void write(const board_info &_info, score_t _score, depth_t _depth, ply_index_t _age, TT_NODE_TYPE _ndtype, const MoveLine &pline) {
assert(!pline.tb);
info=_info, depth=_depth, score=_score, age=_age, ndtype=_ndtype;
for(size_t i = 0; i < m_hint.size(); ++i) {
m_hint[i] = (pline.size() > i) ? pline[i] : board::nullmove;
}
#ifndef NDEBUG
subpline=pline.get_future();
#endif
}
};
struct alpha_beta_state {
zobrist::ttable<tt_ab_entry> &ab_ttable;
zobrist::ttable<tt_eval_entry> &e_ttable;
std::vector<float> &cmh_table;
const depth_t initdepth;
const std::unordered_set<move_t> &searchmoves;
void normalize_cmh_table(size_t cmt_index) {
if(cmh_table[cmt_index] > .5) {
const float mx = *std::max_element(cmh_table.begin(), cmh_table.end());
_printf("renormalizing countermove table\n");
for(auto &cm : cmh_table) {
cm /= (mx * 1e7);
}
}
}
};
INLINE decltype(auto) make_callback_f() {
return [&](...) -> bool { return true; };
}
decltype(auto) ab_ttable_probe(score_t &alpha, score_t &beta, depth_t depth, move_t &hashmove, move_t &your_threatmove,
MoveLine &pline, alpha_beta_state &ab_state, bool allow_nullmoves, int8_t nchecks=0)
{
const zobrist::key_t k = zb_hash();
const bool tt_has_entry = ab_state.ab_ttable[k].can_apply(state.info, depth, tt_age);
if(tt_has_entry) {
++zb_hit;
} else {
++zb_miss;
}
const bool scoutsearch = (alpha + 1 == beta);
auto &zb = ab_state.ab_ttable[k];
debug.update_line(depth, alpha, beta, pline);
score_t maybe_result = NOSCORE;
if(tt_has_entry) {
debug.update_mem(depth, alpha, beta, zb, pline);
if(zb.ndtype == TT_EXACT || (zb.score < alpha && zb.ndtype == TT_ALLNODE) || (zb.score >= beta && zb.ndtype == TT_CUTOFF)) {
make_move_finalize();
bool draw_pathdep = false;
// zb.back() == board::nullmove means slot capacity isn't exceeded
if(ENABLE_TT_RETURN && zb.back() == board::nullmove) {
++nodes_searched;
walk_unfinalized_early_stop(zb.m_hint,
[&](const move_t m, auto &&do_step_f) mutable -> bool {
if(m == board::nullmove) {
return false;
}
assert(check_valid_move(m, true));
do_step_f();
if(is_draw_halfmoves() || is_draw_repetition()) {
draw_pathdep = true;
return false;
}
return true;
}
);
if(!draw_pathdep) {
pline.clear();
pline.draft_line(zb.m_hint);
maybe_result = zb.score;
debug.check_score(zb.depth, maybe_result, pline);
if(!state.moves_initialized)++n_skips;
return std::make_pair(k, maybe_result);
}
}
if(!draw_pathdep) {
// pline.draft_line(zb.m_hint);
bool can_return_score = false;
depth_t R = 0;
MoveLine pline_alt = pline.branch_from_past();
walk_unfinalized_early_stop(zb.m_hint,
// foreach
[&](const move_t m, auto &&do_step_f) mutable -> bool {
if(m == board::nullmove) {
return false;
}
assert(check_valid_move(m, true));
pline_alt.premove(m);
do_step_f();
if(is_draw_halfmoves() || is_draw_repetition()) {
draw_pathdep = true;
return false;
}
return true;
},
// endfunc
[&](const ply_index_t nsteps) mutable -> void {
R = nsteps;
if(!draw_pathdep) {
draw_pathdep = is_draw_repetition() || is_draw_halfmoves();
}
// doesn't lead to path-dependent draw
// changed halfmove clock or pvline at least zb.depth - depth
const depth_t subdepth = zb.depth - R;
can_return_score = !draw_pathdep && (R < (ssize_t)zb.m_hint.size() || subdepth < depth || get_halfmoves() < R) && (state.info != zb.info);
if(can_return_score) {
score_t _alpha=alpha, _beta=beta;
if(R & 1)_alpha=-beta,_beta=-alpha;
score_t score = NOSCORE;
if(subdepth >= 0) {
if(!scoutsearch) {
score = alpha_beta_pv(_alpha,_beta,subdepth,pline_alt,ab_state,allow_nullmoves,make_callback_f());
debug.check_score(depth, score, pline_alt);
} else {
assert(_alpha + 1 == _beta);
score = alpha_beta_scout(_beta,subdepth,pline_alt,ab_state,allow_nullmoves);
debug.check_score(depth, score, pline_alt);
}
} else {
score = alpha_beta_quiescence(_alpha,_beta,subdepth,pline_alt,ab_state,nchecks);
debug.check_score(depth, score, pline_alt);
}
debug.check_score(subdepth, score, pline_alt);
if((score < alpha && zb.ndtype == TT_ALLNODE) || (score >= beta && zb.ndtype == TT_CUTOFF)) {
// note: current position rolls back only after return statement
maybe_result = score_decay(score, R);
} else {
can_return_score = false;
}
assert(check_valid_sequence(pline_alt));
}
}
);
pline_alt.recall_n(R);
assert(check_valid_sequence(pline_alt));
if(can_return_score) {
assert(check_valid_sequence(pline));
pline.replace_line(pline_alt);
debug.check_score(zb.depth, maybe_result, pline);
return std::make_pair(k, maybe_result);
}
}
} else if(alpha < zb.score && zb.score < beta) {
if(zb.ndtype == TT_CUTOFF) {
alpha = zb.score;
} else if(zb.ndtype == TT_ALLNODE) {
beta = zb.score;
} else {
str::perror("error: unknown node type");
abort();
}
}
hashmove = zb.front();
} else if(zb.can_use_move(state.info, depth, tt_age)) {
hashmove = zb.front();
// if(zb.m_hint.size() >= 2) {
// your_threatmove = zb.m_hint[1];
// }
}
return std::make_pair(k, maybe_result);
}
INLINE bool is_knight_fork_move(pos_t i, pos_t j) const {
if(piece::pos_mask(i) & ~get_knight_bits())return false;
const COLOR c = activePlayer();
const COLOR ec = enemy_of(c);
const piece_bitboard_t attack_mask = get_attack_mask(ec);
const piece_bitboard_t targets = (bits_slid_orth | ((bits_pawns | bits_slid_orth) & ~attack_mask) | get_king_bits()) & bits[ec];
return piece::size(piece::get_knight_attack(j) & targets) >= 2;
}
INLINE bool is_pawn_fork_move(pos_t i, pos_t j) const {
if(piece::pos_mask(i) & ~bits_pawns)return false;
const COLOR c = activePlayer();
const COLOR ec = enemy_of(c);
const pos_t j_mask = piece::pos_mask(j);
const piece_bitboard_t notpinned = bits[ec] & ~state.pins[ec];
return (~(
piece::get_knight_attacks(get_knight_bits() & notpinned)
| piece::get_pawn_attacks(bits_pawns & notpinned, ec)
) & j_mask)
&& (~piece::get_sliding_diag_attacks(bits_slid_diag & ~bits_slid_orth & notpinned, bits[c] | bits[ec]) & j_mask)
&& piece::size(piece::get_pawn_attack(j, c) & bits[ec] & ~bits_pawns) == 2;
}
INLINE bool has_promoting_pawns() const {
const COLOR c = activePlayer();
const piece_bitboard_t pawnrank = piece::rank_mask(c == WHITE ? -1+1 : -1+8);
const piece_bitboard_t promoting_pawns = bits[c] & bits_pawns & pawnrank;
bool has_moves = false;
bitmask::foreach_early_stop(promoting_pawns, [&](pos_t i) mutable -> bool {
if(state.moves_initialized) {
has_moves = state.moves[i];
} else {
return ~(bits[WHITE]|bits[BLACK]) & (i + (c == WHITE ? board::LEN : -board::LEN));
}
return !has_moves;
});
return has_moves;
}
INLINE bool abq_should_use_move(move_t m, mval_t &val, bool &reduce_nchecks,
depth_t depth, size_t nchecks, bool king_in_check, move_t hashmove,
const piece_bitboard_t edefendmap, const piece_bitboard_t pawn_attacks) const
{
pos_t i = bitmask::first(m), j = bitmask::second(m);
j &= board::MOVEMASK;
reduce_nchecks = false;
const bool allow_checking = (nchecks > 0 && -depth < 3);
if(king_in_check) {
val = move_heuristic_mvv_lva(i, j, edefendmap);
} else if(crazyhouse && is_drop_move(i, j)) {
return false;
} else if(is_promotion_move(i, j) || is_enpassant_take_move(i, j)) {
val = move_heuristic_see(i, j, edefendmap);
if(val < -1e-9)return false;
} else if(is_naively_capture_move(i, j)) {
if(material_of(self[i].value) + 1e-9 < material_of(self[j].value) && (~edefendmap & piece::pos_mask(j))) {
val = move_heuristic_mvv_lva(i, j, edefendmap) + .01;
} else {
val = move_heuristic_see(i, j, edefendmap);
if(val < -1e-9)return false;
}
} else if((~pawn_attacks & piece::pos_mask(j)) && (is_knight_fork_move(i, j) || is_pawn_fork_move(i, j))) {
const score_t see = static_exchange_evaluation(i, j);
if(see < 0)return false;
val = .0;
} else if((allow_checking && is_naively_checking_move(i, j))) {
const score_t see = static_exchange_evaluation(i, j);
if(see < 0)return false;
reduce_nchecks = (m != hashmove);
val += .1;
} else {
return false;
}
return true;
}
INLINE bool abq_should_use_move(move_t m, mval_t &val, bool &reduce_nchecks,
depth_t depth, size_t nchecks, bool king_in_check, move_t hashmove) const
{
const COLOR c = activePlayer();
const COLOR ec = enemy_of(c);
const piece_bitboard_t edefendmap = get_attack_mask(ec) & bits[ec];
const piece_bitboard_t pawn_attacks = piece::get_pawn_attacks(bits_pawns & bits[ec], ec);
return abq_should_use_move(m, val, reduce_nchecks, depth, nchecks, king_in_check, hashmove, edefendmap, pawn_attacks);
}
decltype(auto) abq_get_ordered_moves(depth_t depth, const MoveLine &pline, const std::vector<float> &cmh_table,
int8_t nchecks, bool king_in_check, move_t hashmove=board::nullmove) const
{
std::vector<std::tuple<mval_t, move_t, bool>> quiescmoves;
quiescmoves.reserve(8);
const COLOR c = activePlayer();
const COLOR ec = enemy_of(c);
const piece_bitboard_t edefendmap = get_attack_mask(ec) & bits[ec];
const piece_bitboard_t pawn_attacks = piece::get_pawn_attacks(bits_pawns & bits[ec], ec);
iter_moves([&](pos_t i, pos_t j) mutable -> void {
const move_t m = bitmask::_pos_pair(i, j);
mval_t val = .0;
j &= board::MOVEMASK;
bool reduce_nchecks = false;
bool ret = abq_should_use_move(m, val, reduce_nchecks, depth, nchecks, king_in_check, hashmove, edefendmap, pawn_attacks);
if(!ret)return;
if(val > -.75) {
val += move_heuristic_pv(m, pline, hashmove);
}
val += move_heuristic_cmt(m, pline, cmh_table);
quiescmoves.emplace_back(val, m, reduce_nchecks);
});
std::sort(quiescmoves.begin(), quiescmoves.end(), std::greater<>());
return quiescmoves;
}
template <typename MovesT, typename F>
INLINE decltype(auto) _iterate_ordered_ranked_moves(size_t start_index, size_t i, const MovesT &moves, F &&func) {
for(size_t j = start_index; j < moves.size(); ++j, ++i) {
const score_t res = func(i, moves[j], moves.size());
if(res == F_BREAK || res != F_CONTINUE) {
return std::make_pair(moves.size(), res);
}
}
return std::make_pair(moves.size(), NOSCORE);
}
template <typename FF, typename F>
INLINE decltype(auto) _iterate_order_moves(move_t pvmove, size_t i, FF &&get_ordered_moves_f, F &&func) {
decltype(auto) moves = get_ordered_moves_f();
if(moves.empty()) {
return std::make_pair((size_t)0, NOSCORE);
}
assert(check_valid_move(pvmove, false));
#ifndef NDEBUG
bool has_pvmove = false;
for(const auto &t:moves) {
if(std::get<1>(t) == pvmove){
has_pvmove = true;
break;
}
}
assert(pvmove == board::nullmove || (i == 1 && std::get<1>(moves[0]) == pvmove) || !has_pvmove);
#endif
const size_t start_index = (std::get<1>(moves.front()) == pvmove) ? 1 : 0;
return _iterate_ordered_ranked_moves(start_index, i, moves, std::forward<F>(func));
}
static constexpr score_t F_CONTINUE = NOSCORE + 1,
F_BREAK = NOSCORE + 2;
template <typename MF, typename FF, typename F, typename PVF>
decltype(auto) _iterate_ranked_moves(const MoveLine &pline, MF &&should_use_pvmove_f, FF &&get_ordered_moves_f, F &&func, PVF &&ret_pv_f) {
size_t i = 0;
move_t pvmove = board::nullmove;
if(!state.moves_initialized && pline.front() != board::nullmove && should_use_pvmove_f(pline.front())) {
pvmove = pline.front();
const mval_t mval = 2000.;
const score_t res = func(i, ret_pv_f(pvmove, mval), (size_t)20);
if(res == F_BREAK || res != F_CONTINUE) {
return std::make_pair((size_t)1, res);
}
++i;
}
return _iterate_order_moves(pvmove, i, std::forward<FF>(get_ordered_moves_f), std::forward<F>(func));
}
template <typename MF, typename F, typename FF>
INLINE decltype(auto) abq_iterate_ranked_moves(const MoveLine &pline, MF &&should_use_pvmove_f, FF &&get_ordered_moves_f, F &&func) {
return _iterate_ranked_moves(pline,
std::forward<MF>(should_use_pvmove_f),
std::forward<FF>(get_ordered_moves_f),
std::forward<F>(func),
[&](const move_t pvmove, mval_t mval) mutable -> decltype(auto) {
return std::make_tuple(mval, pvmove, false);
}
);
}
INLINE score_t ab_terminal_score() {
if(self.is_draw_nogenmoves()) {
return 0;
} else if(self.can_skip_genmoves()) {
return NOSCORE;
}
make_move_finalize();
if(self.is_draw_with_genmoves()) {
return 0;
} else if(self.is_checkmate()) {
return -MATERIAL_KING;