mirror of
https://github.com/HChaZZY/Stockfish.git
synced 2025-12-21 01:27:16 +08:00
Compare commits
600 Commits
sf_2.1.1
...
sf_2.3.1_b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cb2722c95 | ||
|
|
3caeabf73b | ||
|
|
fdbe8006e0 | ||
|
|
09acdac56b | ||
|
|
e4a0482e43 | ||
|
|
22a5f91aa7 | ||
|
|
9ce7469846 | ||
|
|
4b7dbb3922 | ||
|
|
e0035e9ca9 | ||
|
|
0a18adb02a | ||
|
|
630b3b2482 | ||
|
|
6008f6538e | ||
|
|
afcee1e8a4 | ||
|
|
e0bd0f250b | ||
|
|
1598a3edf8 | ||
|
|
0dacab65eb | ||
|
|
834bd9edd7 | ||
|
|
6e840f8033 | ||
|
|
2379312028 | ||
|
|
37db62b2ea | ||
|
|
b50ce5ebfb | ||
|
|
5900ab76a0 | ||
|
|
e6d8e74152 | ||
|
|
9cdca7516c | ||
|
|
6436e75858 | ||
|
|
831f91b859 | ||
|
|
1258c7aabe | ||
|
|
8dcb4bc3cc | ||
|
|
0a003d3ba1 | ||
|
|
92e759a676 | ||
|
|
3df2c01b57 | ||
|
|
8991a6f005 | ||
|
|
16f380e5c1 | ||
|
|
cbd7ce468c | ||
|
|
b6883c872d | ||
|
|
fde0b9e701 | ||
|
|
7a2825053e | ||
|
|
4e619a13d6 | ||
|
|
0de9257610 | ||
|
|
b84af67f4c | ||
|
|
7c8b7222f5 | ||
|
|
ec9038b7b4 | ||
|
|
ab65d3fd0e | ||
|
|
e8b7109eff | ||
|
|
0c6ed5929c | ||
|
|
2f4a9a140a | ||
|
|
dba1bc354a | ||
|
|
4b19430103 | ||
|
|
7c1f8dbde9 | ||
|
|
2c1ba2ab0d | ||
|
|
b011818917 | ||
|
|
bc4de9edae | ||
|
|
9de4ee6d32 | ||
|
|
90ec4a403a | ||
|
|
b61ec33f22 | ||
|
|
1f7b5d9a79 | ||
|
|
5c6ba81cf2 | ||
|
|
591adf564a | ||
|
|
f0db6a6c0b | ||
|
|
520e680278 | ||
|
|
abc6a0be2f | ||
|
|
9dbda6652e | ||
|
|
5dc0df8435 | ||
|
|
6e5a334c95 | ||
|
|
6becc81446 | ||
|
|
6b5322ce00 | ||
|
|
67d91dfd50 | ||
|
|
089e54c7fd | ||
|
|
0b3ffb54b7 | ||
|
|
775488340e | ||
|
|
7d2530873e | ||
|
|
18505f1fc4 | ||
|
|
dc88cd691f | ||
|
|
ebe8009aff | ||
|
|
628808a113 | ||
|
|
dc7fd868f4 | ||
|
|
7b4aa10708 | ||
|
|
960a689769 | ||
|
|
5f5d056c8f | ||
|
|
9c7e2c8f9d | ||
|
|
4f5680950a | ||
|
|
9793fa1906 | ||
|
|
0446fc85de | ||
|
|
764d3f44b6 | ||
|
|
0412f4a1ee | ||
|
|
6828325881 | ||
|
|
61a054b170 | ||
|
|
3361ad4242 | ||
|
|
6c9c6dd989 | ||
|
|
a358dfe934 | ||
|
|
0ecc920a09 | ||
|
|
f86182e791 | ||
|
|
c19a6ef82d | ||
|
|
ecb84464f9 | ||
|
|
1b2af05ea6 | ||
|
|
caef319219 | ||
|
|
2f47844c7c | ||
|
|
b9bc6e823f | ||
|
|
5e90580088 | ||
|
|
ef0496ff40 | ||
|
|
96f4ab48d8 | ||
|
|
39c08c17c5 | ||
|
|
b93693b831 | ||
|
|
cdfe43eb8f | ||
|
|
456f37b8ab | ||
|
|
e8d89ca5b0 | ||
|
|
2aac860db3 | ||
|
|
8b00e50cb7 | ||
|
|
be3b8f3ae9 | ||
|
|
ce159b16b9 | ||
|
|
5392007a24 | ||
|
|
f59323b56a | ||
|
|
25a9b601b2 | ||
|
|
c645aca199 | ||
|
|
44432f67d7 | ||
|
|
d66b765eb6 | ||
|
|
e72b93e44f | ||
|
|
68885f78f3 | ||
|
|
4a310baae2 | ||
|
|
d549497144 | ||
|
|
e56342ed00 | ||
|
|
0049d3f337 | ||
|
|
e0cae4bef8 | ||
|
|
9546b79e20 | ||
|
|
cc04a745e2 | ||
|
|
ce5b972736 | ||
|
|
f30f384757 | ||
|
|
676b2c8435 | ||
|
|
c2fc80e5d1 | ||
|
|
b1f57e92ce | ||
|
|
bed4075580 | ||
|
|
5a2d525048 | ||
|
|
e1919384a2 | ||
|
|
699f700162 | ||
|
|
797c960d20 | ||
|
|
673bc5526f | ||
|
|
0439a79566 | ||
|
|
37fa8adc2b | ||
|
|
2f99de0c6c | ||
|
|
7a8429d9f1 | ||
|
|
dda0fa1a43 | ||
|
|
7eb6a488ad | ||
|
|
72641dcaae | ||
|
|
6e00aa6bae | ||
|
|
9bbd27a80f | ||
|
|
adb71b8096 | ||
|
|
32c504076f | ||
|
|
304deb5e83 | ||
|
|
d84865eac3 | ||
|
|
cc6c745b54 | ||
|
|
d033d5e06a | ||
|
|
b0b9bb3462 | ||
|
|
5e18b81e87 | ||
|
|
10e64e0509 | ||
|
|
76622342ec | ||
|
|
d6e3a40c81 | ||
|
|
46a50cbf38 | ||
|
|
cc2b3ece5c | ||
|
|
22e294e044 | ||
|
|
4124c94583 | ||
|
|
a56322fde8 | ||
|
|
3d0d0237c5 | ||
|
|
d11a529904 | ||
|
|
3aa471f2a9 | ||
|
|
374c9e6b63 | ||
|
|
32d3a07c67 | ||
|
|
b978eb05dc | ||
|
|
e4efc8b741 | ||
|
|
58c2fe391d | ||
|
|
dbe5e28eaa | ||
|
|
c483ffc773 | ||
|
|
41561c9bb8 | ||
|
|
553655eb07 | ||
|
|
f01b53c374 | ||
|
|
8ec421fa14 | ||
|
|
11b0c7b44a | ||
|
|
f8224fc7d3 | ||
|
|
b356e0fae3 | ||
|
|
06f33ff1ee | ||
|
|
c47a74ec62 | ||
|
|
e26d13bb31 | ||
|
|
f41a21fefd | ||
|
|
d4c9abb967 | ||
|
|
d1e18fc7dd | ||
|
|
3c6a4bfbed | ||
|
|
3b7dbc4f6d | ||
|
|
17d1940278 | ||
|
|
258da28e79 | ||
|
|
df80232495 | ||
|
|
eb28a683bd | ||
|
|
2dfc94e0b6 | ||
|
|
7bc3688714 | ||
|
|
fc3ea7365a | ||
|
|
55376219b7 | ||
|
|
9b26356347 | ||
|
|
7c8a8e038f | ||
|
|
ee838f56f7 | ||
|
|
9934b8ec31 | ||
|
|
3dccdf5b83 | ||
|
|
4220f191d8 | ||
|
|
843a5961e1 | ||
|
|
d8e56cbe54 | ||
|
|
2ef5b4066e | ||
|
|
482b5b7ece | ||
|
|
19540c9ee8 | ||
|
|
cf0561d31a | ||
|
|
161c6b025e | ||
|
|
b966adf103 | ||
|
|
c2a68708ef | ||
|
|
34178205fc | ||
|
|
5bb766e826 | ||
|
|
96eefc4af6 | ||
|
|
8751b18cf0 | ||
|
|
2608b9249d | ||
|
|
43f84efa15 | ||
|
|
ea5616785e | ||
|
|
6a48325c49 | ||
|
|
50edb7cd73 | ||
|
|
4aadd1e401 | ||
|
|
ec5b9994b5 | ||
|
|
3441e0075d | ||
|
|
821e1c7233 | ||
|
|
6088ac2108 | ||
|
|
d8349f9d0f | ||
|
|
fd35d92c1e | ||
|
|
3b906ffc27 | ||
|
|
7b4b65d7a9 | ||
|
|
099b5e45e6 | ||
|
|
b1768c115c | ||
|
|
86e159997c | ||
|
|
576f0f6985 | ||
|
|
b46bf2950f | ||
|
|
0347339970 | ||
|
|
40e939421f | ||
|
|
b1cf1acb93 | ||
|
|
c94cfebb7e | ||
|
|
57e942145c | ||
|
|
51e8efdab5 | ||
|
|
df31398bb9 | ||
|
|
a94fd3bbec | ||
|
|
1a1742ac4f | ||
|
|
a492a9dd07 | ||
|
|
875a8079bc | ||
|
|
b76c04c097 | ||
|
|
f7b4983137 | ||
|
|
eeef654cd7 | ||
|
|
7fb6fd2f55 | ||
|
|
a189a5f0c5 | ||
|
|
24b25b4827 | ||
|
|
830ff985db | ||
|
|
3d937e1e90 | ||
|
|
04ff9c2548 | ||
|
|
28bf56e725 | ||
|
|
662d1859bd | ||
|
|
97e0b0a01e | ||
|
|
04ac1bcabe | ||
|
|
ec9b037e5f | ||
|
|
6f6be95bad | ||
|
|
b96db269a8 | ||
|
|
dcbb05ef39 | ||
|
|
e25de55fac | ||
|
|
28892666bd | ||
|
|
6058e7cf60 | ||
|
|
2a21543c88 | ||
|
|
007613cb5e | ||
|
|
1b69ef8e6c | ||
|
|
972dec454c | ||
|
|
b6b8c62ba5 | ||
|
|
db57b5f8f4 | ||
|
|
4a4513d126 | ||
|
|
2b1324eddb | ||
|
|
dfd030b67a | ||
|
|
20621ed3e3 | ||
|
|
2aec8fb956 | ||
|
|
3ec94abcdb | ||
|
|
e1907e349f | ||
|
|
f237e8b8ea | ||
|
|
103b368ab7 | ||
|
|
a29dd88f75 | ||
|
|
a1076cc68a | ||
|
|
78908b7aed | ||
|
|
d98150dffc | ||
|
|
c549f71f64 | ||
|
|
c19ea4b000 | ||
|
|
bede30e7a6 | ||
|
|
b05fbb3733 | ||
|
|
9b43fd7937 | ||
|
|
87fc9dcaa3 | ||
|
|
83f3ea7ab4 | ||
|
|
9c8c4ff46f | ||
|
|
d655147e8c | ||
|
|
3c675db3d0 | ||
|
|
cf247e7e30 | ||
|
|
0026c88b3a | ||
|
|
6482ce2bb2 | ||
|
|
867a5a8cd2 | ||
|
|
78e6b361c5 | ||
|
|
aa392c366e | ||
|
|
f80c50bcdd | ||
|
|
d282cf6964 | ||
|
|
b1fcfe4c5d | ||
|
|
30418a3cfc | ||
|
|
cb1709ef5e | ||
|
|
67338e6f32 | ||
|
|
8300ab149c | ||
|
|
c00443b19e | ||
|
|
9db9e4f7d3 | ||
|
|
22e40c8c10 | ||
|
|
e9296d694c | ||
|
|
fb4b4f772e | ||
|
|
f4dadee5e2 | ||
|
|
808a312e1c | ||
|
|
93e539d909 | ||
|
|
9d7a36121a | ||
|
|
8307da0de7 | ||
|
|
ad43ce1436 | ||
|
|
0a6532a39d | ||
|
|
20a6f99cdb | ||
|
|
4554d8b2ac | ||
|
|
9cb187762a | ||
|
|
4a8c1b2470 | ||
|
|
0759d8f430 | ||
|
|
ae65ab25d5 | ||
|
|
24417a6cd9 | ||
|
|
ad4739a6d4 | ||
|
|
a695ed65a8 | ||
|
|
750ac9ac50 | ||
|
|
07f3f0384a | ||
|
|
87b483f999 | ||
|
|
c2d42ea833 | ||
|
|
b5f6c2241b | ||
|
|
e89a8e0913 | ||
|
|
d543a64cc7 | ||
|
|
939b621e5c | ||
|
|
a77a3b723f | ||
|
|
976270916b | ||
|
|
87f7e99bc4 | ||
|
|
72d8d27234 | ||
|
|
1ae6ae9b60 | ||
|
|
af4fadebda | ||
|
|
0af3af5d25 | ||
|
|
852d45a600 | ||
|
|
96213689e4 | ||
|
|
4e59c5c274 | ||
|
|
7d97ebfe7f | ||
|
|
377c406c74 | ||
|
|
91601d7f95 | ||
|
|
f3728e66f8 | ||
|
|
3f14ed6602 | ||
|
|
14df99130f | ||
|
|
47bcb892af | ||
|
|
6e05055f06 | ||
|
|
da6e53a436 | ||
|
|
56774fff20 | ||
|
|
3527a42063 | ||
|
|
98352a5e84 | ||
|
|
11a7980976 | ||
|
|
5b8ca1eee7 | ||
|
|
81cd417b45 | ||
|
|
a44c5cf4f7 | ||
|
|
5c5af4fa65 | ||
|
|
efd2167998 | ||
|
|
348f824104 | ||
|
|
0f7cbaca75 | ||
|
|
e870afa5d5 | ||
|
|
9bacd921fa | ||
|
|
bb3427ca85 | ||
|
|
6809b57cfc | ||
|
|
ffa75215cc | ||
|
|
c4517c013c | ||
|
|
ed04c010eb | ||
|
|
e9dc2e9e1e | ||
|
|
9c7d72739c | ||
|
|
3fc08f8ab6 | ||
|
|
c56a7ee803 | ||
|
|
35fa4fc71f | ||
|
|
b56a098cfb | ||
|
|
4cc272cb94 | ||
|
|
c4fc82c6b7 | ||
|
|
a40ded2884 | ||
|
|
44c78fdb7a | ||
|
|
ecb98a3330 | ||
|
|
9b6b510ca8 | ||
|
|
c2600a73cf | ||
|
|
43204d9ac2 | ||
|
|
369789b426 | ||
|
|
8fa53a5b92 | ||
|
|
d58176bfea | ||
|
|
0095f423f2 | ||
|
|
2617aa415e | ||
|
|
22b9307aba | ||
|
|
ac7339877b | ||
|
|
90890844ad | ||
|
|
8a89b12641 | ||
|
|
4a3b162c8c | ||
|
|
5c8af7ccb8 | ||
|
|
7942e6f3bf | ||
|
|
c6f497f09d | ||
|
|
29be28e1a2 | ||
|
|
e7939f450f | ||
|
|
81801d395f | ||
|
|
bc76c62c63 | ||
|
|
fd5d6c5340 | ||
|
|
08abe8b4a3 | ||
|
|
e896368496 | ||
|
|
2fe4e10b0b | ||
|
|
f2e78d9f84 | ||
|
|
b5bbc1f713 | ||
|
|
23943208ec | ||
|
|
c555e1aa96 | ||
|
|
36cc214703 | ||
|
|
8f7d36a85d | ||
|
|
e7cfe42d3f | ||
|
|
500fff920b | ||
|
|
782c3f36cc | ||
|
|
8272dcb6cd | ||
|
|
fec623d68d | ||
|
|
a3bf09c5c9 | ||
|
|
325dedc7da | ||
|
|
09b5949cd2 | ||
|
|
3141490374 | ||
|
|
1a8e3f0b2e | ||
|
|
80dd90f972 | ||
|
|
c2c185423b | ||
|
|
25b4d0c127 | ||
|
|
2225e3bbe7 | ||
|
|
a90a990118 | ||
|
|
83d8fe2d59 | ||
|
|
63a04134d0 | ||
|
|
6bc16f3ff1 | ||
|
|
10b24af98a | ||
|
|
be9aba2fa0 | ||
|
|
35018fa307 | ||
|
|
b706165527 | ||
|
|
6963c3802d | ||
|
|
3b67636f0e | ||
|
|
48e39c5c8e | ||
|
|
13524bea9b | ||
|
|
500c7f44ab | ||
|
|
d156e7a20b | ||
|
|
c386ce0023 | ||
|
|
b69d9ee3f7 | ||
|
|
7d5b8fcf77 | ||
|
|
bc6a6e04a0 | ||
|
|
e5ffe9959c | ||
|
|
86b95f2105 | ||
|
|
1e92df6b20 | ||
|
|
ba85c59d96 | ||
|
|
dafd5b5864 | ||
|
|
eabba1119f | ||
|
|
06e0d48794 | ||
|
|
4a71c86270 | ||
|
|
68583f4d48 | ||
|
|
5b35c149e8 | ||
|
|
9a542d9698 | ||
|
|
cd27ed9a74 | ||
|
|
b9f8cb7837 | ||
|
|
ffa150bec3 | ||
|
|
13bc6ba2c6 | ||
|
|
30b3edf328 | ||
|
|
7902d6089e | ||
|
|
b6b0878da8 | ||
|
|
3a76163aba | ||
|
|
1e7c6fc761 | ||
|
|
c50ad85c3c | ||
|
|
bb6a6e159a | ||
|
|
1036cadcec | ||
|
|
c71ae794df | ||
|
|
409930e98c | ||
|
|
b88f7df387 | ||
|
|
adcfffceeb | ||
|
|
a3c1d64a5f | ||
|
|
ce24a229df | ||
|
|
ce619b3b6c | ||
|
|
2e2a4b4ea3 | ||
|
|
7f519a2463 | ||
|
|
ff1ecb5d6c | ||
|
|
dab1cd8af9 | ||
|
|
5b0c6b9bc0 | ||
|
|
fc290dc30b | ||
|
|
5f7eb20090 | ||
|
|
03ad183384 | ||
|
|
527a2ec541 | ||
|
|
3185c36a65 | ||
|
|
3d8140a541 | ||
|
|
a6fc3d6ee5 | ||
|
|
a1f9bf19d9 | ||
|
|
4ad6a3496b | ||
|
|
969ad8001c | ||
|
|
07e0dd27fb | ||
|
|
b8eb699db7 | ||
|
|
ad1f28bc1c | ||
|
|
67686b7684 | ||
|
|
69f4954df1 | ||
|
|
4894231ff7 | ||
|
|
36bb57a47e | ||
|
|
a042449f5d | ||
|
|
f5e434c2d9 | ||
|
|
37d551fb39 | ||
|
|
9c8c0de538 | ||
|
|
fbdabe2975 | ||
|
|
0cfb30e5be | ||
|
|
c081a81daf | ||
|
|
155bed18f5 | ||
|
|
95d9687d95 | ||
|
|
ff41b8df76 | ||
|
|
53ccba8457 | ||
|
|
7ac6e3b850 | ||
|
|
d15217b953 | ||
|
|
bc54a44010 | ||
|
|
3f806df0ca | ||
|
|
f3799aa750 | ||
|
|
30ca6935a5 | ||
|
|
f25582d4b8 | ||
|
|
fb2fdb21d3 | ||
|
|
31a0d2200c | ||
|
|
e0a00c4996 | ||
|
|
e5077dc11e | ||
|
|
01a191936e | ||
|
|
8094b2add8 | ||
|
|
ffb638995d | ||
|
|
c2a4856f9e | ||
|
|
c9b24c3358 | ||
|
|
9305983018 | ||
|
|
ae2f5f25cd | ||
|
|
923b14afaa | ||
|
|
a9782b94e6 | ||
|
|
351ef5c85b | ||
|
|
be2925b3c5 | ||
|
|
ace27831ee | ||
|
|
6a1707889c | ||
|
|
1c42d15340 | ||
|
|
fe26967ea0 | ||
|
|
e7413417ce | ||
|
|
018022b866 | ||
|
|
7ea38e980b | ||
|
|
8173d92dd2 | ||
|
|
808a4fe817 | ||
|
|
72760c05c6 | ||
|
|
15683034a7 | ||
|
|
4c9d570e43 | ||
|
|
fc519ca74a | ||
|
|
a24c0a736c | ||
|
|
b3a0b389d2 | ||
|
|
47959c56fd | ||
|
|
aee75ae105 | ||
|
|
4b8a7f2793 | ||
|
|
89ec224cb9 | ||
|
|
b21a5e2f06 | ||
|
|
735cac5d53 | ||
|
|
bc4f3155ae | ||
|
|
a21a110188 | ||
|
|
b414fc0dfd | ||
|
|
e0215f3222 | ||
|
|
3dfff5bdae | ||
|
|
d632e77058 | ||
|
|
6d665b7f78 | ||
|
|
b1b0c64046 | ||
|
|
670cee44f0 | ||
|
|
3092f0c646 | ||
|
|
2f6142cb9b | ||
|
|
3b2bcee0a8 | ||
|
|
91407f4f74 | ||
|
|
025d57855a | ||
|
|
8647fbd6ed | ||
|
|
811037c845 | ||
|
|
181cc3f93f | ||
|
|
91b919fd1d | ||
|
|
5ff6289afd | ||
|
|
fca0a2dd88 | ||
|
|
462a39ec49 | ||
|
|
70125a3be0 | ||
|
|
cff8877a1a | ||
|
|
8f51f09de7 | ||
|
|
013dc43d5d | ||
|
|
853e2a9495 | ||
|
|
4c3a000211 | ||
|
|
9884573561 | ||
|
|
4b232f5ddc | ||
|
|
45ce92b89c | ||
|
|
bc86668ba4 | ||
|
|
0783211950 | ||
|
|
13fe7ee4df | ||
|
|
21fc66c246 | ||
|
|
ff9e49bac9 | ||
|
|
90e83fa879 | ||
|
|
3ef4fdeaa0 | ||
|
|
13d8af1852 | ||
|
|
5b7a141065 | ||
|
|
89a06f6651 | ||
|
|
a2e924039b | ||
|
|
85d1f9c5ec | ||
|
|
e444e18d2b | ||
|
|
ad0fdf0da6 | ||
|
|
fbbc7e421c | ||
|
|
1cc42ac9e4 | ||
|
|
6624105b5b | ||
|
|
de58594b0f | ||
|
|
d5f0b91c06 | ||
|
|
f78488bbdb |
63
Readme.txt
63
Readme.txt
@@ -2,21 +2,21 @@
|
||||
---------------
|
||||
|
||||
Stockfish is a free UCI chess engine derived from Glaurung 2.1. It is
|
||||
not a complete chess program, but requires some UCI compatible GUI
|
||||
(like XBoard with PolyGlot, eboard, Josè, Arena, Sigma Chess, Shredder,
|
||||
Chess Partner, or Fritz) in order to be used comfortably. Read the
|
||||
not a complete chess program and requires some UCI-compatible GUI
|
||||
(e.g. XBoard with PolyGlot, eboard, Arena, Sigma Chess, Shredder, Chess
|
||||
Partner or Fritz) in order to be used comfortably. Read the
|
||||
documentation for your GUI of choice for information about how to use
|
||||
Stockfish with your GUI.
|
||||
Stockfish with it.
|
||||
|
||||
This version of Stockfish supports up to 32 CPUs, but has not been
|
||||
tested thoroughly with more than 4. The program tries to detect the
|
||||
number of CPUs on your computer and set the number of search threads
|
||||
number of CPUs on your computer and sets the number of search threads
|
||||
accordingly, but please be aware that the detection is not always
|
||||
correct. It is therefore recommended to inspect the value of the
|
||||
correct. It is therefore recommended to inspect the value of the
|
||||
"Threads" UCI parameter, and to make sure it equals the number of CPU
|
||||
cores on your computer. If you are using more than four threads, it
|
||||
is recommended to raise the value of "Minimum Split Depth" UCI parameter
|
||||
to 6.
|
||||
cores on your computer. If you are using more than eight threads, it is
|
||||
recommended to raise the value of the "Min Split Depth" UCI parameter to
|
||||
7.
|
||||
|
||||
|
||||
2. Files
|
||||
@@ -26,13 +26,12 @@ This distribution of Stockfish consists of the following files:
|
||||
|
||||
* Readme.txt, the file you are currently reading.
|
||||
|
||||
* Copying.txt, a text file containing the GNU General Public
|
||||
License.
|
||||
* Copying.txt, a text file containing the GNU General Public License.
|
||||
|
||||
* src/, a subdirectory containing the full source code, including a
|
||||
Makefile that can be used to compile Stockfish on Unix-like
|
||||
systems. For further information about how to compile Stockfish
|
||||
yourself, read section 4 below.
|
||||
Makefile that can be used to compile Stockfish on Unix-like systems.
|
||||
For further information about how to compile Stockfish yourself read
|
||||
section 4 below.
|
||||
|
||||
* polyglot.ini, for using Stockfish with Fabien Letouzey's PolyGlot
|
||||
adapter.
|
||||
@@ -41,38 +40,33 @@ This distribution of Stockfish consists of the following files:
|
||||
3. Opening books
|
||||
----------------
|
||||
|
||||
This version of Stockfish has support for PolyGlot opening books.
|
||||
For information about how to create such books, consult the PolyGlot
|
||||
documentation. The book file can be selected by setting the UCI
|
||||
parameter "Book File".
|
||||
This version of Stockfish has support for PolyGlot opening books. For
|
||||
information about how to create such books, consult the PolyGlot
|
||||
documentation. The book file can be selected by setting the "Book File"
|
||||
UCI parameter.
|
||||
|
||||
|
||||
4. Compiling it yourself
|
||||
------------------------
|
||||
|
||||
On Unix-like systems, it should usually be possible to compile
|
||||
Stockfish directly from the source code with the included Makefile.
|
||||
On Unix-like systems, it should be possible to compile Stockfish
|
||||
directly from the source code with the included Makefile.
|
||||
|
||||
For big-endian machines like Power PC you need to enable the proper
|
||||
flag changing from -DNBIGENDIAN to -DBIGENDIAN in the Makefile.
|
||||
Stockfish has support for 32 or 64-bit CPUs, the hardware POPCNT
|
||||
instruction, big-endian machines such as Power PC, and other platforms.
|
||||
|
||||
Stockfish has POPCNT instruction runtime detection and support. This can
|
||||
give an extra speed on Core i7 or similar systems. To enable this feature
|
||||
compile with 'make icc-profile-popcnt'
|
||||
|
||||
On 64 bit systems the 'bsfq' assembly instruction will be used for bit
|
||||
counting. Detection is automatic at compile time, but in case you experience
|
||||
compile problems you can comment out #define USE_BSFQ line in types.h
|
||||
|
||||
In general is recommended to run 'make help' to see a list of make targets
|
||||
with corresponding descriptions.
|
||||
In general it is recommended to run 'make help' to see a list of make
|
||||
targets with corresponding descriptions. When not using Makefile to
|
||||
compile (for instance with Microsoft MSVC) you need to manually
|
||||
set/unset some switches in the compiler command line; see file "types.h"
|
||||
for a quick reference.
|
||||
|
||||
|
||||
5. Terms of use
|
||||
---------------
|
||||
|
||||
Stockfish is free, and distributed under the GNU General Public License
|
||||
(GPL). Essentially, this means that you are free to do almost exactly
|
||||
(GPL). Essentially, this means that you are free to do almost exactly
|
||||
what you want with the program, including distributing it among your
|
||||
friends, making it available for download from your web site, selling
|
||||
it (either by itself or as part of some bigger software package), or
|
||||
@@ -80,9 +74,8 @@ using it as the starting point for a software project of your own.
|
||||
|
||||
The only real limitation is that whenever you distribute Stockfish in
|
||||
some way, you must always include the full source code, or a pointer
|
||||
to where the source code can be found. If you make any changes to the
|
||||
to where the source code can be found. If you make any changes to the
|
||||
source code, these changes must also be made available under the GPL.
|
||||
|
||||
For full details, read the copy of the GPL found in the file named
|
||||
Copying.txt.
|
||||
|
||||
|
||||
20
polyglot.ini
20
polyglot.ini
@@ -15,13 +15,10 @@ ResignScore = 600
|
||||
|
||||
[Engine]
|
||||
|
||||
Hash = 128
|
||||
Threads = 1
|
||||
OwnBook = false
|
||||
Book File = book.bin
|
||||
Best Book Move = false
|
||||
Use Search Log = false
|
||||
Search Log Filename = SearchLog.txt
|
||||
Book File = book.bin
|
||||
Best Book Move = false
|
||||
Mobility (Middle Game) = 100
|
||||
Mobility (Endgame) = 100
|
||||
Passed Pawns (Middle Game) = 100
|
||||
@@ -29,11 +26,18 @@ Passed Pawns (Endgame) = 100
|
||||
Space = 100
|
||||
Aggressiveness = 100
|
||||
Cowardice = 100
|
||||
Minimum Split Depth = 4
|
||||
Maximum Number of Threads per Split Point = 5
|
||||
Use Sleeping Threads = false
|
||||
Min Split Depth = 4
|
||||
Max Threads per Split Point = 5
|
||||
Threads = 1
|
||||
Use Sleeping Threads = true
|
||||
Hash = 128
|
||||
Ponder = true
|
||||
OwnBook = false
|
||||
MultiPV = 1
|
||||
Skill Level = 20
|
||||
Emergency Move Horizon = 40
|
||||
Emergency Base Time = 200
|
||||
Emergency Move Time = 70
|
||||
Minimum Thinking Time = 20
|
||||
UCI_Chess960 = false
|
||||
UCI_AnalyseMode = false
|
||||
|
||||
171
src/Makefile
171
src/Makefile
@@ -1,6 +1,6 @@
|
||||
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
# Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
# Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
#
|
||||
# Stockfish is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
@@ -20,11 +20,18 @@
|
||||
### Section 1. General Configuration
|
||||
### ==========================================================================
|
||||
|
||||
### Establish the operating system name
|
||||
UNAME = $(shell uname)
|
||||
|
||||
### Executable name
|
||||
EXE = stockfish
|
||||
|
||||
### Installation dir definitions
|
||||
PREFIX = /usr/local
|
||||
# Haiku has a non-standard filesystem layout
|
||||
ifeq ($(UNAME),Haiku)
|
||||
PREFIX=/boot/common
|
||||
endif
|
||||
BINDIR = $(PREFIX)/bin
|
||||
|
||||
### Built-in benchmark for pgo-builds
|
||||
@@ -32,7 +39,7 @@ PGOBENCH = ./$(EXE) bench 32 1 10 default depth
|
||||
|
||||
### Object files
|
||||
OBJS = benchmark.o bitbase.o bitboard.o book.o endgame.o evaluate.o main.o \
|
||||
material.o misc.o move.o movegen.o movepick.o pawns.o position.o \
|
||||
material.o misc.o movegen.o movepick.o notation.o pawns.o position.o \
|
||||
search.o thread.o timeman.o tt.o uci.o ucioption.o
|
||||
|
||||
### ==========================================================================
|
||||
@@ -42,16 +49,15 @@ OBJS = benchmark.o bitbase.o bitboard.o book.o endgame.o evaluate.o main.o \
|
||||
# flag --- Comp switch --- Description
|
||||
# ----------------------------------------------------------------------------
|
||||
#
|
||||
# debug = no/yes --- -DNDEBUG --- Enable/Disable debug mode
|
||||
# debug = yes/no --- -DNDEBUG --- Enable/Disable debug mode
|
||||
# optimize = yes/no --- (-O3/-fast etc.) --- Enable/Disable optimizations
|
||||
# arch = (name) --- (-arch) --- Target architecture
|
||||
# os = (name) --- --- Target operating system
|
||||
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
|
||||
# bigendian = no/yes --- -DBIGENDIAN --- big/little-endian byte order
|
||||
# prefetch = no/yes --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
|
||||
# bsfq = no/yes --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction
|
||||
# --- (Works only with GCC and ICC 64-bit)
|
||||
# popcnt = no/yes --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
|
||||
# arch = (name) --- (-arch) --- Target architecture
|
||||
# os = (name) --- --- Target operating system
|
||||
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
|
||||
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
|
||||
# bsfq = yes/no --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction (only
|
||||
# with GCC and ICC 64-bit)
|
||||
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
|
||||
#
|
||||
# Note that Makefile is space sensitive, so when adding new architectures
|
||||
# or modifying existing flags, you have to make sure there are no extra spaces
|
||||
@@ -68,7 +74,6 @@ ifeq ($(ARCH),general-64)
|
||||
arch = any
|
||||
os = any
|
||||
bits = 64
|
||||
bigendian = no
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -78,27 +83,6 @@ ifeq ($(ARCH),general-32)
|
||||
arch = any
|
||||
os = any
|
||||
bits = 32
|
||||
bigendian = no
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
endif
|
||||
|
||||
ifeq ($(ARCH),bigendian-64)
|
||||
arch = any
|
||||
os = any
|
||||
bits = 64
|
||||
bigendian = yes
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
endif
|
||||
|
||||
ifeq ($(ARCH),bigendian-32)
|
||||
arch = any
|
||||
os = any
|
||||
bits = 32
|
||||
bigendian = yes
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -109,7 +93,6 @@ ifeq ($(ARCH),x86-64)
|
||||
arch = x86_64
|
||||
os = any
|
||||
bits = 64
|
||||
bigendian = no
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
popcnt = no
|
||||
@@ -119,7 +102,6 @@ ifeq ($(ARCH),x86-64-modern)
|
||||
arch = x86_64
|
||||
os = any
|
||||
bits = 64
|
||||
bigendian = no
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
popcnt = yes
|
||||
@@ -129,7 +111,6 @@ ifeq ($(ARCH),x86-32)
|
||||
arch = i386
|
||||
os = any
|
||||
bits = 32
|
||||
bigendian = no
|
||||
prefetch = yes
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -139,7 +120,6 @@ ifeq ($(ARCH),x86-32-old)
|
||||
arch = i386
|
||||
os = any
|
||||
bits = 32
|
||||
bigendian = no
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -150,7 +130,6 @@ ifeq ($(ARCH),osx-ppc-64)
|
||||
arch = ppc64
|
||||
os = osx
|
||||
bits = 64
|
||||
bigendian = yes
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -160,7 +139,6 @@ ifeq ($(ARCH),osx-ppc-32)
|
||||
arch = ppc
|
||||
os = osx
|
||||
bits = 32
|
||||
bigendian = yes
|
||||
prefetch = no
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -170,7 +148,6 @@ ifeq ($(ARCH),osx-x86-64)
|
||||
arch = x86_64
|
||||
os = osx
|
||||
bits = 64
|
||||
bigendian = no
|
||||
prefetch = yes
|
||||
bsfq = yes
|
||||
popcnt = no
|
||||
@@ -180,7 +157,6 @@ ifeq ($(ARCH),osx-x86-32)
|
||||
arch = i386
|
||||
os = osx
|
||||
bits = 32
|
||||
bigendian = no
|
||||
prefetch = yes
|
||||
bsfq = no
|
||||
popcnt = no
|
||||
@@ -223,6 +199,15 @@ ifeq ($(COMP),icc)
|
||||
profile_clean = icc-profile-clean
|
||||
endif
|
||||
|
||||
ifeq ($(COMP),clang)
|
||||
comp=clang
|
||||
CXX=clang++
|
||||
profile_prepare = gcc-profile-prepare
|
||||
profile_make = gcc-profile-make
|
||||
profile_use = gcc-profile-use
|
||||
profile_clean = gcc-profile-clean
|
||||
endif
|
||||
|
||||
### 3.2 General compiler settings
|
||||
CXXFLAGS = -g -Wall -Wcast-qual -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
|
||||
|
||||
@@ -238,12 +223,24 @@ ifeq ($(comp),icc)
|
||||
CXXFLAGS += -wd383,981,1418,1419,10187,10188,11505,11503 -Wcheck -Wabi -Wdeprecated -strict-ansi
|
||||
endif
|
||||
|
||||
ifeq ($(comp),clang)
|
||||
CXXFLAGS += -ansi -pedantic -Wno-long-long -Wextra -Wshadow
|
||||
endif
|
||||
|
||||
ifeq ($(os),osx)
|
||||
CXXFLAGS += -arch $(arch)
|
||||
endif
|
||||
|
||||
### 3.3 General linker settings
|
||||
LDFLAGS = -lpthread $(EXTRALDFLAGS)
|
||||
LDFLAGS = $(EXTRALDFLAGS)
|
||||
|
||||
### On mingw use Windows threads, otherwise POSIX
|
||||
ifneq ($(comp),mingw)
|
||||
# Haiku has pthreads in its libroot, so only link it in on other platforms
|
||||
ifneq ($(UNAME),Haiku)
|
||||
LDFLAGS += -lpthread
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(os),osx)
|
||||
LDFLAGS += -arch $(arch)
|
||||
@@ -281,6 +278,20 @@ ifeq ($(optimize),yes)
|
||||
CXXFLAGS += -O3
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(comp),clang)
|
||||
### -O4 requires a linker that supports LLVM's LTO
|
||||
CXXFLAGS += -O3
|
||||
|
||||
ifeq ($(os),osx)
|
||||
ifeq ($(arch),i386)
|
||||
CXXFLAGS += -mdynamic-no-pic
|
||||
endif
|
||||
ifeq ($(arch),x86_64)
|
||||
CXXFLAGS += -mdynamic-no-pic
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
### 3.6. Bits
|
||||
@@ -288,12 +299,7 @@ ifeq ($(bits),64)
|
||||
CXXFLAGS += -DIS_64BIT
|
||||
endif
|
||||
|
||||
### 3.7 Endianess
|
||||
ifeq ($(bigendian),yes)
|
||||
CXXFLAGS += -DBIGENDIAN
|
||||
endif
|
||||
|
||||
### 3.8 prefetch
|
||||
### 3.7 prefetch
|
||||
ifeq ($(prefetch),yes)
|
||||
CXXFLAGS += -msse
|
||||
DEPENDFLAGS += -msse
|
||||
@@ -301,23 +307,34 @@ else
|
||||
CXXFLAGS += -DNO_PREFETCH
|
||||
endif
|
||||
|
||||
### 3.9 bsfq
|
||||
### 3.8 bsfq
|
||||
ifeq ($(bsfq),yes)
|
||||
CXXFLAGS += -DUSE_BSFQ
|
||||
endif
|
||||
|
||||
### 3.10 popcnt
|
||||
### 3.9 popcnt
|
||||
ifeq ($(popcnt),yes)
|
||||
CXXFLAGS += -DUSE_POPCNT
|
||||
CXXFLAGS += -msse3 -DUSE_POPCNT
|
||||
endif
|
||||
|
||||
### 3.10 Link Time Optimization, it works since gcc 4.5 but not on mingw.
|
||||
### This is a mix of compile and link time options because the lto link phase
|
||||
### needs access to the optimization flags.
|
||||
ifeq ($(comp),gcc)
|
||||
ifeq ($(optimize),yes)
|
||||
GCC_MAJOR := `$(CXX) -dumpversion | cut -f1 -d.`
|
||||
GCC_MINOR := `$(CXX) -dumpversion | cut -f2 -d.`
|
||||
ifeq (1,$(shell expr \( $(GCC_MAJOR) \> 4 \) \| \( $(GCC_MAJOR) \= 4 \& $(GCC_MINOR) \>= 5 \)))
|
||||
CXXFLAGS += -flto
|
||||
LDFLAGS += $(CXXFLAGS)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
### ==========================================================================
|
||||
### Section 4. Public targets
|
||||
### ==========================================================================
|
||||
|
||||
default:
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) build
|
||||
|
||||
help:
|
||||
@echo ""
|
||||
@echo "To compile stockfish, type: "
|
||||
@@ -328,7 +345,6 @@ help:
|
||||
@echo ""
|
||||
@echo "build > Build unoptimized version"
|
||||
@echo "profile-build > Build PGO-optimized version"
|
||||
@echo "popcnt-profile-build > Build PGO-optimized version with optional popcnt-support"
|
||||
@echo "strip > Strip executable"
|
||||
@echo "install > Install executable"
|
||||
@echo "clean > Clean up"
|
||||
@@ -337,8 +353,8 @@ help:
|
||||
@echo "Supported archs:"
|
||||
@echo ""
|
||||
@echo "x86-64 > x86 64-bit"
|
||||
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt-instruction"
|
||||
@echo "x86-32 > x86 32-bit excluding very old hardware without SSE-support"
|
||||
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt instruction"
|
||||
@echo "x86-32 > x86 32-bit excluding old hardware without SSE-support"
|
||||
@echo "x86-32-old > x86 32-bit including also very old hardware"
|
||||
@echo "osx-ppc-64 > PPC-Mac OS X 64 bit"
|
||||
@echo "osx-ppc-32 > PPC-Mac OS X 32 bit"
|
||||
@@ -346,14 +362,13 @@ help:
|
||||
@echo "osx-x86-32 > x86-Mac OS X 32 bit"
|
||||
@echo "general-64 > unspecified 64-bit"
|
||||
@echo "general-32 > unspecified 32-bit"
|
||||
@echo "bigendian-64 > unspecified 64-bit with bigendian byte order"
|
||||
@echo "bigendian-32 > unspecified 32-bit with bigendian byte order"
|
||||
@echo ""
|
||||
@echo "Supported comps:"
|
||||
@echo ""
|
||||
@echo "gcc > Gnu compiler (default)"
|
||||
@echo "icc > Intel compiler"
|
||||
@echo "mingw > Gnu compiler with MinGW under Windows"
|
||||
@echo "clang > LLVM Clang compiler"
|
||||
@echo ""
|
||||
@echo "Non-standard targets:"
|
||||
@echo ""
|
||||
@@ -389,34 +404,6 @@ profile-build:
|
||||
@echo "Step 4/4. Deleting profile data ..."
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
|
||||
|
||||
popcnt-profile-build:
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) config-sanity
|
||||
@echo ""
|
||||
@echo "Step 0/6. Preparing for profile build."
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_prepare)
|
||||
@echo ""
|
||||
@echo "Step 1/6. Building executable for benchmark (popcnt disabled)..."
|
||||
@touch *.cpp *.h
|
||||
$(MAKE) ARCH=x86-64 COMP=$(COMP) $(profile_make)
|
||||
@echo ""
|
||||
@echo "Step 2/6. Running benchmark for pgo-build (popcnt disabled)..."
|
||||
@$(PGOBENCH) > /dev/null
|
||||
@echo ""
|
||||
@echo "Step 3/6. Building executable for benchmark (popcnt enabled)..."
|
||||
@touch *.cpp *.h
|
||||
$(MAKE) ARCH=x86-64-modern COMP=$(COMP) $(profile_make)
|
||||
@echo ""
|
||||
@echo "Step 4/6. Running benchmark for pgo-build (popcnt enabled)..."
|
||||
@$(PGOBENCH) > /dev/null
|
||||
@echo ""
|
||||
@echo "Step 5/6. Building final executable ..."
|
||||
@touch *.cpp *.h
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_use)
|
||||
@echo ""
|
||||
@echo "Step 6/6. Deleting profile data ..."
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
|
||||
@echo ""
|
||||
|
||||
strip:
|
||||
strip $(EXE)
|
||||
|
||||
@@ -431,6 +418,9 @@ clean:
|
||||
testrun:
|
||||
@$(PGOBENCH)
|
||||
|
||||
default:
|
||||
help
|
||||
|
||||
### ==========================================================================
|
||||
### Section 5. Private targets
|
||||
### ==========================================================================
|
||||
@@ -445,7 +435,6 @@ config-sanity:
|
||||
@echo "arch: '$(arch)'"
|
||||
@echo "os: '$(os)'"
|
||||
@echo "bits: '$(bits)'"
|
||||
@echo "bigendian: '$(bigendian)'"
|
||||
@echo "prefetch: '$(prefetch)'"
|
||||
@echo "bsfq: '$(bsfq)'"
|
||||
@echo "popcnt: '$(popcnt)'"
|
||||
@@ -463,11 +452,10 @@ config-sanity:
|
||||
test "$(arch)" = "ppc64" || test "$(arch)" = "ppc"
|
||||
@test "$(os)" = "any" || test "$(os)" = "osx"
|
||||
@test "$(bits)" = "32" || test "$(bits)" = "64"
|
||||
@test "$(bigendian)" = "yes" || test "$(bigendian)" = "no"
|
||||
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
|
||||
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
|
||||
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
|
||||
@test "$(comp)" = "gcc" || test "$(comp)" = "icc" || test "$(comp)" = "mingw"
|
||||
@test "$(comp)" = "gcc" || test "$(comp)" = "icc" || test "$(comp)" = "mingw" || test "$(comp)" = "clang"
|
||||
|
||||
$(EXE): $(OBJS)
|
||||
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
|
||||
@@ -484,6 +472,7 @@ gcc-profile-make:
|
||||
gcc-profile-use:
|
||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
|
||||
EXTRACXXFLAGS='-fprofile-use' \
|
||||
EXTRALDFLAGS='-lgcov' \
|
||||
all
|
||||
|
||||
gcc-profile-clean:
|
||||
@@ -518,7 +507,7 @@ icc-profile-clean:
|
||||
|
||||
hpux:
|
||||
$(MAKE) \
|
||||
CXX='/opt/aCC/bin/aCC -AA +hpxstd98 -DBIGENDIAN -mt +O3 -DNDEBUG -DNO_PREFETCH' \
|
||||
CXX='/opt/aCC/bin/aCC -AA +hpxstd98 -mt +O3 -DNDEBUG -DNO_PREFETCH' \
|
||||
CXXFLAGS="" \
|
||||
LDFLAGS="" \
|
||||
all
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -19,18 +19,22 @@
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <vector>
|
||||
|
||||
#include "misc.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "ucioption.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
static const string Defaults[] = {
|
||||
static const char* Defaults[] = {
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -",
|
||||
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -",
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
|
||||
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
|
||||
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
|
||||
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14",
|
||||
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14",
|
||||
@@ -43,111 +47,96 @@ static const string Defaults[] = {
|
||||
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
|
||||
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
|
||||
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22",
|
||||
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26",
|
||||
""
|
||||
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26"
|
||||
};
|
||||
|
||||
|
||||
/// benchmark() runs a simple benchmark by letting Stockfish analyze a set
|
||||
/// of positions for a given limit each. There are five parameters; the
|
||||
/// of positions for a given limit each. There are five parameters; the
|
||||
/// transposition table size, the number of search threads that should
|
||||
/// be used, the limit value spent for each position (optional, default
|
||||
/// is ply 12), an optional file name where to look for positions in fen
|
||||
/// format (default are the BenchmarkPositions defined above) and the type
|
||||
/// of the limit value: depth (default), time in secs or number of nodes.
|
||||
/// The analysis is written to a file named bench.txt.
|
||||
/// be used, the limit value spent for each position (optional, default is
|
||||
/// depth 12), an optional file name where to look for positions in fen
|
||||
/// format (defaults are the positions defined above) and the type of the
|
||||
/// limit value: depth (default), time in secs or number of nodes.
|
||||
|
||||
void benchmark(int argc, char* argv[]) {
|
||||
void benchmark(const Position& current, istream& is) {
|
||||
|
||||
vector<string> fenList;
|
||||
SearchLimits limits;
|
||||
int64_t totalNodes;
|
||||
int time;
|
||||
|
||||
// Load default positions
|
||||
for (int i = 0; !Defaults[i].empty(); i++)
|
||||
fenList.push_back(Defaults[i]);
|
||||
string token;
|
||||
Search::LimitsType limits;
|
||||
vector<string> fens;
|
||||
|
||||
// Assign default values to missing arguments
|
||||
string ttSize = argc > 2 ? argv[2] : "128";
|
||||
string threads = argc > 3 ? argv[3] : "1";
|
||||
string valStr = argc > 4 ? argv[4] : "12";
|
||||
string fenFile = argc > 5 ? argv[5] : "default";
|
||||
string valType = argc > 6 ? argv[6] : "depth";
|
||||
string ttSize = (is >> token) ? token : "128";
|
||||
string threads = (is >> token) ? token : "1";
|
||||
string limit = (is >> token) ? token : "12";
|
||||
string fenFile = (is >> token) ? token : "default";
|
||||
string limitType = (is >> token) ? token : "depth";
|
||||
|
||||
Options["Hash"].set_value(ttSize);
|
||||
Options["Threads"].set_value(threads);
|
||||
Options["OwnBook"].set_value("false");
|
||||
Options["Hash"] = ttSize;
|
||||
Options["Threads"] = threads;
|
||||
TT.clear();
|
||||
|
||||
if (limitType == "time")
|
||||
limits.movetime = 1000 * atoi(limit.c_str()); // movetime is in ms
|
||||
|
||||
else if (limitType == "nodes")
|
||||
limits.nodes = atoi(limit.c_str());
|
||||
|
||||
// Search should be limited by nodes, time or depth ?
|
||||
if (valType == "nodes")
|
||||
limits.maxNodes = atoi(valStr.c_str());
|
||||
else if (valType == "time")
|
||||
limits.maxTime = 1000 * atoi(valStr.c_str()); // maxTime is in ms
|
||||
else
|
||||
limits.maxDepth = atoi(valStr.c_str());
|
||||
limits.depth = atoi(limit.c_str());
|
||||
|
||||
// Do we need to load positions from a given FEN file ?
|
||||
if (fenFile != "default")
|
||||
if (fenFile == "default")
|
||||
fens.assign(Defaults, Defaults + 16);
|
||||
|
||||
else if (fenFile == "current")
|
||||
fens.push_back(current.to_fen());
|
||||
|
||||
else
|
||||
{
|
||||
string fen;
|
||||
ifstream f(fenFile.c_str());
|
||||
ifstream file(fenFile.c_str());
|
||||
|
||||
if (f.is_open())
|
||||
if (!file.is_open())
|
||||
{
|
||||
fenList.clear();
|
||||
|
||||
while (getline(f, fen))
|
||||
if (!fen.empty())
|
||||
fenList.push_back(fen);
|
||||
|
||||
f.close();
|
||||
}
|
||||
else
|
||||
{
|
||||
cerr << "Unable to open FEN file " << fenFile << endl;
|
||||
cerr << "Unable to open file " << fenFile << endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
while (getline(file, fen))
|
||||
if (!fen.empty())
|
||||
fens.push_back(fen);
|
||||
|
||||
file.close();
|
||||
}
|
||||
|
||||
// Ok, let's start the benchmark !
|
||||
totalNodes = 0;
|
||||
time = get_system_time();
|
||||
int64_t nodes = 0;
|
||||
Search::StateStackPtr st;
|
||||
Time::point elapsed = Time::now();
|
||||
|
||||
for (size_t i = 0; i < fenList.size(); i++)
|
||||
for (size_t i = 0; i < fens.size(); i++)
|
||||
{
|
||||
Move moves[] = { MOVE_NONE };
|
||||
Position pos(fenList[i], false, 0);
|
||||
Position pos(fens[i], Options["UCI_Chess960"], Threads.main_thread());
|
||||
|
||||
cerr << "\nBench position: " << i + 1 << '/' << fenList.size() << endl;
|
||||
cerr << "\nPosition: " << i + 1 << '/' << fens.size() << endl;
|
||||
|
||||
if (valType == "perft")
|
||||
if (limitType == "perft")
|
||||
{
|
||||
int64_t cnt = perft(pos, limits.maxDepth * ONE_PLY);
|
||||
totalNodes += cnt;
|
||||
|
||||
cerr << "\nPerft " << limits.maxDepth << " nodes counted: " << cnt << endl;
|
||||
size_t cnt = Search::perft(pos, limits.depth * ONE_PLY);
|
||||
cerr << "\nPerft " << limits.depth << " leaf nodes: " << cnt << endl;
|
||||
nodes += cnt;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!think(pos, limits, moves))
|
||||
break;
|
||||
|
||||
totalNodes += pos.nodes_searched();
|
||||
Threads.start_searching(pos, limits, vector<Move>(), st);
|
||||
Threads.wait_for_search_finished();
|
||||
nodes += Search::RootPosition.nodes_searched();
|
||||
}
|
||||
}
|
||||
|
||||
time = get_system_time() - time;
|
||||
elapsed = Time::now() - elapsed + 1; // Assure positive to avoid a 'divide by zero'
|
||||
|
||||
cerr << "\n==============================="
|
||||
<< "\nTotal time (ms) : " << time
|
||||
<< "\nNodes searched : " << totalNodes
|
||||
<< "\nNodes/second : " << (int)(totalNodes / (time / 1000.0)) << endl << endl;
|
||||
|
||||
// MS Visual C++ debug window always unconditionally closes when program
|
||||
// exits, this is bad because we want to read results before.
|
||||
#if (defined(WINDOWS) || defined(WIN32) || defined(WIN64))
|
||||
cerr << "Press any key to exit" << endl;
|
||||
cin >> time;
|
||||
#endif
|
||||
cerr << "\n==========================="
|
||||
<< "\nTotal time (ms) : " << elapsed
|
||||
<< "\nNodes searched : " << nodes
|
||||
<< "\nNodes/second : " << 1000 * nodes / elapsed << endl;
|
||||
}
|
||||
|
||||
340
src/bitbase.cpp
340
src/bitbase.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -25,260 +25,206 @@
|
||||
namespace {
|
||||
|
||||
enum Result {
|
||||
RESULT_UNKNOWN,
|
||||
RESULT_INVALID,
|
||||
RESULT_WIN,
|
||||
RESULT_LOSS,
|
||||
RESULT_DRAW
|
||||
INVALID = 0,
|
||||
UNKNOWN = 1,
|
||||
DRAW = 2,
|
||||
WIN = 4
|
||||
};
|
||||
|
||||
struct KPKPosition {
|
||||
void from_index(int index);
|
||||
bool is_legal() const;
|
||||
bool is_immediate_draw() const;
|
||||
bool is_immediate_win() const;
|
||||
Bitboard wk_attacks() const { return StepAttacksBB[WK][whiteKingSquare]; }
|
||||
Bitboard bk_attacks() const { return StepAttacksBB[BK][blackKingSquare]; }
|
||||
Bitboard pawn_attacks() const { return StepAttacksBB[WP][pawnSquare]; }
|
||||
inline Result& operator|=(Result& r, Result v) { return r = Result(r | v); }
|
||||
|
||||
Square whiteKingSquare, blackKingSquare, pawnSquare;
|
||||
Color sideToMove;
|
||||
struct KPKPosition {
|
||||
|
||||
Result classify_leaf(int idx);
|
||||
Result classify(int idx, Result db[]);
|
||||
|
||||
private:
|
||||
template<Color Us> Result classify(const Result db[]) const;
|
||||
|
||||
template<Color Us> Bitboard k_attacks() const {
|
||||
return Us == WHITE ? StepAttacksBB[W_KING][wksq] : StepAttacksBB[B_KING][bksq];
|
||||
}
|
||||
|
||||
Bitboard p_attacks() const { return StepAttacksBB[W_PAWN][psq]; }
|
||||
void decode_index(int idx);
|
||||
|
||||
Square wksq, bksq, psq;
|
||||
Color stm;
|
||||
};
|
||||
|
||||
// The possible pawns squares are 24, the first 4 files and ranks from 2 to 7
|
||||
const int IndexMax = 2 * 24 * 64 * 64; // color * wp_sq * wk_sq * bk_sq
|
||||
const int IndexMax = 2 * 24 * 64 * 64; // stm * wp_sq * wk_sq * bk_sq = 196608
|
||||
|
||||
// Each uint32_t stores results of 32 positions, one per bit
|
||||
uint32_t KPKBitbase[IndexMax / 32];
|
||||
|
||||
Result classify_wtm(const KPKPosition& pos, const Result bb[]);
|
||||
Result classify_btm(const KPKPosition& pos, const Result bb[]);
|
||||
int compute_index(Square wksq, Square bksq, Square wpsq, Color stm);
|
||||
int index(Square wksq, Square bksq, Square psq, Color stm);
|
||||
}
|
||||
|
||||
|
||||
uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm) {
|
||||
uint32_t Bitbases::probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm) {
|
||||
|
||||
int index = compute_index(wksq, bksq, wpsq, stm);
|
||||
|
||||
return KPKBitbase[index / 32] & (1 << (index & 31));
|
||||
int idx = index(wksq, bksq, wpsq, stm);
|
||||
return KPKBitbase[idx / 32] & (1 << (idx & 31));
|
||||
}
|
||||
|
||||
|
||||
void init_kpk_bitbase() {
|
||||
void Bitbases::init_kpk() {
|
||||
|
||||
Result bb[IndexMax];
|
||||
Result db[IndexMax];
|
||||
KPKPosition pos;
|
||||
bool repeat;
|
||||
int idx, bit, repeat = 1;
|
||||
|
||||
// Initialize table
|
||||
for (int i = 0; i < IndexMax; i++)
|
||||
{
|
||||
pos.from_index(i);
|
||||
bb[i] = !pos.is_legal() ? RESULT_INVALID
|
||||
: pos.is_immediate_draw() ? RESULT_DRAW
|
||||
: pos.is_immediate_win() ? RESULT_WIN : RESULT_UNKNOWN;
|
||||
}
|
||||
// Initialize table with known win / draw positions
|
||||
for (idx = 0; idx < IndexMax; idx++)
|
||||
db[idx] = pos.classify_leaf(idx);
|
||||
|
||||
// Iterate until all positions are classified (30 cycles needed)
|
||||
do {
|
||||
repeat = false;
|
||||
|
||||
for (int i = 0; i < IndexMax; i++)
|
||||
if (bb[i] == RESULT_UNKNOWN)
|
||||
{
|
||||
pos.from_index(i);
|
||||
|
||||
bb[i] = (pos.sideToMove == WHITE) ? classify_wtm(pos, bb)
|
||||
: classify_btm(pos, bb);
|
||||
if (bb[i] != RESULT_UNKNOWN)
|
||||
repeat = true;
|
||||
}
|
||||
|
||||
} while (repeat);
|
||||
while (repeat)
|
||||
for (repeat = idx = 0; idx < IndexMax; idx++)
|
||||
if (db[idx] == UNKNOWN && (db[idx] = pos.classify(idx, db)) != UNKNOWN)
|
||||
repeat = 1;
|
||||
|
||||
// Map 32 position results into one KPKBitbase[] entry
|
||||
for (int i = 0; i < IndexMax / 32; i++)
|
||||
for (int j = 0; j < 32; j++)
|
||||
if (bb[32 * i + j] == RESULT_WIN || bb[32 * i + j] == RESULT_LOSS)
|
||||
KPKBitbase[i] |= (1 << j);
|
||||
for (idx = 0; idx < IndexMax / 32; idx++)
|
||||
for (bit = 0; bit < 32; bit++)
|
||||
if (db[32 * idx + bit] == WIN)
|
||||
KPKBitbase[idx] |= 1 << bit;
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
// A KPK bitbase index is an integer in [0, IndexMax] range
|
||||
//
|
||||
// Information is mapped in this way
|
||||
//
|
||||
// bit 0: side to move (WHITE or BLACK)
|
||||
// bit 1- 6: black king square (from SQ_A1 to SQ_H8)
|
||||
// bit 7-12: white king square (from SQ_A1 to SQ_H8)
|
||||
// bit 13-14: white pawn file (from FILE_A to FILE_D)
|
||||
// bit 15-17: white pawn rank - 1 (from RANK_2 - 1 to RANK_7 - 1)
|
||||
// A KPK bitbase index is an integer in [0, IndexMax] range
|
||||
//
|
||||
// Information is mapped in this way
|
||||
//
|
||||
// bit 0: side to move (WHITE or BLACK)
|
||||
// bit 1- 6: black king square (from SQ_A1 to SQ_H8)
|
||||
// bit 7-12: white king square (from SQ_A1 to SQ_H8)
|
||||
// bit 13-14: white pawn file (from FILE_A to FILE_D)
|
||||
// bit 15-17: white pawn rank - 1 (from RANK_2 - 1 to RANK_7 - 1)
|
||||
|
||||
int compute_index(Square wksq, Square bksq, Square wpsq, Color stm) {
|
||||
int index(Square w, Square b, Square p, Color c) {
|
||||
|
||||
assert(square_file(wpsq) <= FILE_D);
|
||||
assert(file_of(p) <= FILE_D);
|
||||
|
||||
int p = int(square_file(wpsq)) + 4 * int(square_rank(wpsq) - 1);
|
||||
int r = int(stm) + 2 * int(bksq) + 128 * int(wksq) + 8192 * p;
|
||||
|
||||
assert(r >= 0 && r < IndexMax);
|
||||
|
||||
return r;
|
||||
return c + (b << 1) + (w << 7) + (file_of(p) << 13) + ((rank_of(p) - 1) << 15);
|
||||
}
|
||||
|
||||
void KPKPosition::from_index(int index) {
|
||||
void KPKPosition::decode_index(int idx) {
|
||||
|
||||
int s = (index / 8192) % 24;
|
||||
|
||||
sideToMove = Color(index % 2);
|
||||
blackKingSquare = Square((index / 2) % 64);
|
||||
whiteKingSquare = Square((index / 128) % 64);
|
||||
pawnSquare = make_square(File(s % 4), Rank(s / 4 + 1));
|
||||
stm = Color(idx & 1);
|
||||
bksq = Square((idx >> 1) & 63);
|
||||
wksq = Square((idx >> 7) & 63);
|
||||
psq = File((idx >> 13) & 3) | Rank((idx >> 15) + 1);
|
||||
}
|
||||
|
||||
bool KPKPosition::is_legal() const {
|
||||
Result KPKPosition::classify_leaf(int idx) {
|
||||
|
||||
if ( whiteKingSquare == pawnSquare
|
||||
|| whiteKingSquare == blackKingSquare
|
||||
|| blackKingSquare == pawnSquare)
|
||||
return false;
|
||||
decode_index(idx);
|
||||
|
||||
if (sideToMove == WHITE)
|
||||
{
|
||||
if ( bit_is_set(wk_attacks(), blackKingSquare)
|
||||
|| bit_is_set(pawn_attacks(), blackKingSquare))
|
||||
return false;
|
||||
}
|
||||
else if (bit_is_set(bk_attacks(), whiteKingSquare))
|
||||
return false;
|
||||
// Check if two pieces are on the same square or if a king can be captured
|
||||
if ( wksq == psq || wksq == bksq || bksq == psq
|
||||
|| (k_attacks<WHITE>() & bksq)
|
||||
|| (stm == WHITE && (p_attacks() & bksq)))
|
||||
return INVALID;
|
||||
|
||||
return true;
|
||||
// The position is an immediate win if it is white to move and the white
|
||||
// pawn can be promoted without getting captured.
|
||||
if ( rank_of(psq) == RANK_7
|
||||
&& stm == WHITE
|
||||
&& wksq != psq + DELTA_N
|
||||
&& ( square_distance(bksq, psq + DELTA_N) > 1
|
||||
||(k_attacks<WHITE>() & (psq + DELTA_N))))
|
||||
return WIN;
|
||||
|
||||
// Check for known draw positions
|
||||
//
|
||||
// Case 1: Stalemate
|
||||
if ( stm == BLACK
|
||||
&& !(k_attacks<BLACK>() & ~(k_attacks<WHITE>() | p_attacks())))
|
||||
return DRAW;
|
||||
|
||||
// Case 2: King can capture undefended pawn
|
||||
if ( stm == BLACK
|
||||
&& (k_attacks<BLACK>() & psq & ~k_attacks<WHITE>()))
|
||||
return DRAW;
|
||||
|
||||
// Case 3: Black king in front of white pawn
|
||||
if ( bksq == psq + DELTA_N
|
||||
&& rank_of(psq) < RANK_7)
|
||||
return DRAW;
|
||||
|
||||
// Case 4: White king in front of pawn and black has opposition
|
||||
if ( stm == WHITE
|
||||
&& wksq == psq + DELTA_N
|
||||
&& bksq == wksq + DELTA_N + DELTA_N
|
||||
&& rank_of(psq) < RANK_5)
|
||||
return DRAW;
|
||||
|
||||
// Case 5: Stalemate with rook pawn
|
||||
if ( bksq == SQ_A8
|
||||
&& file_of(psq) == FILE_A)
|
||||
return DRAW;
|
||||
|
||||
// Case 6: White king trapped on the rook file
|
||||
if ( file_of(wksq) == FILE_A
|
||||
&& file_of(psq) == FILE_A
|
||||
&& rank_of(wksq) > rank_of(psq)
|
||||
&& bksq == wksq + 2)
|
||||
return DRAW;
|
||||
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
bool KPKPosition::is_immediate_draw() const {
|
||||
template<Color Us>
|
||||
Result KPKPosition::classify(const Result db[]) const {
|
||||
|
||||
if (sideToMove == BLACK)
|
||||
{
|
||||
Bitboard wka = wk_attacks();
|
||||
Bitboard bka = bk_attacks();
|
||||
// White to Move: If one move leads to a position classified as RESULT_WIN,
|
||||
// the result of the current position is RESULT_WIN. If all moves lead to
|
||||
// positions classified as RESULT_DRAW, the current position is classified
|
||||
// RESULT_DRAW otherwise the current position is classified as RESULT_UNKNOWN.
|
||||
//
|
||||
// Black to Move: If one move leads to a position classified as RESULT_DRAW,
|
||||
// the result of the current position is RESULT_DRAW. If all moves lead to
|
||||
// positions classified as RESULT_WIN, the position is classified RESULT_WIN.
|
||||
// Otherwise, the current position is classified as RESULT_UNKNOWN.
|
||||
|
||||
// Case 1: Stalemate
|
||||
if ((bka & ~(wka | pawn_attacks())) == EmptyBoardBB)
|
||||
return true;
|
||||
Result r = INVALID;
|
||||
Bitboard b = k_attacks<Us>();
|
||||
|
||||
// Case 2: King can capture pawn
|
||||
if (bit_is_set(bka, pawnSquare) && !bit_is_set(wka, pawnSquare))
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Case 1: Stalemate (possible pawn files are only from A to D)
|
||||
if ( whiteKingSquare == SQ_A8
|
||||
&& pawnSquare == SQ_A7
|
||||
&& (blackKingSquare == SQ_C7 || blackKingSquare == SQ_C8))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool KPKPosition::is_immediate_win() const {
|
||||
|
||||
// The position is an immediate win if it is white to move and the
|
||||
// white pawn can be promoted without getting captured.
|
||||
return sideToMove == WHITE
|
||||
&& square_rank(pawnSquare) == RANK_7
|
||||
&& whiteKingSquare != pawnSquare + DELTA_N
|
||||
&& ( square_distance(blackKingSquare, pawnSquare + DELTA_N) > 1
|
||||
|| bit_is_set(wk_attacks(), pawnSquare + DELTA_N));
|
||||
}
|
||||
|
||||
Result classify_wtm(const KPKPosition& pos, const Result bb[]) {
|
||||
|
||||
// If one move leads to a position classified as RESULT_LOSS, the result
|
||||
// of the current position is RESULT_WIN. If all moves lead to positions
|
||||
// classified as RESULT_DRAW, the current position is classified RESULT_DRAW
|
||||
// otherwise the current position is classified as RESULT_UNKNOWN.
|
||||
|
||||
bool unknownFound = false;
|
||||
Bitboard b;
|
||||
Square s;
|
||||
Result r;
|
||||
|
||||
// King moves
|
||||
b = pos.wk_attacks();
|
||||
while (b)
|
||||
{
|
||||
s = pop_1st_bit(&b);
|
||||
r = bb[compute_index(s, pos.blackKingSquare, pos.pawnSquare, BLACK)];
|
||||
r |= Us == WHITE ? db[index(pop_lsb(&b), bksq, psq, BLACK)]
|
||||
: db[index(wksq, pop_lsb(&b), psq, WHITE)];
|
||||
|
||||
if (r == RESULT_LOSS)
|
||||
return RESULT_WIN;
|
||||
if (Us == WHITE && (r & WIN))
|
||||
return WIN;
|
||||
|
||||
if (r == RESULT_UNKNOWN)
|
||||
unknownFound = true;
|
||||
if (Us == BLACK && (r & DRAW))
|
||||
return DRAW;
|
||||
}
|
||||
|
||||
// Pawn moves
|
||||
if (square_rank(pos.pawnSquare) < RANK_7)
|
||||
if (Us == WHITE && rank_of(psq) < RANK_7)
|
||||
{
|
||||
s = pos.pawnSquare + DELTA_N;
|
||||
r = bb[compute_index(pos.whiteKingSquare, pos.blackKingSquare, s, BLACK)];
|
||||
Square s = psq + DELTA_N;
|
||||
r |= db[index(wksq, bksq, s, BLACK)]; // Single push
|
||||
|
||||
if (r == RESULT_LOSS)
|
||||
return RESULT_WIN;
|
||||
if (rank_of(s) == RANK_3 && s != wksq && s != bksq)
|
||||
r |= db[index(wksq, bksq, s + DELTA_N, BLACK)]; // Double push
|
||||
|
||||
if (r == RESULT_UNKNOWN)
|
||||
unknownFound = true;
|
||||
|
||||
// Double pawn push
|
||||
if ( square_rank(s) == RANK_3
|
||||
&& s != pos.whiteKingSquare
|
||||
&& s != pos.blackKingSquare)
|
||||
{
|
||||
s += DELTA_N;
|
||||
r = bb[compute_index(pos.whiteKingSquare, pos.blackKingSquare, s, BLACK)];
|
||||
|
||||
if (r == RESULT_LOSS)
|
||||
return RESULT_WIN;
|
||||
|
||||
if (r == RESULT_UNKNOWN)
|
||||
unknownFound = true;
|
||||
}
|
||||
if (r & WIN)
|
||||
return WIN;
|
||||
}
|
||||
return unknownFound ? RESULT_UNKNOWN : RESULT_DRAW;
|
||||
|
||||
return r & UNKNOWN ? UNKNOWN : Us == WHITE ? DRAW : WIN;
|
||||
}
|
||||
|
||||
Result KPKPosition::classify(int idx, Result db[]) {
|
||||
|
||||
Result classify_btm(const KPKPosition& pos, const Result bb[]) {
|
||||
|
||||
// If one move leads to a position classified as RESULT_DRAW, the result
|
||||
// of the current position is RESULT_DRAW. If all moves lead to positions
|
||||
// classified as RESULT_WIN, the current position is classified as
|
||||
// RESULT_LOSS. Otherwise, the current position is classified as
|
||||
// RESULT_UNKNOWN.
|
||||
|
||||
bool unknownFound = false;
|
||||
Bitboard b;
|
||||
Square s;
|
||||
Result r;
|
||||
|
||||
// King moves
|
||||
b = pos.bk_attacks();
|
||||
while (b)
|
||||
{
|
||||
s = pop_1st_bit(&b);
|
||||
r = bb[compute_index(pos.whiteKingSquare, s, pos.pawnSquare, WHITE)];
|
||||
|
||||
if (r == RESULT_DRAW)
|
||||
return RESULT_DRAW;
|
||||
|
||||
if (r == RESULT_UNKNOWN)
|
||||
unknownFound = true;
|
||||
}
|
||||
return unknownFound ? RESULT_UNKNOWN : RESULT_LOSS;
|
||||
decode_index(idx);
|
||||
return stm == WHITE ? classify<WHITE>(db) : classify<BLACK>(db);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
649
src/bitboard.cpp
649
src/bitboard.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,470 +17,335 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "bitcount.h"
|
||||
#include "misc.h"
|
||||
#include "rkiss.h"
|
||||
|
||||
#if defined(IS_64BIT)
|
||||
CACHE_LINE_ALIGNMENT
|
||||
|
||||
const uint64_t BMult[64] = {
|
||||
0x0440049104032280ULL, 0x1021023C82008040ULL, 0x0404040082000048ULL,
|
||||
0x48C4440084048090ULL, 0x2801104026490000ULL, 0x4100880442040800ULL,
|
||||
0x0181011002E06040ULL, 0x9101004104200E00ULL, 0x1240848848310401ULL,
|
||||
0x2000142828050024ULL, 0x00001004024D5000ULL, 0x0102044400800200ULL,
|
||||
0x8108108820112000ULL, 0xA880818210C00046ULL, 0x4008008801082000ULL,
|
||||
0x0060882404049400ULL, 0x0104402004240810ULL, 0x000A002084250200ULL,
|
||||
0x00100B0880801100ULL, 0x0004080201220101ULL, 0x0044008080A00000ULL,
|
||||
0x0000202200842000ULL, 0x5006004882D00808ULL, 0x0000200045080802ULL,
|
||||
0x0086100020200601ULL, 0xA802080A20112C02ULL, 0x0080411218080900ULL,
|
||||
0x000200A0880080A0ULL, 0x9A01010000104000ULL, 0x0028008003100080ULL,
|
||||
0x0211021004480417ULL, 0x0401004188220806ULL, 0x00825051400C2006ULL,
|
||||
0x00140C0210943000ULL, 0x0000242800300080ULL, 0x00C2208120080200ULL,
|
||||
0x2430008200002200ULL, 0x1010100112008040ULL, 0x8141050100020842ULL,
|
||||
0x0000822081014405ULL, 0x800C049E40400804ULL, 0x4A0404028A000820ULL,
|
||||
0x0022060201041200ULL, 0x0360904200840801ULL, 0x0881A08208800400ULL,
|
||||
0x0060202C00400420ULL, 0x1204440086061400ULL, 0x0008184042804040ULL,
|
||||
0x0064040315300400ULL, 0x0C01008801090A00ULL, 0x0808010401140C00ULL,
|
||||
0x04004830C2020040ULL, 0x0080005002020054ULL, 0x40000C14481A0490ULL,
|
||||
0x0010500101042048ULL, 0x1010100200424000ULL, 0x0000640901901040ULL,
|
||||
0x00000A0201014840ULL, 0x00840082AA011002ULL, 0x010010840084240AULL,
|
||||
0x0420400810420608ULL, 0x8D40230408102100ULL, 0x4A00200612222409ULL,
|
||||
0x0A08520292120600ULL
|
||||
};
|
||||
Bitboard RMasks[64];
|
||||
Bitboard RMagics[64];
|
||||
Bitboard* RAttacks[64];
|
||||
unsigned RShifts[64];
|
||||
|
||||
const uint64_t RMult[64] = {
|
||||
0x0A8002C000108020ULL, 0x4440200140003000ULL, 0x8080200010011880ULL,
|
||||
0x0380180080141000ULL, 0x1A00060008211044ULL, 0x410001000A0C0008ULL,
|
||||
0x9500060004008100ULL, 0x0100024284A20700ULL, 0x0000802140008000ULL,
|
||||
0x0080C01002A00840ULL, 0x0402004282011020ULL, 0x9862000820420050ULL,
|
||||
0x0001001448011100ULL, 0x6432800200800400ULL, 0x040100010002000CULL,
|
||||
0x0002800D0010C080ULL, 0x90C0008000803042ULL, 0x4010004000200041ULL,
|
||||
0x0003010010200040ULL, 0x0A40828028001000ULL, 0x0123010008000430ULL,
|
||||
0x0024008004020080ULL, 0x0060040001104802ULL, 0x00582200028400D1ULL,
|
||||
0x4000802080044000ULL, 0x0408208200420308ULL, 0x0610038080102000ULL,
|
||||
0x3601000900100020ULL, 0x0000080080040180ULL, 0x00C2020080040080ULL,
|
||||
0x0080084400100102ULL, 0x4022408200014401ULL, 0x0040052040800082ULL,
|
||||
0x0B08200280804000ULL, 0x008A80A008801000ULL, 0x4000480080801000ULL,
|
||||
0x0911808800801401ULL, 0x822A003002001894ULL, 0x401068091400108AULL,
|
||||
0x000004A10A00004CULL, 0x2000800640008024ULL, 0x1486408102020020ULL,
|
||||
0x000100A000D50041ULL, 0x00810050020B0020ULL, 0x0204000800808004ULL,
|
||||
0x00020048100A000CULL, 0x0112000831020004ULL, 0x0009000040810002ULL,
|
||||
0x0440490200208200ULL, 0x8910401000200040ULL, 0x6404200050008480ULL,
|
||||
0x4B824A2010010100ULL, 0x04080801810C0080ULL, 0x00000400802A0080ULL,
|
||||
0x8224080110026400ULL, 0x40002C4104088200ULL, 0x01002100104A0282ULL,
|
||||
0x1208400811048021ULL, 0x3201014A40D02001ULL, 0x0005100019200501ULL,
|
||||
0x0101000208001005ULL, 0x0002008450080702ULL, 0x001002080301D00CULL,
|
||||
0x410201CE5C030092ULL
|
||||
};
|
||||
Bitboard BMasks[64];
|
||||
Bitboard BMagics[64];
|
||||
Bitboard* BAttacks[64];
|
||||
unsigned BShifts[64];
|
||||
|
||||
const int BShift[64] = {
|
||||
58, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 59, 59,
|
||||
59, 59, 57, 57, 57, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59,
|
||||
59, 59, 57, 55, 55, 57, 59, 59, 59, 59, 57, 57, 57, 57, 59, 59,
|
||||
59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58
|
||||
};
|
||||
|
||||
const int RShift[64] = {
|
||||
52, 53, 53, 53, 53, 53, 53, 52, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||
53, 54, 54, 54, 54, 54, 54, 53, 52, 53, 53, 53, 53, 53, 53, 52
|
||||
};
|
||||
|
||||
#else // if !defined(IS_64BIT)
|
||||
|
||||
const uint64_t BMult[64] = {
|
||||
0x54142844C6A22981ULL, 0x710358A6EA25C19EULL, 0x704F746D63A4A8DCULL,
|
||||
0xBFED1A0B80F838C5ULL, 0x90561D5631E62110ULL, 0x2804260376E60944ULL,
|
||||
0x84A656409AA76871ULL, 0xF0267F64C28B6197ULL, 0x70764EBB762F0585ULL,
|
||||
0x92AA09E0CFE161DEULL, 0x41EE1F6BB266F60EULL, 0xDDCBF04F6039C444ULL,
|
||||
0x5A3FAB7BAC0D988AULL, 0xD3727877FA4EAA03ULL, 0xD988402D868DDAAEULL,
|
||||
0x812B291AFA075C7CULL, 0x94FAF987B685A932ULL, 0x3ED867D8470D08DBULL,
|
||||
0x92517660B8901DE8ULL, 0x2D97E43E058814B4ULL, 0x880A10C220B25582ULL,
|
||||
0xC7C6520D1F1A0477ULL, 0xDBFC7FBCD7656AA6ULL, 0x78B1B9BFB1A2B84FULL,
|
||||
0x2F20037F112A0BC1ULL, 0x657171EA2269A916ULL, 0xC08302B07142210EULL,
|
||||
0x0880A4403064080BULL, 0x3602420842208C00ULL, 0x852800DC7E0B6602ULL,
|
||||
0x595A3FBBAA0F03B2ULL, 0x9F01411558159D5EULL, 0x2B4A4A5F88B394F2ULL,
|
||||
0x4AFCBFFC292DD03AULL, 0x4A4094A3B3F10522ULL, 0xB06F00B491F30048ULL,
|
||||
0xD5B3820280D77004ULL, 0x8B2E01E7C8E57A75ULL, 0x2D342794E886C2E6ULL,
|
||||
0xC302C410CDE21461ULL, 0x111F426F1379C274ULL, 0xE0569220ABB31588ULL,
|
||||
0x5026D3064D453324ULL, 0xE2076040C343CD8AULL, 0x93EFD1E1738021EEULL,
|
||||
0xB680804BED143132ULL, 0x44E361B21986944CULL, 0x44C60170EF5C598CULL,
|
||||
0xF4DA475C195C9C94ULL, 0xA3AFBB5F72060B1DULL, 0xBC75F410E41C4FFCULL,
|
||||
0xB51C099390520922ULL, 0x902C011F8F8EC368ULL, 0x950B56B3D6F5490AULL,
|
||||
0x3909E0635BF202D0ULL, 0x5744F90206EC10CCULL, 0xDC59FD76317ABBC1ULL,
|
||||
0x881C7C67FCBFC4F6ULL, 0x47CA41E7E440D423ULL, 0xEB0C88112048D004ULL,
|
||||
0x51C60E04359AEF1AULL, 0x1AA1FE0E957A5554ULL, 0xDD9448DB4F5E3104ULL,
|
||||
0xDC01F6DCA4BEBBDCULL,
|
||||
};
|
||||
|
||||
const uint64_t RMult[64] = {
|
||||
0xD7445CDEC88002C0ULL, 0xD0A505C1F2001722ULL, 0xE065D1C896002182ULL,
|
||||
0x9A8C41E75A000892ULL, 0x8900B10C89002AA8ULL, 0x9B28D1C1D60005A2ULL,
|
||||
0x015D6C88DE002D9AULL, 0xB1DBFC802E8016A9ULL, 0x149A1042D9D60029ULL,
|
||||
0xB9C08050599E002FULL, 0x132208C3AF300403ULL, 0xC1000CE2E9C50070ULL,
|
||||
0x9D9AA13C99020012ULL, 0xB6B078DAF71E0046ULL, 0x9D880182FB6E002EULL,
|
||||
0x52889F467E850037ULL, 0xDA6DC008D19A8480ULL, 0x468286034F902420ULL,
|
||||
0x7140AC09DC54C020ULL, 0xD76FFFFA39548808ULL, 0xEA901C4141500808ULL,
|
||||
0xC91004093F953A02ULL, 0x02882AFA8F6BB402ULL, 0xAEBE335692442C01ULL,
|
||||
0x0E904A22079FB91EULL, 0x13A514851055F606ULL, 0x76C782018C8FE632ULL,
|
||||
0x1DC012A9D116DA06ULL, 0x3C9E0037264FFFA6ULL, 0x2036002853C6E4A2ULL,
|
||||
0xE3FE08500AFB47D4ULL, 0xF38AF25C86B025C2ULL, 0xC0800E2182CF9A40ULL,
|
||||
0x72002480D1F60673ULL, 0x2500200BAE6E9B53ULL, 0xC60018C1EEFCA252ULL,
|
||||
0x0600590473E3608AULL, 0x46002C4AB3FE51B2ULL, 0xA200011486BCC8D2ULL,
|
||||
0xB680078095784C63ULL, 0x2742002639BF11AEULL, 0xC7D60021A5BDB142ULL,
|
||||
0xC8C04016BB83D820ULL, 0xBD520028123B4842ULL, 0x9D1600344AC2A832ULL,
|
||||
0x6A808005631C8A05ULL, 0x604600A148D5389AULL, 0xE2E40103D40DEA65ULL,
|
||||
0x945B5A0087C62A81ULL, 0x012DC200CD82D28EULL, 0x2431C600B5F9EF76ULL,
|
||||
0xFB142A006A9B314AULL, 0x06870E00A1C97D62ULL, 0x2A9DB2004A2689A2ULL,
|
||||
0xD3594600CAF5D1A2ULL, 0xEE0E4900439344A7ULL, 0x89C4D266CA25007AULL,
|
||||
0x3E0013A2743F97E3ULL, 0x0180E31A0431378AULL, 0x3A9E465A4D42A512ULL,
|
||||
0x98D0A11A0C0D9CC2ULL, 0x8E711C1ABA19B01EULL, 0x8DCDC836DD201142ULL,
|
||||
0x5AC08A4735370479ULL,
|
||||
};
|
||||
|
||||
const int BShift[64] = {
|
||||
26, 27, 27, 27, 27, 27, 27, 26, 27, 27, 27, 27, 27, 27, 27, 27,
|
||||
27, 27, 25, 25, 25, 25, 27, 27, 27, 27, 25, 23, 23, 25, 27, 27,
|
||||
27, 27, 25, 23, 23, 25, 27, 27, 27, 27, 25, 25, 25, 25, 27, 27,
|
||||
27, 27, 27, 27, 27, 27, 27, 27, 26, 27, 27, 27, 27, 27, 27, 26
|
||||
};
|
||||
|
||||
const int RShift[64] = {
|
||||
20, 21, 21, 21, 21, 21, 21, 20, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||
21, 22, 22, 22, 22, 22, 22, 21, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||
21, 22, 22, 22, 22, 22, 22, 21, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||
21, 22, 22, 22, 22, 22, 22, 21, 20, 21, 21, 21, 21, 21, 21, 20
|
||||
};
|
||||
|
||||
#endif // defined(IS_64BIT)
|
||||
|
||||
// Global bitboards definitions with static storage duration are
|
||||
// automatically set to zero before enter main().
|
||||
Bitboard RMask[64];
|
||||
int RAttackIndex[64];
|
||||
Bitboard RAttacks[0x19000];
|
||||
|
||||
Bitboard BMask[64];
|
||||
int BAttackIndex[64];
|
||||
Bitboard BAttacks[0x1480];
|
||||
|
||||
Bitboard SetMaskBB[65];
|
||||
Bitboard ClearMaskBB[65];
|
||||
|
||||
Bitboard SquaresByColorBB[2];
|
||||
Bitboard SquareBB[64];
|
||||
Bitboard FileBB[8];
|
||||
Bitboard RankBB[8];
|
||||
Bitboard NeighboringFilesBB[8];
|
||||
Bitboard ThisAndNeighboringFilesBB[8];
|
||||
Bitboard AdjacentFilesBB[8];
|
||||
Bitboard ThisAndAdjacentFilesBB[8];
|
||||
Bitboard InFrontBB[2][8];
|
||||
Bitboard StepAttacksBB[16][64];
|
||||
Bitboard BetweenBB[64][64];
|
||||
Bitboard SquaresInFrontMask[2][64];
|
||||
Bitboard DistanceRingsBB[64][8];
|
||||
Bitboard ForwardBB[2][64];
|
||||
Bitboard PassedPawnMask[2][64];
|
||||
Bitboard AttackSpanMask[2][64];
|
||||
Bitboard PseudoAttacks[6][64];
|
||||
|
||||
Bitboard BishopPseudoAttacks[64];
|
||||
Bitboard RookPseudoAttacks[64];
|
||||
Bitboard QueenPseudoAttacks[64];
|
||||
|
||||
uint8_t BitCount8Bit[256];
|
||||
|
||||
int SquareDistance[64][64];
|
||||
|
||||
namespace {
|
||||
|
||||
void init_masks();
|
||||
void init_step_attacks();
|
||||
void init_pseudo_attacks();
|
||||
void init_between_bitboards();
|
||||
Bitboard index_to_bitboard(int index, Bitboard mask);
|
||||
Bitboard sliding_attacks(int sq, Bitboard occupied, int deltas[][2],
|
||||
int fmin, int fmax, int rmin, int rmax);
|
||||
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
|
||||
const int shift[], const Bitboard mult[], int deltas[][2]);
|
||||
}
|
||||
// De Bruijn sequences. See chessprogramming.wikispaces.com/BitScan
|
||||
const uint64_t DeBruijn_64 = 0x218A392CD3D5DBFULL;
|
||||
const uint32_t DeBruijn_32 = 0x783A9B23;
|
||||
|
||||
CACHE_LINE_ALIGNMENT
|
||||
|
||||
/// print_bitboard() prints a bitboard in an easily readable format to the
|
||||
/// standard output. This is sometimes useful for debugging.
|
||||
int MS1BTable[256];
|
||||
Square BSFTable[64];
|
||||
Bitboard RTable[0x19000]; // Storage space for rook attacks
|
||||
Bitboard BTable[0x1480]; // Storage space for bishop attacks
|
||||
uint8_t BitCount8Bit[256];
|
||||
|
||||
void print_bitboard(Bitboard b) {
|
||||
typedef unsigned (Fn)(Square, Bitboard);
|
||||
|
||||
for (Rank r = RANK_8; r >= RANK_1; r--)
|
||||
{
|
||||
std::cout << "+---+---+---+---+---+---+---+---+" << '\n';
|
||||
for (File f = FILE_A; f <= FILE_H; f++)
|
||||
std::cout << "| " << (bit_is_set(b, make_square(f, r)) ? 'X' : ' ') << ' ';
|
||||
void init_magics(Bitboard table[], Bitboard* attacks[], Bitboard magics[],
|
||||
Bitboard masks[], unsigned shifts[], Square deltas[], Fn index);
|
||||
|
||||
std::cout << "|\n";
|
||||
FORCE_INLINE unsigned bsf_index(Bitboard b) {
|
||||
|
||||
if (Is64Bit)
|
||||
return ((b & -b) * DeBruijn_64) >> 58;
|
||||
|
||||
// Use Matt Taylor's folding trick for 32 bit systems
|
||||
b ^= (b - 1);
|
||||
return ((unsigned(b) ^ unsigned(b >> 32)) * DeBruijn_32) >> 26;
|
||||
}
|
||||
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
|
||||
}
|
||||
|
||||
/// lsb()/msb() finds the least/most significant bit in a nonzero bitboard.
|
||||
/// pop_lsb() finds and clears the least significant bit in a nonzero bitboard.
|
||||
|
||||
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
||||
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
||||
/// nonzero bitboard.
|
||||
#if !defined(USE_BSFQ)
|
||||
|
||||
#if defined(IS_64BIT) && !defined(USE_BSFQ)
|
||||
Square lsb(Bitboard b) { return BSFTable[bsf_index(b)]; }
|
||||
|
||||
static CACHE_LINE_ALIGNMENT
|
||||
const int BitTable[64] = {
|
||||
0, 1, 2, 7, 3, 13, 8, 19, 4, 25, 14, 28, 9, 34, 20, 40, 5, 17, 26,
|
||||
38, 15, 46, 29, 48, 10, 31, 35, 54, 21, 50, 41, 57, 63, 6, 12, 18, 24, 27,
|
||||
33, 39, 16, 37, 45, 47, 30, 53, 49, 56, 62, 11, 23, 32, 36, 44, 52, 55, 61,
|
||||
22, 43, 51, 60, 42, 59, 58
|
||||
};
|
||||
Square pop_lsb(Bitboard* b) {
|
||||
|
||||
Square first_1(Bitboard b) {
|
||||
return Square(BitTable[((b & -b) * 0x218a392cd3d5dbfULL) >> 58]);
|
||||
}
|
||||
|
||||
Square pop_1st_bit(Bitboard* b) {
|
||||
Bitboard bb = *b;
|
||||
*b &= (*b - 1);
|
||||
return Square(BitTable[((bb & -bb) * 0x218a392cd3d5dbfULL) >> 58]);
|
||||
*b = bb & (bb - 1);
|
||||
return BSFTable[bsf_index(bb)];
|
||||
}
|
||||
|
||||
#elif !defined(USE_BSFQ)
|
||||
Square msb(Bitboard b) {
|
||||
|
||||
static CACHE_LINE_ALIGNMENT
|
||||
const int BitTable[64] = {
|
||||
63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2,
|
||||
51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5,
|
||||
52, 26, 60, 6, 23, 44, 46, 27, 56, 16, 7, 39, 48, 24, 59, 14, 12, 55, 38,
|
||||
28, 58, 20, 37, 17, 36, 8
|
||||
};
|
||||
unsigned b32;
|
||||
int result = 0;
|
||||
|
||||
Square first_1(Bitboard b) {
|
||||
if (b > 0xFFFFFFFF)
|
||||
{
|
||||
b >>= 32;
|
||||
result = 32;
|
||||
}
|
||||
|
||||
b ^= (b - 1);
|
||||
uint32_t fold = int(b) ^ int(b >> 32);
|
||||
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
|
||||
}
|
||||
b32 = unsigned(b);
|
||||
|
||||
// Use type-punning
|
||||
union b_union {
|
||||
if (b32 > 0xFFFF)
|
||||
{
|
||||
b32 >>= 16;
|
||||
result += 16;
|
||||
}
|
||||
|
||||
Bitboard b;
|
||||
struct {
|
||||
#if defined (BIGENDIAN)
|
||||
uint32_t h;
|
||||
uint32_t l;
|
||||
#else
|
||||
uint32_t l;
|
||||
uint32_t h;
|
||||
#endif
|
||||
} dw;
|
||||
};
|
||||
if (b32 > 0xFF)
|
||||
{
|
||||
b32 >>= 8;
|
||||
result += 8;
|
||||
}
|
||||
|
||||
Square pop_1st_bit(Bitboard* bb) {
|
||||
|
||||
b_union u;
|
||||
Square ret;
|
||||
|
||||
u.b = *bb;
|
||||
|
||||
if (u.dw.l)
|
||||
{
|
||||
ret = Square(BitTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783a9b23) >> 26]);
|
||||
u.dw.l &= (u.dw.l - 1);
|
||||
*bb = u.b;
|
||||
return ret;
|
||||
}
|
||||
ret = Square(BitTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783a9b23) >> 26]);
|
||||
u.dw.h &= (u.dw.h - 1);
|
||||
*bb = u.b;
|
||||
return ret;
|
||||
return (Square)(result + MS1BTable[b32]);
|
||||
}
|
||||
|
||||
#endif // !defined(USE_BSFQ)
|
||||
|
||||
|
||||
/// init_bitboards() initializes various bitboard arrays. It is called during
|
||||
/// Bitboards::print() prints a bitboard in an easily readable format to the
|
||||
/// standard output. This is sometimes useful for debugging.
|
||||
|
||||
void Bitboards::print(Bitboard b) {
|
||||
|
||||
sync_cout;
|
||||
|
||||
for (Rank rank = RANK_8; rank >= RANK_1; rank--)
|
||||
{
|
||||
std::cout << "+---+---+---+---+---+---+---+---+" << '\n';
|
||||
|
||||
for (File file = FILE_A; file <= FILE_H; file++)
|
||||
std::cout << "| " << (b & (file | rank) ? "X " : " ");
|
||||
|
||||
std::cout << "|\n";
|
||||
}
|
||||
std::cout << "+---+---+---+---+---+---+---+---+" << sync_endl;
|
||||
}
|
||||
|
||||
|
||||
/// Bitboards::init() initializes various bitboard arrays. It is called during
|
||||
/// program initialization.
|
||||
|
||||
void init_bitboards() {
|
||||
void Bitboards::init() {
|
||||
|
||||
int rookDeltas[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
|
||||
int bishopDeltas[4][2] = {{1,1},{-1,1},{1,-1},{-1,-1}};
|
||||
for (int k = 0, i = 0; i < 8; i++)
|
||||
while (k < (2 << i))
|
||||
MS1BTable[k++] = i;
|
||||
|
||||
init_masks();
|
||||
init_step_attacks();
|
||||
init_sliding_attacks(RAttacks, RAttackIndex, RMask, RShift, RMult, rookDeltas);
|
||||
init_sliding_attacks(BAttacks, BAttackIndex, BMask, BShift, BMult, bishopDeltas);
|
||||
init_pseudo_attacks();
|
||||
init_between_bitboards();
|
||||
for (int i = 0; i < 64; i++)
|
||||
BSFTable[bsf_index(1ULL << i)] = Square(i);
|
||||
|
||||
for (Bitboard b = 0; b < 256; b++)
|
||||
BitCount8Bit[b] = (uint8_t)popcount<Max15>(b);
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
SquareBB[s] = 1ULL << s;
|
||||
|
||||
FileBB[FILE_A] = FileABB;
|
||||
RankBB[RANK_1] = Rank1BB;
|
||||
|
||||
for (int i = 1; i < 8; i++)
|
||||
{
|
||||
FileBB[i] = FileBB[i - 1] << 1;
|
||||
RankBB[i] = RankBB[i - 1] << 8;
|
||||
}
|
||||
|
||||
for (File f = FILE_A; f <= FILE_H; f++)
|
||||
{
|
||||
AdjacentFilesBB[f] = (f > FILE_A ? FileBB[f - 1] : 0) | (f < FILE_H ? FileBB[f + 1] : 0);
|
||||
ThisAndAdjacentFilesBB[f] = FileBB[f] | AdjacentFilesBB[f];
|
||||
}
|
||||
|
||||
for (Rank r = RANK_1; r < RANK_8; r++)
|
||||
InFrontBB[WHITE][r] = ~(InFrontBB[BLACK][r + 1] = InFrontBB[BLACK][r] | RankBB[r]);
|
||||
|
||||
for (Color c = WHITE; c <= BLACK; c++)
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
{
|
||||
ForwardBB[c][s] = InFrontBB[c][rank_of(s)] & FileBB[file_of(s)];
|
||||
PassedPawnMask[c][s] = InFrontBB[c][rank_of(s)] & ThisAndAdjacentFilesBB[file_of(s)];
|
||||
AttackSpanMask[c][s] = InFrontBB[c][rank_of(s)] & AdjacentFilesBB[file_of(s)];
|
||||
}
|
||||
|
||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||
SquareDistance[s1][s2] = std::max(file_distance(s1, s2), rank_distance(s1, s2));
|
||||
|
||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||
for (int d = 1; d < 8; d++)
|
||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||
if (SquareDistance[s1][s2] == d)
|
||||
DistanceRingsBB[s1][d - 1] |= s2;
|
||||
|
||||
int steps[][9] = { {}, { 7, 9 }, { 17, 15, 10, 6, -6, -10, -15, -17 },
|
||||
{}, {}, {}, { 9, 7, -7, -9, 8, 1, -1, -8 } };
|
||||
|
||||
for (Color c = WHITE; c <= BLACK; c++)
|
||||
for (PieceType pt = PAWN; pt <= KING; pt++)
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
for (int k = 0; steps[pt][k]; k++)
|
||||
{
|
||||
Square to = s + Square(c == WHITE ? steps[pt][k] : -steps[pt][k]);
|
||||
|
||||
if (is_ok(to) && square_distance(s, to) < 3)
|
||||
StepAttacksBB[make_piece(c, pt)][s] |= to;
|
||||
}
|
||||
|
||||
Square RDeltas[] = { DELTA_N, DELTA_E, DELTA_S, DELTA_W };
|
||||
Square BDeltas[] = { DELTA_NE, DELTA_SE, DELTA_SW, DELTA_NW };
|
||||
|
||||
init_magics(RTable, RAttacks, RMagics, RMasks, RShifts, RDeltas, magic_index<ROOK>);
|
||||
init_magics(BTable, BAttacks, BMagics, BMasks, BShifts, BDeltas, magic_index<BISHOP>);
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
{
|
||||
PseudoAttacks[QUEEN][s] = PseudoAttacks[BISHOP][s] = attacks_bb<BISHOP>(s, 0);
|
||||
PseudoAttacks[QUEEN][s] |= PseudoAttacks[ ROOK][s] = attacks_bb< ROOK>(s, 0);
|
||||
}
|
||||
|
||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||
if (PseudoAttacks[QUEEN][s1] & s2)
|
||||
{
|
||||
Square delta = (s2 - s1) / square_distance(s1, s2);
|
||||
|
||||
for (Square s = s1 + delta; s != s2; s += delta)
|
||||
BetweenBB[s1][s2] |= s;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
// All functions below are used to precompute various bitboards during
|
||||
// program initialization. Some of the functions may be difficult to
|
||||
// understand, but they all seem to work correctly, and it should never
|
||||
// be necessary to touch any of them.
|
||||
Bitboard sliding_attack(Square deltas[], Square sq, Bitboard occupied) {
|
||||
|
||||
void init_masks() {
|
||||
|
||||
SquaresByColorBB[DARK] = 0xAA55AA55AA55AA55ULL;
|
||||
SquaresByColorBB[LIGHT] = ~SquaresByColorBB[DARK];
|
||||
|
||||
FileBB[FILE_A] = FileABB;
|
||||
RankBB[RANK_1] = Rank1BB;
|
||||
|
||||
for (int f = FILE_B; f <= FILE_H; f++)
|
||||
{
|
||||
FileBB[f] = FileBB[f - 1] << 1;
|
||||
RankBB[f] = RankBB[f - 1] << 8;
|
||||
}
|
||||
|
||||
for (int f = FILE_A; f <= FILE_H; f++)
|
||||
{
|
||||
NeighboringFilesBB[f] = (f > FILE_A ? FileBB[f - 1] : 0) | (f < FILE_H ? FileBB[f + 1] : 0);
|
||||
ThisAndNeighboringFilesBB[f] = FileBB[f] | NeighboringFilesBB[f];
|
||||
}
|
||||
|
||||
for (int rw = RANK_7, rb = RANK_2; rw >= RANK_1; rw--, rb++)
|
||||
{
|
||||
InFrontBB[WHITE][rw] = InFrontBB[WHITE][rw + 1] | RankBB[rw + 1];
|
||||
InFrontBB[BLACK][rb] = InFrontBB[BLACK][rb - 1] | RankBB[rb - 1];
|
||||
}
|
||||
|
||||
SetMaskBB[SQ_NONE] = EmptyBoardBB;
|
||||
ClearMaskBB[SQ_NONE] = ~SetMaskBB[SQ_NONE];
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
{
|
||||
SetMaskBB[s] = (1ULL << s);
|
||||
ClearMaskBB[s] = ~SetMaskBB[s];
|
||||
}
|
||||
|
||||
for (Color c = WHITE; c <= BLACK; c++)
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
{
|
||||
SquaresInFrontMask[c][s] = in_front_bb(c, s) & file_bb(s);
|
||||
PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(s);
|
||||
AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
|
||||
}
|
||||
|
||||
for (Bitboard b = 0; b < 256; b++)
|
||||
BitCount8Bit[b] = (uint8_t)count_1s<CNT32>(b);
|
||||
}
|
||||
|
||||
void init_step_attacks() {
|
||||
|
||||
const int step[][9] = {
|
||||
{0},
|
||||
{7,9,0}, {17,15,10,6,-6,-10,-15,-17,0}, {0}, {0}, {0},
|
||||
{9,7,-7,-9,8,1,-1,-8,0}, {0}, {0},
|
||||
{-7,-9,0}, {17,15,10,6,-6,-10,-15,-17,0}, {0}, {0}, {0},
|
||||
{9,7,-7,-9,8,1,-1,-8,0}
|
||||
};
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
for (Piece pc = WP; pc <= BK; pc++)
|
||||
for (int k = 0; step[pc][k] != 0; k++)
|
||||
{
|
||||
Square to = s + Square(step[pc][k]);
|
||||
|
||||
if (square_is_ok(to) && square_distance(s, to) < 3)
|
||||
set_bit(&StepAttacksBB[pc][s], to);
|
||||
}
|
||||
}
|
||||
|
||||
Bitboard sliding_attacks(int sq, Bitboard occupied, int deltas[][2],
|
||||
int fmin, int fmax, int rmin, int rmax) {
|
||||
int dx, dy, f, r;
|
||||
int rk = sq / 8;
|
||||
int fl = sq % 8;
|
||||
Bitboard attacks = EmptyBoardBB;
|
||||
Bitboard attack = 0;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
dx = deltas[i][0];
|
||||
dy = deltas[i][1];
|
||||
f = fl + dx;
|
||||
r = rk + dy;
|
||||
|
||||
while ( (dx == 0 || (f >= fmin && f <= fmax))
|
||||
&& (dy == 0 || (r >= rmin && r <= rmax)))
|
||||
for (Square s = sq + deltas[i];
|
||||
is_ok(s) && square_distance(s, s - deltas[i]) == 1;
|
||||
s += deltas[i])
|
||||
{
|
||||
attacks |= (1ULL << (f + r * 8));
|
||||
attack |= s;
|
||||
|
||||
if (occupied & (1ULL << (f + r * 8)))
|
||||
if (occupied & s)
|
||||
break;
|
||||
|
||||
f += dx;
|
||||
r += dy;
|
||||
}
|
||||
}
|
||||
return attacks;
|
||||
|
||||
return attack;
|
||||
}
|
||||
|
||||
Bitboard index_to_bitboard(int index, Bitboard mask) {
|
||||
|
||||
Bitboard result = EmptyBoardBB;
|
||||
int sq, cnt = 0;
|
||||
Bitboard pick_random(RKISS& rk, int booster) {
|
||||
|
||||
while (mask)
|
||||
{
|
||||
sq = pop_1st_bit(&mask);
|
||||
// Values s1 and s2 are used to rotate the candidate magic of a
|
||||
// quantity known to be the optimal to quickly find the magics.
|
||||
int s1 = booster & 63, s2 = (booster >> 6) & 63;
|
||||
|
||||
if (index & (1 << cnt++))
|
||||
result |= (1ULL << sq);
|
||||
}
|
||||
return result;
|
||||
Bitboard m = rk.rand<Bitboard>();
|
||||
m = (m >> s1) | (m << (64 - s1));
|
||||
m &= rk.rand<Bitboard>();
|
||||
m = (m >> s2) | (m << (64 - s2));
|
||||
return m & rk.rand<Bitboard>();
|
||||
}
|
||||
|
||||
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
|
||||
const int shift[], const Bitboard mult[], int deltas[][2]) {
|
||||
Bitboard b, v;
|
||||
int i, j, index;
|
||||
|
||||
for (i = index = 0; i < 64; i++)
|
||||
{
|
||||
attackIndex[i] = index;
|
||||
mask[i] = sliding_attacks(i, 0, deltas, 1, 6, 1, 6);
|
||||
j = 1 << ((CpuIs64Bit ? 64 : 32) - shift[i]);
|
||||
// init_magics() computes all rook and bishop attacks at startup. Magic
|
||||
// bitboards are used to look up attacks of sliding pieces. As a reference see
|
||||
// chessprogramming.wikispaces.com/Magic+Bitboards. In particular, here we
|
||||
// use the so called "fancy" approach.
|
||||
|
||||
for (int k = 0; k < j; k++)
|
||||
{
|
||||
b = index_to_bitboard(k, mask[i]);
|
||||
v = CpuIs64Bit ? b * mult[i] : unsigned(b * mult[i] ^ (b >> 32) * (mult[i] >> 32));
|
||||
attacks[index + (v >> shift[i])] = sliding_attacks(i, b, deltas, 0, 7, 0, 7);
|
||||
}
|
||||
index += j;
|
||||
}
|
||||
}
|
||||
void init_magics(Bitboard table[], Bitboard* attacks[], Bitboard magics[],
|
||||
Bitboard masks[], unsigned shifts[], Square deltas[], Fn index) {
|
||||
|
||||
void init_pseudo_attacks() {
|
||||
int MagicBoosters[][8] = { { 3191, 2184, 1310, 3618, 2091, 1308, 2452, 3996 },
|
||||
{ 1059, 3608, 605, 3234, 3326, 38, 2029, 3043 } };
|
||||
RKISS rk;
|
||||
Bitboard occupancy[4096], reference[4096], edges, b;
|
||||
int i, size, booster;
|
||||
|
||||
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
|
||||
attacks[SQ_A1] = table;
|
||||
|
||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||
{
|
||||
BishopPseudoAttacks[s] = bishop_attacks_bb(s, EmptyBoardBB);
|
||||
RookPseudoAttacks[s] = rook_attacks_bb(s, EmptyBoardBB);
|
||||
QueenPseudoAttacks[s] = queen_attacks_bb(s, EmptyBoardBB);
|
||||
// Board edges are not considered in the relevant occupancies
|
||||
edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
|
||||
|
||||
// Given a square 's', the mask is the bitboard of sliding attacks from
|
||||
// 's' computed on an empty board. The index must be big enough to contain
|
||||
// all the attacks for each possible subset of the mask and so is 2 power
|
||||
// the number of 1s of the mask. Hence we deduce the size of the shift to
|
||||
// apply to the 64 or 32 bits word to get the index.
|
||||
masks[s] = sliding_attack(deltas, s, 0) & ~edges;
|
||||
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
|
||||
|
||||
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
|
||||
// store the corresponding sliding attack bitboard in reference[].
|
||||
b = size = 0;
|
||||
do {
|
||||
occupancy[size] = b;
|
||||
reference[size++] = sliding_attack(deltas, s, b);
|
||||
b = (b - masks[s]) & masks[s];
|
||||
} while (b);
|
||||
|
||||
// Set the offset for the table of the next square. We have individual
|
||||
// table sizes for each square with "Fancy Magic Bitboards".
|
||||
if (s < SQ_H8)
|
||||
attacks[s + 1] = attacks[s] + size;
|
||||
|
||||
booster = MagicBoosters[Is64Bit][rank_of(s)];
|
||||
|
||||
// Find a magic for square 's' picking up an (almost) random number
|
||||
// until we find the one that passes the verification test.
|
||||
do {
|
||||
do magics[s] = pick_random(rk, booster);
|
||||
while (BitCount8Bit[(magics[s] * masks[s]) >> 56] < 6);
|
||||
|
||||
memset(attacks[s], 0, size * sizeof(Bitboard));
|
||||
|
||||
// A good magic must map every possible occupancy to an index that
|
||||
// looks up the correct sliding attack in the attacks[s] database.
|
||||
// Note that we build up the database for square 's' as a side
|
||||
// effect of verifying the magic.
|
||||
for (i = 0; i < size; i++)
|
||||
{
|
||||
Bitboard& attack = attacks[s][index(s, occupancy[i])];
|
||||
|
||||
if (attack && attack != reference[i])
|
||||
break;
|
||||
|
||||
assert(reference[i] != 0);
|
||||
|
||||
attack = reference[i];
|
||||
}
|
||||
} while (i != size);
|
||||
}
|
||||
}
|
||||
|
||||
void init_between_bitboards() {
|
||||
|
||||
Square s1, s2, s3, d;
|
||||
int f, r;
|
||||
|
||||
for (s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||
for (s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||
if (bit_is_set(QueenPseudoAttacks[s1], s2))
|
||||
{
|
||||
f = file_distance(s1, s2);
|
||||
r = rank_distance(s1, s2);
|
||||
|
||||
d = (s2 - s1) / Max(f, r);
|
||||
|
||||
for (s3 = s1 + d; s3 != s2; s3 += d)
|
||||
set_bit(&(BetweenBB[s1][s2]), s3);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
295
src/bitboard.h
295
src/bitboard.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -23,87 +23,75 @@
|
||||
|
||||
#include "types.h"
|
||||
|
||||
const Bitboard EmptyBoardBB = 0;
|
||||
namespace Bitboards {
|
||||
|
||||
const Bitboard FileABB = 0x0101010101010101ULL;
|
||||
const Bitboard FileBBB = FileABB << 1;
|
||||
const Bitboard FileCBB = FileABB << 2;
|
||||
const Bitboard FileDBB = FileABB << 3;
|
||||
const Bitboard FileEBB = FileABB << 4;
|
||||
const Bitboard FileFBB = FileABB << 5;
|
||||
const Bitboard FileGBB = FileABB << 6;
|
||||
const Bitboard FileHBB = FileABB << 7;
|
||||
void init();
|
||||
void print(Bitboard b);
|
||||
|
||||
const Bitboard Rank1BB = 0xFF;
|
||||
const Bitboard Rank2BB = Rank1BB << (8 * 1);
|
||||
const Bitboard Rank3BB = Rank1BB << (8 * 2);
|
||||
const Bitboard Rank4BB = Rank1BB << (8 * 3);
|
||||
const Bitboard Rank5BB = Rank1BB << (8 * 4);
|
||||
const Bitboard Rank6BB = Rank1BB << (8 * 5);
|
||||
const Bitboard Rank7BB = Rank1BB << (8 * 6);
|
||||
const Bitboard Rank8BB = Rank1BB << (8 * 7);
|
||||
}
|
||||
|
||||
extern Bitboard SquaresByColorBB[2];
|
||||
namespace Bitbases {
|
||||
|
||||
void init_kpk();
|
||||
uint32_t probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm);
|
||||
|
||||
}
|
||||
|
||||
CACHE_LINE_ALIGNMENT
|
||||
|
||||
extern Bitboard RMasks[64];
|
||||
extern Bitboard RMagics[64];
|
||||
extern Bitboard* RAttacks[64];
|
||||
extern unsigned RShifts[64];
|
||||
|
||||
extern Bitboard BMasks[64];
|
||||
extern Bitboard BMagics[64];
|
||||
extern Bitboard* BAttacks[64];
|
||||
extern unsigned BShifts[64];
|
||||
|
||||
extern Bitboard SquareBB[64];
|
||||
extern Bitboard FileBB[8];
|
||||
extern Bitboard NeighboringFilesBB[8];
|
||||
extern Bitboard ThisAndNeighboringFilesBB[8];
|
||||
extern Bitboard RankBB[8];
|
||||
extern Bitboard AdjacentFilesBB[8];
|
||||
extern Bitboard ThisAndAdjacentFilesBB[8];
|
||||
extern Bitboard InFrontBB[2][8];
|
||||
|
||||
extern Bitboard SetMaskBB[65];
|
||||
extern Bitboard ClearMaskBB[65];
|
||||
|
||||
extern Bitboard StepAttacksBB[16][64];
|
||||
extern Bitboard BetweenBB[64][64];
|
||||
|
||||
extern Bitboard SquaresInFrontMask[2][64];
|
||||
extern Bitboard DistanceRingsBB[64][8];
|
||||
extern Bitboard ForwardBB[2][64];
|
||||
extern Bitboard PassedPawnMask[2][64];
|
||||
extern Bitboard AttackSpanMask[2][64];
|
||||
|
||||
extern const uint64_t RMult[64];
|
||||
extern const int RShift[64];
|
||||
extern Bitboard RMask[64];
|
||||
extern int RAttackIndex[64];
|
||||
extern Bitboard RAttacks[0x19000];
|
||||
|
||||
extern const uint64_t BMult[64];
|
||||
extern const int BShift[64];
|
||||
extern Bitboard BMask[64];
|
||||
extern int BAttackIndex[64];
|
||||
extern Bitboard BAttacks[0x1480];
|
||||
|
||||
extern Bitboard BishopPseudoAttacks[64];
|
||||
extern Bitboard RookPseudoAttacks[64];
|
||||
extern Bitboard QueenPseudoAttacks[64];
|
||||
|
||||
extern uint8_t BitCount8Bit[256];
|
||||
extern Bitboard PseudoAttacks[6][64];
|
||||
|
||||
|
||||
/// Functions for testing whether a given bit is set in a bitboard, and for
|
||||
/// setting and clearing bits.
|
||||
/// Overloads of bitwise operators between a Bitboard and a Square for testing
|
||||
/// whether a given bit is set in a bitboard, and for setting and clearing bits.
|
||||
|
||||
inline Bitboard bit_is_set(Bitboard b, Square s) {
|
||||
return b & SetMaskBB[s];
|
||||
inline Bitboard operator&(Bitboard b, Square s) {
|
||||
return b & SquareBB[s];
|
||||
}
|
||||
|
||||
inline void set_bit(Bitboard *b, Square s) {
|
||||
*b |= SetMaskBB[s];
|
||||
inline Bitboard& operator|=(Bitboard& b, Square s) {
|
||||
return b |= SquareBB[s];
|
||||
}
|
||||
|
||||
inline void clear_bit(Bitboard *b, Square s) {
|
||||
*b &= ClearMaskBB[s];
|
||||
inline Bitboard& operator^=(Bitboard& b, Square s) {
|
||||
return b ^= SquareBB[s];
|
||||
}
|
||||
|
||||
inline Bitboard operator|(Bitboard b, Square s) {
|
||||
return b | SquareBB[s];
|
||||
}
|
||||
|
||||
inline Bitboard operator^(Bitboard b, Square s) {
|
||||
return b ^ SquareBB[s];
|
||||
}
|
||||
|
||||
|
||||
/// Functions used to update a bitboard after a move. This is faster
|
||||
/// then calling a sequence of clear_bit() + set_bit()
|
||||
/// more_than_one() returns true if in 'b' there is more than one bit set
|
||||
|
||||
inline Bitboard make_move_bb(Square from, Square to) {
|
||||
return SetMaskBB[from] | SetMaskBB[to];
|
||||
}
|
||||
|
||||
inline void do_move_bb(Bitboard *b, Bitboard move_bb) {
|
||||
*b ^= move_bb;
|
||||
inline bool more_than_one(Bitboard b) {
|
||||
return b & (b - 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -115,7 +103,7 @@ inline Bitboard rank_bb(Rank r) {
|
||||
}
|
||||
|
||||
inline Bitboard rank_bb(Square s) {
|
||||
return RankBB[square_rank(s)];
|
||||
return RankBB[rank_of(s)];
|
||||
}
|
||||
|
||||
inline Bitboard file_bb(File f) {
|
||||
@@ -123,31 +111,23 @@ inline Bitboard file_bb(File f) {
|
||||
}
|
||||
|
||||
inline Bitboard file_bb(Square s) {
|
||||
return FileBB[square_file(s)];
|
||||
return FileBB[file_of(s)];
|
||||
}
|
||||
|
||||
|
||||
/// neighboring_files_bb takes a file or a square as input and returns a
|
||||
/// bitboard representing all squares on the neighboring files.
|
||||
/// adjacent_files_bb takes a file as input and returns a bitboard representing
|
||||
/// all squares on the adjacent files.
|
||||
|
||||
inline Bitboard neighboring_files_bb(File f) {
|
||||
return NeighboringFilesBB[f];
|
||||
}
|
||||
|
||||
inline Bitboard neighboring_files_bb(Square s) {
|
||||
return NeighboringFilesBB[square_file(s)];
|
||||
inline Bitboard adjacent_files_bb(File f) {
|
||||
return AdjacentFilesBB[f];
|
||||
}
|
||||
|
||||
|
||||
/// this_and_neighboring_files_bb takes a file or a square as input and returns
|
||||
/// a bitboard representing all squares on the given and neighboring files.
|
||||
/// this_and_adjacent_files_bb takes a file as input and returns a bitboard
|
||||
/// representing all squares on the given and adjacent files.
|
||||
|
||||
inline Bitboard this_and_neighboring_files_bb(File f) {
|
||||
return ThisAndNeighboringFilesBB[f];
|
||||
}
|
||||
|
||||
inline Bitboard this_and_neighboring_files_bb(Square s) {
|
||||
return ThisAndNeighboringFilesBB[square_file(s)];
|
||||
inline Bitboard this_and_adjacent_files_bb(File f) {
|
||||
return ThisAndAdjacentFilesBB[f];
|
||||
}
|
||||
|
||||
|
||||
@@ -162,72 +142,34 @@ inline Bitboard in_front_bb(Color c, Rank r) {
|
||||
}
|
||||
|
||||
inline Bitboard in_front_bb(Color c, Square s) {
|
||||
return InFrontBB[c][square_rank(s)];
|
||||
return InFrontBB[c][rank_of(s)];
|
||||
}
|
||||
|
||||
|
||||
/// Functions for computing sliding attack bitboards. rook_attacks_bb(),
|
||||
/// bishop_attacks_bb() and queen_attacks_bb() all take a square and a
|
||||
/// bitboard of occupied squares as input, and return a bitboard representing
|
||||
/// all squares attacked by a rook, bishop or queen on the given square.
|
||||
/// between_bb returns a bitboard representing all squares between two squares.
|
||||
/// For instance, between_bb(SQ_C4, SQ_F7) returns a bitboard with the bits for
|
||||
/// square d5 and e6 set. If s1 and s2 are not on the same line, file or diagonal,
|
||||
/// 0 is returned.
|
||||
|
||||
#if defined(IS_64BIT)
|
||||
|
||||
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
|
||||
Bitboard b = blockers & RMask[s];
|
||||
return RAttacks[RAttackIndex[s] + ((b * RMult[s]) >> RShift[s])];
|
||||
}
|
||||
|
||||
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
|
||||
Bitboard b = blockers & BMask[s];
|
||||
return BAttacks[BAttackIndex[s] + ((b * BMult[s]) >> BShift[s])];
|
||||
}
|
||||
|
||||
#else // if !defined(IS_64BIT)
|
||||
|
||||
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
|
||||
Bitboard b = blockers & RMask[s];
|
||||
return RAttacks[RAttackIndex[s] +
|
||||
(unsigned(int(b) * int(RMult[s]) ^ int(b >> 32) * int(RMult[s] >> 32)) >> RShift[s])];
|
||||
}
|
||||
|
||||
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
|
||||
Bitboard b = blockers & BMask[s];
|
||||
return BAttacks[BAttackIndex[s] +
|
||||
(unsigned(int(b) * int(BMult[s]) ^ int(b >> 32) * int(BMult[s] >> 32)) >> BShift[s])];
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
inline Bitboard queen_attacks_bb(Square s, Bitboard blockers) {
|
||||
return rook_attacks_bb(s, blockers) | bishop_attacks_bb(s, blockers);
|
||||
}
|
||||
|
||||
|
||||
/// squares_between returns a bitboard representing all squares between
|
||||
/// two squares. For instance, squares_between(SQ_C4, SQ_F7) returns a
|
||||
/// bitboard with the bits for square d5 and e6 set. If s1 and s2 are not
|
||||
/// on the same line, file or diagonal, EmptyBoardBB is returned.
|
||||
|
||||
inline Bitboard squares_between(Square s1, Square s2) {
|
||||
inline Bitboard between_bb(Square s1, Square s2) {
|
||||
return BetweenBB[s1][s2];
|
||||
}
|
||||
|
||||
|
||||
/// squares_in_front_of takes a color and a square as input, and returns a
|
||||
/// bitboard representing all squares along the line in front of the square,
|
||||
/// from the point of view of the given color. Definition of the table is:
|
||||
/// SquaresInFrontOf[c][s] = in_front_bb(c, s) & file_bb(s)
|
||||
/// forward_bb takes a color and a square as input, and returns a bitboard
|
||||
/// representing all squares along the line in front of the square, from the
|
||||
/// point of view of the given color. Definition of the table is:
|
||||
/// ForwardBB[c][s] = in_front_bb(c, s) & file_bb(s)
|
||||
|
||||
inline Bitboard squares_in_front_of(Color c, Square s) {
|
||||
return SquaresInFrontMask[c][s];
|
||||
inline Bitboard forward_bb(Color c, Square s) {
|
||||
return ForwardBB[c][s];
|
||||
}
|
||||
|
||||
|
||||
/// passed_pawn_mask takes a color and a square as input, and returns a
|
||||
/// bitboard mask which can be used to test if a pawn of the given color on
|
||||
/// the given square is a passed pawn. Definition of the table is:
|
||||
/// PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(s)
|
||||
/// PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_adjacent_files_bb(s)
|
||||
|
||||
inline Bitboard passed_pawn_mask(Color c, Square s) {
|
||||
return PassedPawnMask[c][s];
|
||||
@@ -237,7 +179,7 @@ inline Bitboard passed_pawn_mask(Color c, Square s) {
|
||||
/// attack_span_mask takes a color and a square as input, and returns a bitboard
|
||||
/// representing all squares that can be attacked by a pawn of the given color
|
||||
/// when it moves along its file starting from the given square. Definition is:
|
||||
/// AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
|
||||
/// AttackSpanMask[c][s] = in_front_bb(c, s) & adjacent_files_bb(s);
|
||||
|
||||
inline Bitboard attack_span_mask(Color c, Square s) {
|
||||
return AttackSpanMask[c][s];
|
||||
@@ -249,47 +191,90 @@ inline Bitboard attack_span_mask(Color c, Square s) {
|
||||
|
||||
inline bool squares_aligned(Square s1, Square s2, Square s3) {
|
||||
return (BetweenBB[s1][s2] | BetweenBB[s1][s3] | BetweenBB[s2][s3])
|
||||
& ((1ULL << s1) | (1ULL << s2) | (1ULL << s3));
|
||||
& ( SquareBB[s1] | SquareBB[s2] | SquareBB[s3]);
|
||||
}
|
||||
|
||||
|
||||
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
||||
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
||||
/// nonzero bitboard.
|
||||
/// same_color_squares() returns a bitboard representing all squares with
|
||||
/// the same color of the given square.
|
||||
|
||||
inline Bitboard same_color_squares(Square s) {
|
||||
return Bitboard(0xAA55AA55AA55AA55ULL) & s ? 0xAA55AA55AA55AA55ULL
|
||||
: ~0xAA55AA55AA55AA55ULL;
|
||||
}
|
||||
|
||||
|
||||
/// Functions for computing sliding attack bitboards. Function attacks_bb() takes
|
||||
/// a square and a bitboard of occupied squares as input, and returns a bitboard
|
||||
/// representing all squares attacked by Pt (bishop or rook) on the given square.
|
||||
template<PieceType Pt>
|
||||
FORCE_INLINE unsigned magic_index(Square s, Bitboard occ) {
|
||||
|
||||
Bitboard* const Masks = Pt == ROOK ? RMasks : BMasks;
|
||||
Bitboard* const Magics = Pt == ROOK ? RMagics : BMagics;
|
||||
unsigned* const Shifts = Pt == ROOK ? RShifts : BShifts;
|
||||
|
||||
if (Is64Bit)
|
||||
return unsigned(((occ & Masks[s]) * Magics[s]) >> Shifts[s]);
|
||||
|
||||
unsigned lo = unsigned(occ) & unsigned(Masks[s]);
|
||||
unsigned hi = unsigned(occ >> 32) & unsigned(Masks[s] >> 32);
|
||||
return (lo * unsigned(Magics[s]) ^ hi * unsigned(Magics[s] >> 32)) >> Shifts[s];
|
||||
}
|
||||
|
||||
template<PieceType Pt>
|
||||
inline Bitboard attacks_bb(Square s, Bitboard occ) {
|
||||
return (Pt == ROOK ? RAttacks : BAttacks)[s][magic_index<Pt>(s, occ)];
|
||||
}
|
||||
|
||||
|
||||
/// lsb()/msb() finds the least/most significant bit in a nonzero bitboard.
|
||||
/// pop_lsb() finds and clears the least significant bit in a nonzero bitboard.
|
||||
|
||||
#if defined(USE_BSFQ)
|
||||
|
||||
#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
|
||||
# if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
|
||||
|
||||
FORCE_INLINE Square first_1(Bitboard b) {
|
||||
unsigned long index;
|
||||
_BitScanForward64(&index, b);
|
||||
return (Square) index;
|
||||
FORCE_INLINE Square lsb(Bitboard b) {
|
||||
unsigned long index;
|
||||
_BitScanForward64(&index, b);
|
||||
return (Square) index;
|
||||
}
|
||||
#else
|
||||
|
||||
FORCE_INLINE Square first_1(Bitboard b) { // Assembly code by Heinz van Saanen
|
||||
Bitboard dummy;
|
||||
__asm__("bsfq %1, %0": "=r"(dummy): "rm"(b) );
|
||||
return (Square) dummy;
|
||||
FORCE_INLINE Square msb(Bitboard b) {
|
||||
unsigned long index;
|
||||
_BitScanReverse64(&index, b);
|
||||
return (Square) index;
|
||||
}
|
||||
#endif
|
||||
|
||||
FORCE_INLINE Square pop_1st_bit(Bitboard* b) {
|
||||
const Square s = first_1(*b);
|
||||
*b &= ~(1ULL<<s);
|
||||
# else
|
||||
|
||||
FORCE_INLINE Square lsb(Bitboard b) { // Assembly code by Heinz van Saanen
|
||||
Bitboard index;
|
||||
__asm__("bsfq %1, %0": "=r"(index): "rm"(b) );
|
||||
return (Square) index;
|
||||
}
|
||||
|
||||
FORCE_INLINE Square msb(Bitboard b) {
|
||||
Bitboard index;
|
||||
__asm__("bsrq %1, %0": "=r"(index): "rm"(b) );
|
||||
return (Square) index;
|
||||
}
|
||||
|
||||
# endif
|
||||
|
||||
FORCE_INLINE Square pop_lsb(Bitboard* b) {
|
||||
const Square s = lsb(*b);
|
||||
*b &= ~(1ULL << s);
|
||||
return s;
|
||||
}
|
||||
|
||||
#else // if !defined(USE_BSFQ)
|
||||
|
||||
extern Square first_1(Bitboard b);
|
||||
extern Square pop_1st_bit(Bitboard* b);
|
||||
extern Square msb(Bitboard b);
|
||||
extern Square lsb(Bitboard b);
|
||||
extern Square pop_lsb(Bitboard* b);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
extern void print_bitboard(Bitboard b);
|
||||
extern void init_bitboards();
|
||||
|
||||
#endif // !defined(BITBOARD_H_INCLUDED)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -21,25 +21,29 @@
|
||||
#if !defined(BITCOUNT_H_INCLUDED)
|
||||
#define BITCOUNT_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
#include "types.h"
|
||||
|
||||
enum BitCountType {
|
||||
CNT64,
|
||||
CNT64_MAX15,
|
||||
CNT32,
|
||||
CNT32_MAX15,
|
||||
CNT_POPCNT
|
||||
CNT_64,
|
||||
CNT_64_MAX15,
|
||||
CNT_32,
|
||||
CNT_32_MAX15,
|
||||
CNT_HW_POPCNT
|
||||
};
|
||||
|
||||
/// count_1s() counts the number of nonzero bits in a bitboard.
|
||||
/// We have different optimized versions according if platform
|
||||
/// is 32 or 64 bits, and to the maximum number of nonzero bits.
|
||||
/// We also support hardware popcnt instruction. See Readme.txt
|
||||
/// on how to pgo compile with popcnt support.
|
||||
template<BitCountType> inline int count_1s(Bitboard);
|
||||
/// Determine at compile time the best popcount<> specialization according if
|
||||
/// platform is 32 or 64 bits, to the maximum number of nonzero bits to count or
|
||||
/// use hardware popcnt instruction when available.
|
||||
const BitCountType Full = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64 : CNT_32;
|
||||
const BitCountType Max15 = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64_MAX15 : CNT_32_MAX15;
|
||||
|
||||
|
||||
/// popcount() counts the number of nonzero bits in a bitboard
|
||||
template<BitCountType> inline int popcount(Bitboard);
|
||||
|
||||
template<>
|
||||
inline int count_1s<CNT64>(Bitboard b) {
|
||||
inline int popcount<CNT_64>(Bitboard b) {
|
||||
b -= ((b>>1) & 0x5555555555555555ULL);
|
||||
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
|
||||
@@ -48,7 +52,7 @@ inline int count_1s<CNT64>(Bitboard b) {
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int count_1s<CNT64_MAX15>(Bitboard b) {
|
||||
inline int popcount<CNT_64_MAX15>(Bitboard b) {
|
||||
b -= (b>>1) & 0x5555555555555555ULL;
|
||||
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||
b *= 0x1111111111111111ULL;
|
||||
@@ -56,7 +60,7 @@ inline int count_1s<CNT64_MAX15>(Bitboard b) {
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int count_1s<CNT32>(Bitboard b) {
|
||||
inline int popcount<CNT_32>(Bitboard b) {
|
||||
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||
w -= (w >> 1) & 0x55555555;
|
||||
@@ -69,7 +73,7 @@ inline int count_1s<CNT32>(Bitboard b) {
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int count_1s<CNT32_MAX15>(Bitboard b) {
|
||||
inline int popcount<CNT_32_MAX15>(Bitboard b) {
|
||||
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||
w -= (w >> 1) & 0x55555555;
|
||||
@@ -81,17 +85,27 @@ inline int count_1s<CNT32_MAX15>(Bitboard b) {
|
||||
}
|
||||
|
||||
template<>
|
||||
inline int count_1s<CNT_POPCNT>(Bitboard b) {
|
||||
inline int popcount<CNT_HW_POPCNT>(Bitboard b) {
|
||||
|
||||
#if !defined(USE_POPCNT)
|
||||
return int(b != 0); // Avoid 'b not used' warning
|
||||
|
||||
assert(false);
|
||||
return b != 0; // Avoid 'b not used' warning
|
||||
|
||||
#elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
|
||||
|
||||
return _mm_popcnt_u64(b);
|
||||
|
||||
#elif defined(_MSC_VER)
|
||||
|
||||
return (int)__popcnt64(b);
|
||||
#elif defined(__GNUC__)
|
||||
|
||||
#else
|
||||
|
||||
unsigned long ret;
|
||||
__asm__("popcnt %1, %0" : "=r" (ret) : "r" (b));
|
||||
return ret;
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
319
src/book.cpp
319
src/book.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,25 +17,36 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
The code in this file is based on the opening book code in PolyGlot
|
||||
by Fabien Letouzey. PolyGlot is available under the GNU General
|
||||
Public License, and can be downloaded from http://wbec-ridderkerk.nl
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
#include "book.h"
|
||||
#include "misc.h"
|
||||
#include "movegen.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace {
|
||||
|
||||
// A Polyglot book is a series of "entries" of 16 bytes. All integers are
|
||||
// stored in big-endian format, with highest byte first (regardless of size).
|
||||
// The entries are ordered according to the key in ascending order.
|
||||
struct BookEntry {
|
||||
uint64_t key;
|
||||
uint16_t move;
|
||||
uint16_t count;
|
||||
uint32_t learn;
|
||||
};
|
||||
|
||||
// Random numbers from PolyGlot, used to compute book hash keys
|
||||
const uint64_t Random64[781] = {
|
||||
const Key PolyGlotRandoms[781] = {
|
||||
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
|
||||
0x9C15F73E62A76AE2ULL, 0x75834465489C0C89ULL, 0x3290AC3A203001BFULL,
|
||||
0x0FBBAD1F61042279ULL, 0xE83A908FF2FB60CAULL, 0x0D7E765D58755C10ULL,
|
||||
@@ -299,242 +310,172 @@ namespace {
|
||||
0xF8D626AAAF278509ULL
|
||||
};
|
||||
|
||||
// Indices to the Random64[] array
|
||||
const int PieceIdx = 0;
|
||||
const int CastleIdx = 768;
|
||||
const int EnPassantIdx = 772;
|
||||
const int TurnIdx = 780;
|
||||
// Offsets to the PolyGlotRandoms[] array of zobrist keys
|
||||
const Key* ZobPiece = PolyGlotRandoms;
|
||||
const Key* ZobCastle = ZobPiece + 12 * 64; // Pieces * squares
|
||||
const Key* ZobEnPassant = ZobCastle + 4; // Castle flags
|
||||
const Key* ZobTurn = ZobEnPassant + 8; // Number of files
|
||||
|
||||
// book_key() builds up a PolyGlot hash key out of a position
|
||||
// book_key() returns the PolyGlot hash key of the given position
|
||||
uint64_t book_key(const Position& pos) {
|
||||
|
||||
// Piece offset is calculated as (64 * PolyPieceType + square), where
|
||||
// PolyPieceType is: BP = 0, WP = 1, BN = 2, WN = 3 .... BK = 10, WK = 11
|
||||
static const int PieceToPoly[] = { 0, 1, 3, 5, 7, 9, 11, 0, 0, 0, 2, 4, 6, 8, 10 };
|
||||
|
||||
uint64_t result = 0;
|
||||
Bitboard b = pos.occupied_squares();
|
||||
uint64_t key = 0;
|
||||
Bitboard b = pos.pieces();
|
||||
|
||||
while (b)
|
||||
{
|
||||
Square s = pop_1st_bit(&b);
|
||||
int p = PieceToPoly[int(pos.piece_on(s))];
|
||||
result ^= Random64[PieceIdx + 64 * p + int(s)];
|
||||
// In PolyGlotRandoms[] pieces are stored in the following sequence:
|
||||
// BP = 0, WP = 1, BN = 2, WN = 3, ... BK = 10, WK = 11
|
||||
Square s = pop_lsb(&b);
|
||||
Piece p = pos.piece_on(s);
|
||||
int pieceOfs = 2 * (type_of(p) - 1) + (color_of(p) == WHITE);
|
||||
key ^= ZobPiece[64 * pieceOfs + s];
|
||||
}
|
||||
|
||||
if (pos.can_castle_kingside(WHITE))
|
||||
result ^= Random64[CastleIdx + 0];
|
||||
b = pos.can_castle(ALL_CASTLES);
|
||||
|
||||
if (pos.can_castle_queenside(WHITE))
|
||||
result ^= Random64[CastleIdx + 1];
|
||||
|
||||
if (pos.can_castle_kingside(BLACK))
|
||||
result ^= Random64[CastleIdx + 2];
|
||||
|
||||
if (pos.can_castle_queenside(BLACK))
|
||||
result ^= Random64[CastleIdx + 3];
|
||||
while (b)
|
||||
key ^= ZobCastle[pop_lsb(&b)];
|
||||
|
||||
if (pos.ep_square() != SQ_NONE)
|
||||
result ^= Random64[EnPassantIdx + square_file(pos.ep_square())];
|
||||
key ^= ZobEnPassant[file_of(pos.ep_square())];
|
||||
|
||||
if (pos.side_to_move() == WHITE)
|
||||
result ^= Random64[TurnIdx];
|
||||
key ^= ZobTurn[0];
|
||||
|
||||
return result;
|
||||
return key;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PolyglotBook::PolyglotBook() {
|
||||
|
||||
for (int i = Time::now() % 10000; i > 0; i--)
|
||||
RKiss.rand<unsigned>(); // Make random number generation less deterministic
|
||||
}
|
||||
|
||||
PolyglotBook::~PolyglotBook() { if (is_open()) close(); }
|
||||
|
||||
|
||||
/// operator>>() reads sizeof(T) chars from the file's binary byte stream and
|
||||
/// converts them in a number of type T. A Polyglot book stores numbers in
|
||||
/// big-endian format.
|
||||
|
||||
template<typename T> PolyglotBook& PolyglotBook::operator>>(T& n) {
|
||||
|
||||
n = 0;
|
||||
for (size_t i = 0; i < sizeof(T); i++)
|
||||
n = T((n << 8) + ifstream::get());
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<> PolyglotBook& PolyglotBook::operator>>(BookEntry& e) {
|
||||
return *this >> e.key >> e.move >> e.count >> e.learn;
|
||||
}
|
||||
|
||||
|
||||
/// Book c'tor. Make random number generation less deterministic, for book moves
|
||||
Book::Book() {
|
||||
/// open() tries to open a book file with the given name after closing any
|
||||
/// exsisting one.
|
||||
|
||||
for (int i = abs(get_system_time() % 10000); i > 0; i--)
|
||||
RKiss.rand<unsigned>();
|
||||
bool PolyglotBook::open(const char* fName) {
|
||||
|
||||
if (is_open()) // Cannot close an already closed file
|
||||
close();
|
||||
|
||||
ifstream::open(fName, ifstream::in | ifstream::binary);
|
||||
|
||||
fileName = is_open() ? fName : "";
|
||||
ifstream::clear(); // Reset any error flag to allow retry ifstream::open()
|
||||
return !fileName.empty();
|
||||
}
|
||||
|
||||
|
||||
/// Book destructor. Be sure file is closed before we leave.
|
||||
/// probe() tries to find a book move for the given position. If no move is
|
||||
/// found returns MOVE_NONE. If pickBest is true returns always the highest
|
||||
/// rated move, otherwise randomly chooses one, based on the move score.
|
||||
|
||||
Book::~Book() {
|
||||
Move PolyglotBook::probe(const Position& pos, const string& fName, bool pickBest) {
|
||||
|
||||
close();
|
||||
}
|
||||
|
||||
|
||||
/// Book::close() closes the file only if it is open, otherwise
|
||||
/// we can end up in a little mess due to how std::ifstream works.
|
||||
|
||||
void Book::close() {
|
||||
|
||||
if (bookFile.is_open())
|
||||
bookFile.close();
|
||||
|
||||
bookName = "";
|
||||
}
|
||||
|
||||
|
||||
/// Book::open() opens a book file with a given file name
|
||||
|
||||
void Book::open(const string& fileName) {
|
||||
|
||||
// Close old file before opening the new
|
||||
close();
|
||||
|
||||
bookFile.open(fileName.c_str(), ifstream::in | ifstream::binary);
|
||||
|
||||
// Silently return when asked to open a non-exsistent file
|
||||
if (!bookFile.is_open())
|
||||
return;
|
||||
|
||||
// Get the book size in number of entries
|
||||
bookFile.seekg(0, ios::end);
|
||||
bookSize = long(bookFile.tellg()) / sizeof(BookEntry);
|
||||
|
||||
if (!bookFile.good())
|
||||
{
|
||||
cerr << "Failed to open book file " << fileName << endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Set only if successful
|
||||
bookName = fileName;
|
||||
}
|
||||
|
||||
|
||||
/// Book::get_move() gets a book move for a given position. Returns
|
||||
/// MOVE_NONE if no book move is found. If findBestMove is true then
|
||||
/// return always the highest rated book move.
|
||||
|
||||
Move Book::get_move(const Position& pos, bool findBestMove) {
|
||||
|
||||
if (!bookFile.is_open() || bookSize == 0)
|
||||
if (fileName != fName && !open(fName.c_str()))
|
||||
return MOVE_NONE;
|
||||
|
||||
BookEntry entry;
|
||||
int bookMove = MOVE_NONE;
|
||||
unsigned score, scoresSum = 0, bestScore = 0;
|
||||
BookEntry e;
|
||||
uint16_t best = 0;
|
||||
unsigned sum = 0;
|
||||
Move move = MOVE_NONE;
|
||||
uint64_t key = book_key(pos);
|
||||
|
||||
// Choose a book move among the possible moves for the given position
|
||||
for (int idx = find_entry(key); idx < bookSize; idx++)
|
||||
seekg(find_first(key) * sizeof(BookEntry), ios_base::beg);
|
||||
|
||||
while (*this >> e, e.key == key && good())
|
||||
{
|
||||
entry = read_entry(idx);
|
||||
best = max(best, e.count);
|
||||
sum += e.count;
|
||||
|
||||
if (entry.key != key)
|
||||
break;
|
||||
|
||||
score = entry.count;
|
||||
|
||||
if (!findBestMove)
|
||||
{
|
||||
// Choose book move according to its score. If a move has a very
|
||||
// high score it has more probability to be choosen then a one with
|
||||
// lower score. Note that first entry is always chosen.
|
||||
scoresSum += score;
|
||||
if (RKiss.rand<unsigned>() % scoresSum < score)
|
||||
bookMove = entry.move;
|
||||
}
|
||||
else if (score > bestScore)
|
||||
{
|
||||
bestScore = score;
|
||||
bookMove = entry.move;
|
||||
}
|
||||
// Choose book move according to its score. If a move has a very
|
||||
// high score it has higher probability to be choosen than a move
|
||||
// with lower score. Note that first entry is always chosen.
|
||||
if ( (sum && RKiss.rand<unsigned>() % sum < e.count)
|
||||
|| (pickBest && e.count == best))
|
||||
move = Move(e.move);
|
||||
}
|
||||
|
||||
if (!move)
|
||||
return MOVE_NONE;
|
||||
|
||||
// A PolyGlot book move is encoded as follows:
|
||||
//
|
||||
// bit 0- 5: destination square (from 0 to 63)
|
||||
// bit 6-11: origin square (from 0 to 63)
|
||||
// bit 12-13-14: promotion piece (from KNIGHT == 1 to QUEEN == 4)
|
||||
// bit 12-14: promotion piece (from KNIGHT == 1 to QUEEN == 4)
|
||||
//
|
||||
// Castling moves follow "king captures rook" representation. So in case
|
||||
// book move is a promotion we have to convert to our representation, in
|
||||
// all other cases we can directly compare with a Move after having
|
||||
// masked out special Move's flags that are not supported by PolyGlot.
|
||||
int p = (bookMove >> 12) & 7;
|
||||
// Castling moves follow "king captures rook" representation. So in case book
|
||||
// move is a promotion we have to convert to our representation, in all the
|
||||
// other cases we can directly compare with a Move after having masked out
|
||||
// the special Move's flags (bit 14-15) that are not supported by PolyGlot.
|
||||
int pt = (move >> 12) & 7;
|
||||
if (pt)
|
||||
move = make<PROMOTION>(from_sq(move), to_sq(move), PieceType(pt + 1));
|
||||
|
||||
if (p)
|
||||
bookMove = int(make_promotion_move(move_from(Move(bookMove)),
|
||||
move_to(Move(bookMove)), PieceType(p + 1)));
|
||||
|
||||
// Verify the book move (if any) is legal
|
||||
MoveStack mlist[MAX_MOVES];
|
||||
MoveStack* last = generate<MV_LEGAL>(pos, mlist);
|
||||
for (MoveStack* cur = mlist; cur != last; cur++)
|
||||
if ((int(cur->move) & ~(3 << 14)) == bookMove) // Mask out special flags
|
||||
return cur->move;
|
||||
// Add 'special move' flags and verify it is legal
|
||||
for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
|
||||
if (move == (ml.move() & 0x3FFF))
|
||||
return ml.move();
|
||||
|
||||
return MOVE_NONE;
|
||||
}
|
||||
|
||||
|
||||
/// Book::find_entry() takes a book key as input, and does a binary search
|
||||
/// through the book file for the given key. The index to the first book
|
||||
/// entry with the same key as the input is returned. When the key is not
|
||||
/// found in the book file, bookSize is returned.
|
||||
/// find_first() takes a book key as input, and does a binary search through
|
||||
/// the book file for the given key. Returns the index of the leftmost book
|
||||
/// entry with the same key as the input.
|
||||
|
||||
int Book::find_entry(uint64_t key) {
|
||||
size_t PolyglotBook::find_first(uint64_t key) {
|
||||
|
||||
int left, right, mid;
|
||||
|
||||
// Binary search (finds the leftmost entry)
|
||||
left = 0;
|
||||
right = bookSize - 1;
|
||||
|
||||
assert(left <= right);
|
||||
|
||||
while (left < right)
|
||||
{
|
||||
mid = (left + right) / 2;
|
||||
|
||||
assert(mid >= left && mid < right);
|
||||
|
||||
if (key <= read_entry(mid).key)
|
||||
right = mid;
|
||||
else
|
||||
left = mid + 1;
|
||||
}
|
||||
|
||||
assert(left == right);
|
||||
|
||||
return read_entry(left).key == key ? left : bookSize;
|
||||
}
|
||||
|
||||
|
||||
/// Book::get_number() reads sizeof(T) chars from the file's binary byte
|
||||
/// stream and converts them in a number of type T.
|
||||
template<typename T>
|
||||
void Book::get_number(T& n) {
|
||||
|
||||
n = 0;
|
||||
|
||||
for (size_t i = 0; i < sizeof(T); i++)
|
||||
n = (n << 8) + (T)bookFile.get();
|
||||
}
|
||||
|
||||
|
||||
/// Book::read_entry() takes an integer index, and returns the BookEntry
|
||||
/// at the given index in the book file.
|
||||
|
||||
BookEntry Book::read_entry(int idx) {
|
||||
|
||||
assert(idx >= 0 && idx < bookSize);
|
||||
assert(bookFile.is_open());
|
||||
seekg(0, ios::end); // Move pointer to end, so tellg() gets file's size
|
||||
|
||||
size_t low = 0, mid, high = (size_t)tellg() / sizeof(BookEntry) - 1;
|
||||
BookEntry e;
|
||||
|
||||
bookFile.seekg(idx * sizeof(BookEntry), ios_base::beg);
|
||||
assert(low <= high);
|
||||
|
||||
get_number(e.key);
|
||||
get_number(e.move);
|
||||
get_number(e.count);
|
||||
get_number(e.learn);
|
||||
|
||||
if (!bookFile.good())
|
||||
while (low < high && good())
|
||||
{
|
||||
cerr << "Failed to read book entry at index " << idx << endl;
|
||||
exit(EXIT_FAILURE);
|
||||
mid = (low + high) / 2;
|
||||
|
||||
assert(mid >= low && mid < high);
|
||||
|
||||
seekg(mid * sizeof(BookEntry), ios_base::beg);
|
||||
*this >> e;
|
||||
|
||||
if (key <= e.key)
|
||||
high = mid;
|
||||
else
|
||||
low = mid + 1;
|
||||
}
|
||||
return e;
|
||||
|
||||
assert(low == high);
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
35
src/book.h
35
src/book.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -23,40 +23,23 @@
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#include "move.h"
|
||||
#include "position.h"
|
||||
#include "rkiss.h"
|
||||
|
||||
|
||||
// A Polyglot book is a series of "entries" of 16 bytes. All integers are
|
||||
// stored highest byte first (regardless of size). The entries are ordered
|
||||
// according to key. Lowest key first.
|
||||
struct BookEntry {
|
||||
uint64_t key;
|
||||
uint16_t move;
|
||||
uint16_t count;
|
||||
uint32_t learn;
|
||||
};
|
||||
|
||||
class Book {
|
||||
class PolyglotBook : private std::ifstream {
|
||||
public:
|
||||
Book();
|
||||
~Book();
|
||||
void open(const std::string& fileName);
|
||||
void close();
|
||||
Move get_move(const Position& pos, bool findBestMove);
|
||||
const std::string name() const { return bookName; }
|
||||
PolyglotBook();
|
||||
~PolyglotBook();
|
||||
Move probe(const Position& pos, const std::string& fName, bool pickBest);
|
||||
|
||||
private:
|
||||
template<typename T> void get_number(T& n);
|
||||
template<typename T> PolyglotBook& operator>>(T& n);
|
||||
|
||||
BookEntry read_entry(int idx);
|
||||
int find_entry(uint64_t key);
|
||||
bool open(const char* fName);
|
||||
size_t find_first(uint64_t key);
|
||||
|
||||
std::ifstream bookFile;
|
||||
std::string bookName;
|
||||
int bookSize;
|
||||
RKISS RKiss;
|
||||
std::string fileName;
|
||||
};
|
||||
|
||||
#endif // !defined(BOOK_H_INCLUDED)
|
||||
|
||||
609
src/endgame.cpp
609
src/endgame.cpp
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,8 +20,8 @@
|
||||
#if !defined(ENDGAME_H_INCLUDED)
|
||||
#define ENDGAME_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include "position.h"
|
||||
#include "types.h"
|
||||
@@ -46,6 +46,7 @@ enum EndgameType {
|
||||
|
||||
|
||||
// Scaling functions
|
||||
SCALE_FUNS,
|
||||
|
||||
KBPsK, // KB+pawns vs K
|
||||
KQKRPs, // KQ vs KR+pawns
|
||||
@@ -60,25 +61,31 @@ enum EndgameType {
|
||||
};
|
||||
|
||||
|
||||
/// Endgame functions can be of two types according if return a Value or a
|
||||
/// ScaleFactor. Type eg_fun<int>::type equals to either ScaleFactor or Value
|
||||
/// depending if the template parameter is 0 or 1.
|
||||
|
||||
template<int> struct eg_fun { typedef Value type; };
|
||||
template<> struct eg_fun<1> { typedef ScaleFactor type; };
|
||||
|
||||
|
||||
/// Base and derived templates for endgame evaluation and scaling functions
|
||||
|
||||
template<typename T>
|
||||
struct EndgameBase {
|
||||
|
||||
typedef EndgameBase<T> Base;
|
||||
|
||||
virtual ~EndgameBase() {}
|
||||
virtual Color color() const = 0;
|
||||
virtual T apply(const Position&) const = 0;
|
||||
virtual T operator()(const Position&) const = 0;
|
||||
};
|
||||
|
||||
|
||||
template<typename T, EndgameType>
|
||||
template<EndgameType E, typename T = typename eg_fun<(E > SCALE_FUNS)>::type>
|
||||
struct Endgame : public EndgameBase<T> {
|
||||
|
||||
explicit Endgame(Color c) : strongerSide(c), weakerSide(opposite_color(c)) {}
|
||||
explicit Endgame(Color c) : strongerSide(c), weakerSide(~c) {}
|
||||
Color color() const { return strongerSide; }
|
||||
T apply(const Position&) const;
|
||||
T operator()(const Position&) const;
|
||||
|
||||
private:
|
||||
Color strongerSide, weakerSide;
|
||||
@@ -87,26 +94,27 @@ private:
|
||||
|
||||
/// Endgames class stores in two std::map the pointers to endgame evaluation
|
||||
/// and scaling base objects. Then we use polymorphism to invoke the actual
|
||||
/// endgame function calling its apply() method that is virtual.
|
||||
/// endgame function calling its operator() that is virtual.
|
||||
|
||||
class Endgames {
|
||||
|
||||
typedef std::map<Key, EndgameBase<Value>* > EFMap;
|
||||
typedef std::map<Key, EndgameBase<ScaleFactor>* > SFMap;
|
||||
typedef std::map<Key, EndgameBase<eg_fun<0>::type>*> M1;
|
||||
typedef std::map<Key, EndgameBase<eg_fun<1>::type>*> M2;
|
||||
|
||||
M1 m1;
|
||||
M2 m2;
|
||||
|
||||
M1& map(M1::mapped_type) { return m1; }
|
||||
M2& map(M2::mapped_type) { return m2; }
|
||||
|
||||
template<EndgameType E> void add(const std::string& code);
|
||||
|
||||
public:
|
||||
Endgames();
|
||||
~Endgames();
|
||||
template<class T> T* get(Key key) const;
|
||||
|
||||
private:
|
||||
template<class T> void add(const std::string& keyCode);
|
||||
|
||||
// Here we store two maps, for evaluate and scaling functions...
|
||||
std::pair<EFMap, SFMap> maps;
|
||||
|
||||
// ...and here is the accessing template function
|
||||
template<typename T> const std::map<Key, T*>& get() const;
|
||||
template<typename T> T probe(Key key, T& eg)
|
||||
{ return eg = map(eg).count(key) ? map(eg)[key] : NULL; }
|
||||
};
|
||||
|
||||
#endif // !defined(ENDGAME_H_INCLUDED)
|
||||
|
||||
1868
src/evaluate.cpp
1868
src/evaluate.cpp
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -24,8 +24,14 @@
|
||||
|
||||
class Position;
|
||||
|
||||
namespace Eval {
|
||||
|
||||
extern Color RootColor;
|
||||
|
||||
extern void init();
|
||||
extern Value evaluate(const Position& pos, Value& margin);
|
||||
extern std::string trace_evaluate(const Position& pos);
|
||||
extern void read_evaluation_uci_options(Color sideToMove);
|
||||
extern std::string trace(const Position& pos);
|
||||
|
||||
}
|
||||
|
||||
#endif // !defined(EVALUATE_H_INCLUDED)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,7 +20,9 @@
|
||||
#if !defined(HISTORY_H_INCLUDED)
|
||||
#define HISTORY_H_INCLUDED
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
/// The History class stores statistics about how often different moves
|
||||
@@ -35,7 +37,7 @@ class History {
|
||||
public:
|
||||
void clear();
|
||||
Value value(Piece p, Square to) const;
|
||||
void update(Piece p, Square to, Value bonus);
|
||||
void add(Piece p, Square to, Value bonus);
|
||||
Value gain(Piece p, Square to) const;
|
||||
void update_gain(Piece p, Square to, Value g);
|
||||
|
||||
@@ -55,7 +57,7 @@ inline Value History::value(Piece p, Square to) const {
|
||||
return history[p][to];
|
||||
}
|
||||
|
||||
inline void History::update(Piece p, Square to, Value bonus) {
|
||||
inline void History::add(Piece p, Square to, Value bonus) {
|
||||
if (abs(history[p][to] + bonus) < MaxValue) history[p][to] += bonus;
|
||||
}
|
||||
|
||||
@@ -64,7 +66,7 @@ inline Value History::gain(Piece p, Square to) const {
|
||||
}
|
||||
|
||||
inline void History::update_gain(Piece p, Square to, Value g) {
|
||||
maxGains[p][to] = Max(g, maxGains[p][to] - 1);
|
||||
maxGains[p][to] = std::max(g, maxGains[p][to] - 1);
|
||||
}
|
||||
|
||||
#endif // !defined(HISTORY_H_INCLUDED)
|
||||
|
||||
79
src/lock.h
79
src/lock.h
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#if !defined(LOCK_H_INCLUDED)
|
||||
#define LOCK_H_INCLUDED
|
||||
|
||||
#if !defined(_MSC_VER)
|
||||
|
||||
# include <pthread.h>
|
||||
|
||||
typedef pthread_mutex_t Lock;
|
||||
typedef pthread_cond_t WaitCondition;
|
||||
|
||||
# define lock_init(x) pthread_mutex_init(x, NULL)
|
||||
# define lock_grab(x) pthread_mutex_lock(x)
|
||||
# define lock_release(x) pthread_mutex_unlock(x)
|
||||
# define lock_destroy(x) pthread_mutex_destroy(x)
|
||||
# define cond_destroy(x) pthread_cond_destroy(x)
|
||||
# define cond_init(x) pthread_cond_init(x, NULL)
|
||||
# define cond_signal(x) pthread_cond_signal(x)
|
||||
# define cond_wait(x,y) pthread_cond_wait(x,y)
|
||||
|
||||
#else
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
|
||||
// Default fast and race free locks and condition variables
|
||||
#if !defined(OLD_LOCKS)
|
||||
|
||||
typedef SRWLOCK Lock;
|
||||
typedef CONDITION_VARIABLE WaitCondition;
|
||||
|
||||
# define lock_init(x) InitializeSRWLock(x)
|
||||
# define lock_grab(x) AcquireSRWLockExclusive(x)
|
||||
# define lock_release(x) ReleaseSRWLockExclusive(x)
|
||||
# define lock_destroy(x) (x)
|
||||
# define cond_destroy(x) (x)
|
||||
# define cond_init(x) InitializeConditionVariable(x)
|
||||
# define cond_signal(x) WakeConditionVariable(x)
|
||||
# define cond_wait(x,y) SleepConditionVariableSRW(x, y, INFINITE,0)
|
||||
|
||||
// Fallback solution to build for Windows XP and older versions, note that
|
||||
// cond_wait() is racy between lock_release() and WaitForSingleObject().
|
||||
#else
|
||||
|
||||
typedef CRITICAL_SECTION Lock;
|
||||
typedef HANDLE WaitCondition;
|
||||
|
||||
# define lock_init(x) InitializeCriticalSection(x)
|
||||
# define lock_grab(x) EnterCriticalSection(x)
|
||||
# define lock_release(x) LeaveCriticalSection(x)
|
||||
# define lock_destroy(x) DeleteCriticalSection(x)
|
||||
# define cond_init(x) { *x = CreateEvent(0, FALSE, FALSE, 0); }
|
||||
# define cond_destroy(x) CloseHandle(*x)
|
||||
# define cond_signal(x) SetEvent(*x)
|
||||
# define cond_wait(x,y) { lock_release(y); WaitForSingleObject(*x, INFINITE); lock_grab(y); }
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#endif // !defined(LOCK_H_INCLUDED)
|
||||
65
src/main.cpp
65
src/main.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,71 +17,36 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// To profile with callgrind uncomment following line
|
||||
//#define USE_CALLGRIND
|
||||
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "evaluate.h"
|
||||
#include "position.h"
|
||||
#include "thread.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "ucioption.h"
|
||||
|
||||
#ifdef USE_CALLGRIND
|
||||
#include <valgrind/callgrind.h>
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
|
||||
extern bool execute_uci_command(const string& cmd);
|
||||
extern void benchmark(int argc, char* argv[]);
|
||||
extern void init_kpk_bitbase();
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
|
||||
// Disable IO buffering for C and C++ standard libraries
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
cout.rdbuf()->pubsetbuf(NULL, 0);
|
||||
cin.rdbuf()->pubsetbuf(NULL, 0);
|
||||
std::cout << engine_info() << std::endl;
|
||||
|
||||
// Startup initializations
|
||||
init_bitboards();
|
||||
Position::init_zobrist();
|
||||
Position::init_piece_square_tables();
|
||||
init_kpk_bitbase();
|
||||
init_search();
|
||||
UCI::init(Options);
|
||||
Bitboards::init();
|
||||
Zobrist::init();
|
||||
Bitbases::init_kpk();
|
||||
Search::init();
|
||||
Eval::init();
|
||||
Threads.init();
|
||||
TT.set_size(Options["Hash"]);
|
||||
|
||||
#ifdef USE_CALLGRIND
|
||||
CALLGRIND_START_INSTRUMENTATION;
|
||||
#endif
|
||||
std::string args;
|
||||
|
||||
if (argc < 2)
|
||||
{
|
||||
// Print copyright notice
|
||||
cout << engine_name() << " by " << engine_authors() << endl;
|
||||
for (int i = 1; i < argc; i++)
|
||||
args += std::string(argv[i]) + " ";
|
||||
|
||||
if (CpuHasPOPCNT)
|
||||
cout << "Good! CPU has hardware POPCNT." << endl;
|
||||
|
||||
// Wait for a command from the user, and passes this command to
|
||||
// execute_uci_command() and also intercepts EOF from stdin to
|
||||
// ensure that we exit gracefully if the GUI dies unexpectedly.
|
||||
string cmd;
|
||||
while (getline(cin, cmd) && execute_uci_command(cmd)) {}
|
||||
}
|
||||
else if (string(argv[1]) == "bench" && argc < 8)
|
||||
benchmark(argc, argv);
|
||||
else
|
||||
cout << "Usage: stockfish bench [hash size = 128] [threads = 1] "
|
||||
<< "[limit = 12] [fen positions file = default] "
|
||||
<< "[limited by depth, time, nodes or perft = depth]" << endl;
|
||||
UCI::loop(args);
|
||||
|
||||
Threads.exit();
|
||||
return 0;
|
||||
}
|
||||
|
||||
135
src/material.cpp
135
src/material.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,6 +17,7 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
|
||||
@@ -49,24 +50,24 @@ namespace {
|
||||
|
||||
// Endgame evaluation and scaling functions accessed direcly and not through
|
||||
// the function maps because correspond to more then one material hash key.
|
||||
Endgame<Value, KmmKm> EvaluateKmmKm[] = { Endgame<Value, KmmKm>(WHITE), Endgame<Value, KmmKm>(BLACK) };
|
||||
Endgame<Value, KXK> EvaluateKXK[] = { Endgame<Value, KXK>(WHITE), Endgame<Value, KXK>(BLACK) };
|
||||
Endgame<KmmKm> EvaluateKmmKm[] = { Endgame<KmmKm>(WHITE), Endgame<KmmKm>(BLACK) };
|
||||
Endgame<KXK> EvaluateKXK[] = { Endgame<KXK>(WHITE), Endgame<KXK>(BLACK) };
|
||||
|
||||
Endgame<ScaleFactor, KBPsK> ScaleKBPsK[] = { Endgame<ScaleFactor, KBPsK>(WHITE), Endgame<ScaleFactor, KBPsK>(BLACK) };
|
||||
Endgame<ScaleFactor, KQKRPs> ScaleKQKRPs[] = { Endgame<ScaleFactor, KQKRPs>(WHITE), Endgame<ScaleFactor, KQKRPs>(BLACK) };
|
||||
Endgame<ScaleFactor, KPsK> ScaleKPsK[] = { Endgame<ScaleFactor, KPsK>(WHITE), Endgame<ScaleFactor, KPsK>(BLACK) };
|
||||
Endgame<ScaleFactor, KPKP> ScaleKPKP[] = { Endgame<ScaleFactor, KPKP>(WHITE), Endgame<ScaleFactor, KPKP>(BLACK) };
|
||||
Endgame<KBPsK> ScaleKBPsK[] = { Endgame<KBPsK>(WHITE), Endgame<KBPsK>(BLACK) };
|
||||
Endgame<KQKRPs> ScaleKQKRPs[] = { Endgame<KQKRPs>(WHITE), Endgame<KQKRPs>(BLACK) };
|
||||
Endgame<KPsK> ScaleKPsK[] = { Endgame<KPsK>(WHITE), Endgame<KPsK>(BLACK) };
|
||||
Endgame<KPKP> ScaleKPKP[] = { Endgame<KPKP>(WHITE), Endgame<KPKP>(BLACK) };
|
||||
|
||||
// Helper templates used to detect a given material distribution
|
||||
template<Color Us> bool is_KXK(const Position& pos) {
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
return pos.non_pawn_material(Them) == VALUE_ZERO
|
||||
&& pos.piece_count(Them, PAWN) == 0
|
||||
&& pos.non_pawn_material(Us) >= RookValueMidgame;
|
||||
&& pos.non_pawn_material(Us) >= RookValueMg;
|
||||
}
|
||||
|
||||
template<Color Us> bool is_KBPsKs(const Position& pos) {
|
||||
return pos.non_pawn_material(Us) == BishopValueMidgame
|
||||
return pos.non_pawn_material(Us) == BishopValueMg
|
||||
&& pos.piece_count(Us, BISHOP) == 1
|
||||
&& pos.piece_count(Us, PAWN) >= 1;
|
||||
}
|
||||
@@ -74,7 +75,7 @@ namespace {
|
||||
template<Color Us> bool is_KQKRPs(const Position& pos) {
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
return pos.piece_count(Us, PAWN) == 0
|
||||
&& pos.non_pawn_material(Us) == QueenValueMidgame
|
||||
&& pos.non_pawn_material(Us) == QueenValueMg
|
||||
&& pos.piece_count(Us, QUEEN) == 1
|
||||
&& pos.piece_count(Them, ROOK) == 1
|
||||
&& pos.piece_count(Them, PAWN) >= 1;
|
||||
@@ -83,67 +84,57 @@ namespace {
|
||||
} // namespace
|
||||
|
||||
|
||||
/// MaterialInfoTable c'tor and d'tor allocate and free the space for Endgames
|
||||
/// MaterialTable::probe() takes a position object as input, looks up a MaterialEntry
|
||||
/// object, and returns a pointer to it. If the material configuration is not
|
||||
/// already present in the table, it is computed and stored there, so we don't
|
||||
/// have to recompute everything when the same material configuration occurs again.
|
||||
|
||||
void MaterialInfoTable::init() { Base::init(); if (!funcs) funcs = new Endgames(); }
|
||||
MaterialInfoTable::~MaterialInfoTable() { delete funcs; }
|
||||
MaterialEntry* MaterialTable::probe(const Position& pos) {
|
||||
|
||||
Key key = pos.material_key();
|
||||
MaterialEntry* e = entries[key];
|
||||
|
||||
/// MaterialInfoTable::get_material_info() takes a position object as input,
|
||||
/// computes or looks up a MaterialInfo object, and returns a pointer to it.
|
||||
/// If the material configuration is not already present in the table, it
|
||||
/// is stored there, so we don't have to recompute everything when the
|
||||
/// same material configuration occurs again.
|
||||
|
||||
MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) const {
|
||||
|
||||
Key key = pos.get_material_key();
|
||||
MaterialInfo* mi = probe(key);
|
||||
|
||||
// If mi->key matches the position's material hash key, it means that we
|
||||
// If e->key matches the position's material hash key, it means that we
|
||||
// have analysed this material configuration before, and we can simply
|
||||
// return the information we found the last time instead of recomputing it.
|
||||
if (mi->key == key)
|
||||
return mi;
|
||||
if (e->key == key)
|
||||
return e;
|
||||
|
||||
// Initialize MaterialInfo entry
|
||||
memset(mi, 0, sizeof(MaterialInfo));
|
||||
mi->key = key;
|
||||
mi->factor[WHITE] = mi->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
|
||||
|
||||
// Store game phase
|
||||
mi->gamePhase = MaterialInfoTable::game_phase(pos);
|
||||
memset(e, 0, sizeof(MaterialEntry));
|
||||
e->key = key;
|
||||
e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
|
||||
e->gamePhase = MaterialTable::game_phase(pos);
|
||||
|
||||
// Let's look if we have a specialized evaluation function for this
|
||||
// particular material configuration. First we look for a fixed
|
||||
// configuration one, then a generic one if previous search failed.
|
||||
if ((mi->evaluationFunction = funcs->get<EndgameBase<Value> >(key)) != NULL)
|
||||
return mi;
|
||||
if (endgames.probe(key, e->evaluationFunction))
|
||||
return e;
|
||||
|
||||
if (is_KXK<WHITE>(pos))
|
||||
{
|
||||
mi->evaluationFunction = &EvaluateKXK[WHITE];
|
||||
return mi;
|
||||
e->evaluationFunction = &EvaluateKXK[WHITE];
|
||||
return e;
|
||||
}
|
||||
|
||||
if (is_KXK<BLACK>(pos))
|
||||
{
|
||||
mi->evaluationFunction = &EvaluateKXK[BLACK];
|
||||
return mi;
|
||||
e->evaluationFunction = &EvaluateKXK[BLACK];
|
||||
return e;
|
||||
}
|
||||
|
||||
if (!pos.pieces(PAWN) && !pos.pieces(ROOK) && !pos.pieces(QUEEN))
|
||||
{
|
||||
// Minor piece endgame with at least one minor piece per side and
|
||||
// no pawns. Note that the case KmmK is already handled by KXK.
|
||||
assert((pos.pieces(KNIGHT, WHITE) | pos.pieces(BISHOP, WHITE)));
|
||||
assert((pos.pieces(KNIGHT, BLACK) | pos.pieces(BISHOP, BLACK)));
|
||||
assert((pos.pieces(WHITE, KNIGHT) | pos.pieces(WHITE, BISHOP)));
|
||||
assert((pos.pieces(BLACK, KNIGHT) | pos.pieces(BLACK, BISHOP)));
|
||||
|
||||
if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
|
||||
&& pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
|
||||
{
|
||||
mi->evaluationFunction = &EvaluateKmmKm[WHITE];
|
||||
return mi;
|
||||
e->evaluationFunction = &EvaluateKmmKm[pos.side_to_move()];
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,26 +145,26 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) const {
|
||||
// scaling functions and we need to decide which one to use.
|
||||
EndgameBase<ScaleFactor>* sf;
|
||||
|
||||
if ((sf = funcs->get<EndgameBase<ScaleFactor> >(key)) != NULL)
|
||||
if (endgames.probe(key, sf))
|
||||
{
|
||||
mi->scalingFunction[sf->color()] = sf;
|
||||
return mi;
|
||||
e->scalingFunction[sf->color()] = sf;
|
||||
return e;
|
||||
}
|
||||
|
||||
// Generic scaling functions that refer to more then one material
|
||||
// distribution. Should be probed after the specialized ones.
|
||||
// Note that these ones don't return after setting the function.
|
||||
if (is_KBPsKs<WHITE>(pos))
|
||||
mi->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
|
||||
e->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
|
||||
|
||||
if (is_KBPsKs<BLACK>(pos))
|
||||
mi->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
|
||||
e->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
|
||||
|
||||
if (is_KQKRPs<WHITE>(pos))
|
||||
mi->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
|
||||
e->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
|
||||
|
||||
else if (is_KQKRPs<BLACK>(pos))
|
||||
mi->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
|
||||
e->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
|
||||
|
||||
Value npm_w = pos.non_pawn_material(WHITE);
|
||||
Value npm_b = pos.non_pawn_material(BLACK);
|
||||
@@ -183,42 +174,42 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) const {
|
||||
if (pos.piece_count(BLACK, PAWN) == 0)
|
||||
{
|
||||
assert(pos.piece_count(WHITE, PAWN) >= 2);
|
||||
mi->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
|
||||
e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
|
||||
}
|
||||
else if (pos.piece_count(WHITE, PAWN) == 0)
|
||||
{
|
||||
assert(pos.piece_count(BLACK, PAWN) >= 2);
|
||||
mi->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
|
||||
e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
|
||||
}
|
||||
else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
|
||||
{
|
||||
// This is a special case because we set scaling functions
|
||||
// for both colors instead of only one.
|
||||
mi->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
|
||||
mi->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
|
||||
e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
|
||||
e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
|
||||
}
|
||||
}
|
||||
|
||||
// No pawns makes it difficult to win, even with a material advantage
|
||||
if (pos.piece_count(WHITE, PAWN) == 0 && npm_w - npm_b <= BishopValueMidgame)
|
||||
if (pos.piece_count(WHITE, PAWN) == 0 && npm_w - npm_b <= BishopValueMg)
|
||||
{
|
||||
mi->factor[WHITE] = uint8_t
|
||||
(npm_w == npm_b || npm_w < RookValueMidgame ? 0 : NoPawnsSF[Min(pos.piece_count(WHITE, BISHOP), 2)]);
|
||||
e->factor[WHITE] = (uint8_t)
|
||||
(npm_w == npm_b || npm_w < RookValueMg ? 0 : NoPawnsSF[std::min(pos.piece_count(WHITE, BISHOP), 2)]);
|
||||
}
|
||||
|
||||
if (pos.piece_count(BLACK, PAWN) == 0 && npm_b - npm_w <= BishopValueMidgame)
|
||||
if (pos.piece_count(BLACK, PAWN) == 0 && npm_b - npm_w <= BishopValueMg)
|
||||
{
|
||||
mi->factor[BLACK] = uint8_t
|
||||
(npm_w == npm_b || npm_b < RookValueMidgame ? 0 : NoPawnsSF[Min(pos.piece_count(BLACK, BISHOP), 2)]);
|
||||
e->factor[BLACK] = (uint8_t)
|
||||
(npm_w == npm_b || npm_b < RookValueMg ? 0 : NoPawnsSF[std::min(pos.piece_count(BLACK, BISHOP), 2)]);
|
||||
}
|
||||
|
||||
// Compute the space weight
|
||||
if (npm_w + npm_b >= 2 * QueenValueMidgame + 4 * RookValueMidgame + 2 * KnightValueMidgame)
|
||||
if (npm_w + npm_b >= 2 * QueenValueMg + 4 * RookValueMg + 2 * KnightValueMg)
|
||||
{
|
||||
int minorPieceCount = pos.piece_count(WHITE, KNIGHT) + pos.piece_count(WHITE, BISHOP)
|
||||
+ pos.piece_count(BLACK, KNIGHT) + pos.piece_count(BLACK, BISHOP);
|
||||
|
||||
mi->spaceWeight = minorPieceCount * minorPieceCount;
|
||||
e->spaceWeight = minorPieceCount * minorPieceCount;
|
||||
}
|
||||
|
||||
// Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
|
||||
@@ -230,16 +221,16 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) const {
|
||||
{ pos.piece_count(BLACK, BISHOP) > 1, pos.piece_count(BLACK, PAWN), pos.piece_count(BLACK, KNIGHT),
|
||||
pos.piece_count(BLACK, BISHOP) , pos.piece_count(BLACK, ROOK), pos.piece_count(BLACK, QUEEN) } };
|
||||
|
||||
mi->value = int16_t((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
|
||||
return mi;
|
||||
e->value = (int16_t)((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
|
||||
return e;
|
||||
}
|
||||
|
||||
|
||||
/// MaterialInfoTable::imbalance() calculates imbalance comparing piece count of each
|
||||
/// MaterialTable::imbalance() calculates imbalance comparing piece count of each
|
||||
/// piece type for both colors.
|
||||
|
||||
template<Color Us>
|
||||
int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
||||
int MaterialTable::imbalance(const int pieceCount[][8]) {
|
||||
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
|
||||
@@ -253,7 +244,7 @@ int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
||||
+ RedundantQueenPenalty * pieceCount[Us][QUEEN];
|
||||
|
||||
// Second-degree polynomial material imbalance by Tord Romstad
|
||||
for (pt1 = PIECE_TYPE_NONE; pt1 <= QUEEN; pt1++)
|
||||
for (pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
|
||||
{
|
||||
pc = pieceCount[Us][pt1];
|
||||
if (!pc)
|
||||
@@ -261,7 +252,7 @@ int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
||||
|
||||
v = LinearCoefficients[pt1];
|
||||
|
||||
for (pt2 = PIECE_TYPE_NONE; pt2 <= pt1; pt2++)
|
||||
for (pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
|
||||
v += QuadraticCoefficientsSameColor[pt1][pt2] * pieceCount[Us][pt2]
|
||||
+ QuadraticCoefficientsOppositeColor[pt1][pt2] * pieceCount[Them][pt2];
|
||||
|
||||
@@ -271,11 +262,11 @@ int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
||||
}
|
||||
|
||||
|
||||
/// MaterialInfoTable::game_phase() calculates the phase given the current
|
||||
/// MaterialTable::game_phase() calculates the phase given the current
|
||||
/// position. Because the phase is strictly a function of the material, it
|
||||
/// is stored in MaterialInfo.
|
||||
/// is stored in MaterialEntry.
|
||||
|
||||
Phase MaterialInfoTable::game_phase(const Position& pos) {
|
||||
Phase MaterialTable::game_phase(const Position& pos) {
|
||||
|
||||
Value npm = pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -21,13 +21,20 @@
|
||||
#define MATERIAL_H_INCLUDED
|
||||
|
||||
#include "endgame.h"
|
||||
#include "misc.h"
|
||||
#include "position.h"
|
||||
#include "tt.h"
|
||||
#include "types.h"
|
||||
|
||||
const int MaterialTableSize = 8192;
|
||||
|
||||
/// MaterialInfo is a class which contains various information about a
|
||||
/// Game phase
|
||||
enum Phase {
|
||||
PHASE_ENDGAME = 0,
|
||||
PHASE_MIDGAME = 128
|
||||
};
|
||||
|
||||
|
||||
/// MaterialEntry is a class which contains various information about a
|
||||
/// material configuration. It contains a material balance evaluation,
|
||||
/// a function pointer to a special endgame evaluation function (which in
|
||||
/// most cases is NULL, meaning that the standard evaluation function will
|
||||
@@ -37,9 +44,9 @@ const int MaterialTableSize = 8192;
|
||||
/// For instance, in KRB vs KR endgames, the score is scaled down by a factor
|
||||
/// of 4, which will result in scores of absolute value less than one pawn.
|
||||
|
||||
class MaterialInfo {
|
||||
class MaterialEntry {
|
||||
|
||||
friend class MaterialInfoTable;
|
||||
friend struct MaterialTable;
|
||||
|
||||
public:
|
||||
Score material_value() const;
|
||||
@@ -60,57 +67,53 @@ private:
|
||||
};
|
||||
|
||||
|
||||
/// The MaterialInfoTable class represents a pawn hash table. The most important
|
||||
/// method is get_material_info, which returns a pointer to a MaterialInfo object.
|
||||
/// The MaterialTable class represents a material hash table. The most important
|
||||
/// method is probe(), which returns a pointer to a MaterialEntry object.
|
||||
|
||||
class MaterialInfoTable : public SimpleHash<MaterialInfo, MaterialTableSize> {
|
||||
public:
|
||||
~MaterialInfoTable();
|
||||
void init();
|
||||
MaterialInfo* get_material_info(const Position& pos) const;
|
||||
struct MaterialTable {
|
||||
|
||||
MaterialEntry* probe(const Position& pos);
|
||||
static Phase game_phase(const Position& pos);
|
||||
template<Color Us> static int imbalance(const int pieceCount[][8]);
|
||||
|
||||
private:
|
||||
template<Color Us>
|
||||
static int imbalance(const int pieceCount[][8]);
|
||||
|
||||
Endgames* funcs;
|
||||
HashTable<MaterialEntry, MaterialTableSize> entries;
|
||||
Endgames endgames;
|
||||
};
|
||||
|
||||
|
||||
/// MaterialInfo::scale_factor takes a position and a color as input, and
|
||||
/// MaterialEntry::scale_factor takes a position and a color as input, and
|
||||
/// returns a scale factor for the given color. We have to provide the
|
||||
/// position in addition to the color, because the scale factor need not
|
||||
/// to be a constant: It can also be a function which should be applied to
|
||||
/// the position. For instance, in KBP vs K endgames, a scaling function
|
||||
/// which checks for draws with rook pawns and wrong-colored bishops.
|
||||
|
||||
inline ScaleFactor MaterialInfo::scale_factor(const Position& pos, Color c) const {
|
||||
inline ScaleFactor MaterialEntry::scale_factor(const Position& pos, Color c) const {
|
||||
|
||||
if (!scalingFunction[c])
|
||||
return ScaleFactor(factor[c]);
|
||||
|
||||
ScaleFactor sf = scalingFunction[c]->apply(pos);
|
||||
ScaleFactor sf = (*scalingFunction[c])(pos);
|
||||
return sf == SCALE_FACTOR_NONE ? ScaleFactor(factor[c]) : sf;
|
||||
}
|
||||
|
||||
inline Value MaterialInfo::evaluate(const Position& pos) const {
|
||||
return evaluationFunction->apply(pos);
|
||||
inline Value MaterialEntry::evaluate(const Position& pos) const {
|
||||
return (*evaluationFunction)(pos);
|
||||
}
|
||||
|
||||
inline Score MaterialInfo::material_value() const {
|
||||
inline Score MaterialEntry::material_value() const {
|
||||
return make_score(value, value);
|
||||
}
|
||||
|
||||
inline int MaterialInfo::space_weight() const {
|
||||
inline int MaterialEntry::space_weight() const {
|
||||
return spaceWeight;
|
||||
}
|
||||
|
||||
inline Phase MaterialInfo::game_phase() const {
|
||||
inline Phase MaterialEntry::game_phase() const {
|
||||
return gamePhase;
|
||||
}
|
||||
|
||||
inline bool MaterialInfo::specialized_eval_exists() const {
|
||||
inline bool MaterialEntry::specialized_eval_exists() const {
|
||||
return evaluationFunction != NULL;
|
||||
}
|
||||
|
||||
|
||||
304
src/misc.cpp
304
src/misc.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,154 +17,180 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#if !defined(_MSC_VER)
|
||||
|
||||
# include <sys/time.h>
|
||||
# include <sys/types.h>
|
||||
# include <unistd.h>
|
||||
# if defined(__hpux)
|
||||
# include <sys/pstat.h>
|
||||
# endif
|
||||
|
||||
#else
|
||||
|
||||
#define _CRT_SECURE_NO_DEPRECATE
|
||||
#include <windows.h>
|
||||
#include <sys/timeb.h>
|
||||
|
||||
#endif
|
||||
|
||||
#if !defined(NO_PREFETCH)
|
||||
# include <xmmintrin.h>
|
||||
#endif
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
#include "bitcount.h"
|
||||
#include "misc.h"
|
||||
#include "thread.h"
|
||||
|
||||
#if defined(__hpux)
|
||||
# include <sys/pstat.h>
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
|
||||
/// Version number. If EngineVersion is left empty, then AppTag plus
|
||||
/// current date (in the format YYMMDD) is used as a version number.
|
||||
/// Version number. If Version is left empty, then Tag plus current
|
||||
/// date (in the format YYMMDD) is used as a version number.
|
||||
|
||||
static const string AppName = "Stockfish";
|
||||
static const string EngineVersion = "2.1.1";
|
||||
static const string AppTag = "";
|
||||
static const string Version = "";
|
||||
static const string Tag = "";
|
||||
|
||||
|
||||
/// engine_name() returns the full name of the current Stockfish version.
|
||||
/// engine_info() returns the full name of the current Stockfish version.
|
||||
/// This will be either "Stockfish YYMMDD" (where YYMMDD is the date when
|
||||
/// the program was compiled) or "Stockfish <version number>", depending
|
||||
/// on whether the constant EngineVersion is empty.
|
||||
/// on whether Version is empty.
|
||||
|
||||
const string engine_name() {
|
||||
const string engine_info(bool to_uci) {
|
||||
|
||||
const string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
|
||||
const string cpu64(CpuIs64Bit ? " 64bit" : "");
|
||||
const string cpu64(Is64Bit ? " 64bit" : "");
|
||||
const string popcnt(HasPopCnt ? " SSE4.2" : "");
|
||||
|
||||
if (!EngineVersion.empty())
|
||||
return AppName + " " + EngineVersion + cpu64;
|
||||
|
||||
stringstream s, date(__DATE__); // From compiler, format is "Sep 21 2008"
|
||||
string month, day, year;
|
||||
stringstream s, date(__DATE__); // From compiler, format is "Sep 21 2008"
|
||||
|
||||
date >> month >> day >> year;
|
||||
s << "Stockfish " << Version;
|
||||
|
||||
s << setfill('0') << AppName + " " + AppTag + " "
|
||||
<< year.substr(2, 2) << setw(2)
|
||||
<< (1 + months.find(month) / 4) << setw(2)
|
||||
<< day << cpu64;
|
||||
if (Version.empty())
|
||||
{
|
||||
date >> month >> day >> year;
|
||||
|
||||
s << Tag << setfill('0') << " " << year.substr(2)
|
||||
<< setw(2) << (1 + months.find(month) / 4) << setw(2) << day;
|
||||
}
|
||||
|
||||
s << cpu64 << popcnt << (to_uci ? "\nid author ": " by ")
|
||||
<< "Tord Romstad, Marco Costalba and Joona Kiiski";
|
||||
|
||||
return s.str();
|
||||
}
|
||||
|
||||
|
||||
/// Our brave developers! Required by UCI
|
||||
/// Convert system time to milliseconds. That's all we need.
|
||||
|
||||
const string engine_authors() {
|
||||
|
||||
return "Tord Romstad, Marco Costalba and Joona Kiiski";
|
||||
Time::point Time::now() {
|
||||
sys_time_t t; system_time(&t); return time_to_msec(t);
|
||||
}
|
||||
|
||||
|
||||
/// Debug stuff. Helper functions used mainly for debugging purposes
|
||||
/// Debug functions used mainly to collect run-time statistics
|
||||
|
||||
static uint64_t dbg_hit_cnt0;
|
||||
static uint64_t dbg_hit_cnt1;
|
||||
static uint64_t dbg_mean_cnt0;
|
||||
static uint64_t dbg_mean_cnt1;
|
||||
|
||||
void dbg_print_hit_rate() {
|
||||
|
||||
if (dbg_hit_cnt0)
|
||||
cout << "Total " << dbg_hit_cnt0 << " Hit " << dbg_hit_cnt1
|
||||
<< " hit rate (%) " << 100 * dbg_hit_cnt1 / dbg_hit_cnt0 << endl;
|
||||
}
|
||||
|
||||
void dbg_print_mean() {
|
||||
|
||||
if (dbg_mean_cnt0)
|
||||
cout << "Total " << dbg_mean_cnt0 << " Mean "
|
||||
<< (float)dbg_mean_cnt1 / dbg_mean_cnt0 << endl;
|
||||
}
|
||||
|
||||
void dbg_mean_of(int v) {
|
||||
|
||||
dbg_mean_cnt0++;
|
||||
dbg_mean_cnt1 += v;
|
||||
}
|
||||
|
||||
void dbg_hit_on(bool b) {
|
||||
|
||||
dbg_hit_cnt0++;
|
||||
if (b)
|
||||
dbg_hit_cnt1++;
|
||||
}
|
||||
static uint64_t hits[2], means[2];
|
||||
|
||||
void dbg_hit_on(bool b) { hits[0]++; if (b) hits[1]++; }
|
||||
void dbg_hit_on_c(bool c, bool b) { if (c) dbg_hit_on(b); }
|
||||
void dbg_before() { dbg_hit_on(false); }
|
||||
void dbg_after() { dbg_hit_on(true); dbg_hit_cnt0--; }
|
||||
void dbg_mean_of(int v) { means[0]++; means[1] += v; }
|
||||
|
||||
void dbg_print() {
|
||||
|
||||
/// get_system_time() returns the current system time, measured in milliseconds
|
||||
if (hits[0])
|
||||
cerr << "Total " << hits[0] << " Hits " << hits[1]
|
||||
<< " hit rate (%) " << 100 * hits[1] / hits[0] << endl;
|
||||
|
||||
int get_system_time() {
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
struct _timeb t;
|
||||
_ftime(&t);
|
||||
return int(t.time * 1000 + t.millitm);
|
||||
#else
|
||||
struct timeval t;
|
||||
gettimeofday(&t, NULL);
|
||||
return t.tv_sec * 1000 + t.tv_usec / 1000;
|
||||
#endif
|
||||
if (means[0])
|
||||
cerr << "Total " << means[0] << " Mean "
|
||||
<< (float)means[1] / means[0] << endl;
|
||||
}
|
||||
|
||||
|
||||
/// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
|
||||
/// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
|
||||
/// can toggle the logging of std::cout and std:cin at runtime while preserving
|
||||
/// usual i/o functionality and without changing a single line of code!
|
||||
/// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
|
||||
|
||||
struct Tie: public streambuf { // MSVC requires splitted streambuf for cin and cout
|
||||
|
||||
Tie(streambuf* b, ofstream* f) : buf(b), file(f) {}
|
||||
|
||||
int sync() { return file->rdbuf()->pubsync(), buf->pubsync(); }
|
||||
int overflow(int c) { return log(buf->sputc((char)c), "<< "); }
|
||||
int underflow() { return buf->sgetc(); }
|
||||
int uflow() { return log(buf->sbumpc(), ">> "); }
|
||||
|
||||
streambuf* buf;
|
||||
ofstream* file;
|
||||
|
||||
int log(int c, const char* prefix) {
|
||||
|
||||
static int last = '\n';
|
||||
|
||||
if (last == '\n')
|
||||
file->rdbuf()->sputn(prefix, 3);
|
||||
|
||||
return last = file->rdbuf()->sputc((char)c);
|
||||
}
|
||||
};
|
||||
|
||||
class Logger {
|
||||
|
||||
Logger() : in(cin.rdbuf(), &file), out(cout.rdbuf(), &file) {}
|
||||
~Logger() { start(false); }
|
||||
|
||||
ofstream file;
|
||||
Tie in, out;
|
||||
|
||||
public:
|
||||
static void start(bool b) {
|
||||
|
||||
static Logger l;
|
||||
|
||||
if (b && !l.file.is_open())
|
||||
{
|
||||
l.file.open("io_log.txt", ifstream::out | ifstream::app);
|
||||
cin.rdbuf(&l.in);
|
||||
cout.rdbuf(&l.out);
|
||||
}
|
||||
else if (!b && l.file.is_open())
|
||||
{
|
||||
cout.rdbuf(l.out.buf);
|
||||
cin.rdbuf(l.in.buf);
|
||||
l.file.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/// Used to serialize access to std::cout to avoid multiple threads to write at
|
||||
/// the same time.
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, SyncCout sc) {
|
||||
|
||||
static Mutex m;
|
||||
|
||||
if (sc == io_lock)
|
||||
m.lock();
|
||||
|
||||
if (sc == io_unlock)
|
||||
m.unlock();
|
||||
|
||||
return os;
|
||||
}
|
||||
|
||||
|
||||
/// Trampoline helper to avoid moving Logger to misc.h
|
||||
void start_logger(bool b) { Logger::start(b); }
|
||||
|
||||
|
||||
/// cpu_count() tries to detect the number of CPU cores
|
||||
|
||||
int cpu_count() {
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
SYSTEM_INFO s;
|
||||
GetSystemInfo(&s);
|
||||
return Min(s.dwNumberOfProcessors, MAX_THREADS);
|
||||
return s.dwNumberOfProcessors;
|
||||
#else
|
||||
|
||||
# if defined(_SC_NPROCESSORS_ONLN)
|
||||
return Min(sysconf(_SC_NPROCESSORS_ONLN), MAX_THREADS);
|
||||
return sysconf(_SC_NPROCESSORS_ONLN);
|
||||
# elif defined(__hpux)
|
||||
struct pst_dynamic psd;
|
||||
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) == -1)
|
||||
return 1;
|
||||
return Min(psd.psd_proc_cnt, MAX_THREADS);
|
||||
return psd.psd_proc_cnt;
|
||||
# else
|
||||
return 1;
|
||||
# endif
|
||||
@@ -173,78 +199,24 @@ int cpu_count() {
|
||||
}
|
||||
|
||||
|
||||
/// Check for console input. Original code from Beowulf, Olithink and Greko
|
||||
/// timed_wait() waits for msec milliseconds. It is mainly an helper to wrap
|
||||
/// conversion from milliseconds to struct timespec, as used by pthreads.
|
||||
|
||||
#ifndef _WIN32
|
||||
|
||||
int input_available() {
|
||||
|
||||
fd_set readfds;
|
||||
struct timeval timeout;
|
||||
|
||||
FD_ZERO(&readfds);
|
||||
FD_SET(fileno(stdin), &readfds);
|
||||
timeout.tv_sec = 0; // Set to timeout immediately
|
||||
timeout.tv_usec = 0;
|
||||
select(16, &readfds, 0, 0, &timeout);
|
||||
|
||||
return (FD_ISSET(fileno(stdin), &readfds));
|
||||
}
|
||||
void timed_wait(WaitCondition& sleepCond, Lock& sleepLock, int msec) {
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
int tm = msec;
|
||||
#else
|
||||
timespec ts, *tm = &ts;
|
||||
uint64_t ms = Time::now() + msec;
|
||||
|
||||
int input_available() {
|
||||
|
||||
static HANDLE inh = NULL;
|
||||
static bool usePipe = false;
|
||||
INPUT_RECORD rec[256];
|
||||
DWORD nchars, recCnt;
|
||||
|
||||
if (!inh)
|
||||
{
|
||||
inh = GetStdHandle(STD_INPUT_HANDLE);
|
||||
if (GetConsoleMode(inh, &nchars))
|
||||
{
|
||||
SetConsoleMode(inh, nchars & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT));
|
||||
FlushConsoleInputBuffer(inh);
|
||||
} else
|
||||
usePipe = true;
|
||||
}
|
||||
|
||||
// When using Standard C input functions, also check if there
|
||||
// is anything in the buffer. After a call to such functions,
|
||||
// the input waiting in the pipe will be copied to the buffer,
|
||||
// and the call to PeekNamedPipe can indicate no input available.
|
||||
// Setting stdin to unbuffered was not enough. [from Greko]
|
||||
if (stdin->_cnt > 0)
|
||||
return 1;
|
||||
|
||||
// When running under a GUI the input commands are sent to us
|
||||
// directly over the internal pipe. If PeekNamedPipe() returns 0
|
||||
// then something went wrong. Probably the parent program exited.
|
||||
// Returning 1 will make the next call to the input function
|
||||
// return EOF, where this should be catched then.
|
||||
if (usePipe)
|
||||
return PeekNamedPipe(inh, NULL, 0, NULL, &nchars, NULL) ? nchars : 1;
|
||||
|
||||
// Count the number of unread input records, including keyboard,
|
||||
// mouse, and window-resizing input records.
|
||||
GetNumberOfConsoleInputEvents(inh, &nchars);
|
||||
|
||||
// Read data from console without removing it from the buffer
|
||||
if (nchars <= 0 || !PeekConsoleInput(inh, rec, Min(nchars, 256), &recCnt))
|
||||
return 0;
|
||||
|
||||
// Search for at least one keyboard event
|
||||
for (DWORD i = 0; i < recCnt; i++)
|
||||
if (rec[i].EventType == KEY_EVENT)
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ts.tv_sec = ms / 1000;
|
||||
ts.tv_nsec = (ms % 1000) * 1000000LL;
|
||||
#endif
|
||||
|
||||
cond_timedwait(sleepCond, sleepLock, tm);
|
||||
}
|
||||
|
||||
|
||||
/// prefetch() preloads the given address in L1/L2 cache. This is a non
|
||||
/// blocking function and do not stalls the CPU waiting for data to be
|
||||
@@ -255,13 +227,15 @@ void prefetch(char*) {}
|
||||
|
||||
#else
|
||||
|
||||
# include <xmmintrin.h>
|
||||
|
||||
void prefetch(char* addr) {
|
||||
|
||||
#if defined(__INTEL_COMPILER) || defined(__ICL)
|
||||
# if defined(__INTEL_COMPILER) || defined(__ICL)
|
||||
// This hack prevents prefetches to be optimized away by
|
||||
// Intel compiler. Both MSVC and gcc seems not affected.
|
||||
__asm__ ("");
|
||||
#endif
|
||||
# endif
|
||||
|
||||
_mm_prefetch(addr, _MM_HINT_T2);
|
||||
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
|
||||
|
||||
46
src/misc.h
46
src/misc.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,22 +20,50 @@
|
||||
#if !defined(MISC_H_INCLUDED)
|
||||
#define MISC_H_INCLUDED
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
extern const std::string engine_name();
|
||||
extern const std::string engine_authors();
|
||||
extern int get_system_time();
|
||||
extern const std::string engine_info(bool to_uci = false);
|
||||
extern int cpu_count();
|
||||
extern int input_available();
|
||||
extern void timed_wait(WaitCondition&, Lock&, int);
|
||||
extern void prefetch(char* addr);
|
||||
extern void start_logger(bool b);
|
||||
|
||||
extern void dbg_hit_on(bool b);
|
||||
extern void dbg_hit_on_c(bool c, bool b);
|
||||
extern void dbg_before();
|
||||
extern void dbg_after();
|
||||
extern void dbg_mean_of(int v);
|
||||
extern void dbg_print_hit_rate();
|
||||
extern void dbg_print_mean();
|
||||
extern void dbg_print();
|
||||
|
||||
|
||||
struct Log : public std::ofstream {
|
||||
Log(const std::string& f = "log.txt") : std::ofstream(f.c_str(), std::ios::out | std::ios::app) {}
|
||||
~Log() { if (is_open()) close(); }
|
||||
};
|
||||
|
||||
|
||||
namespace Time {
|
||||
typedef int64_t point;
|
||||
point now();
|
||||
}
|
||||
|
||||
|
||||
template<class Entry, int Size>
|
||||
struct HashTable {
|
||||
HashTable() : e(Size, Entry()) {}
|
||||
Entry* operator[](Key k) { return &e[(uint32_t)k & (Size - 1)]; }
|
||||
|
||||
private:
|
||||
std::vector<Entry> e;
|
||||
};
|
||||
|
||||
|
||||
enum SyncCout { io_lock, io_unlock };
|
||||
std::ostream& operator<<(std::ostream&, SyncCout);
|
||||
|
||||
#define sync_cout std::cout << io_lock
|
||||
#define sync_endl std::endl << io_unlock
|
||||
|
||||
#endif // !defined(MISC_H_INCLUDED)
|
||||
|
||||
258
src/move.cpp
258
src/move.cpp
@@ -1,258 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
|
||||
#include "move.h"
|
||||
#include "movegen.h"
|
||||
#include "search.h"
|
||||
|
||||
using std::string;
|
||||
|
||||
namespace {
|
||||
const string time_string(int milliseconds);
|
||||
const string score_string(Value v);
|
||||
}
|
||||
|
||||
|
||||
/// move_to_uci() converts a move to a string in coordinate notation
|
||||
/// (g1f3, a7a8q, etc.). The only special case is castling moves, where we
|
||||
/// print in the e1g1 notation in normal chess mode, and in e1h1 notation in
|
||||
/// Chess960 mode.
|
||||
|
||||
const string move_to_uci(Move m, bool chess960) {
|
||||
|
||||
Square from = move_from(m);
|
||||
Square to = move_to(m);
|
||||
string promotion;
|
||||
|
||||
if (m == MOVE_NONE)
|
||||
return "(none)";
|
||||
|
||||
if (m == MOVE_NULL)
|
||||
return "0000";
|
||||
|
||||
if (move_is_short_castle(m) && !chess960)
|
||||
return from == SQ_E1 ? "e1g1" : "e8g8";
|
||||
|
||||
if (move_is_long_castle(m) && !chess960)
|
||||
return from == SQ_E1 ? "e1c1" : "e8c8";
|
||||
|
||||
if (move_is_promotion(m))
|
||||
promotion = char(tolower(piece_type_to_char(move_promotion_piece(m))));
|
||||
|
||||
return square_to_string(from) + square_to_string(to) + promotion;
|
||||
}
|
||||
|
||||
|
||||
/// move_from_uci() takes a position and a string representing a move in
|
||||
/// simple coordinate notation and returns an equivalent Move if any.
|
||||
/// Moves are guaranteed to be legal.
|
||||
|
||||
Move move_from_uci(const Position& pos, const string& str) {
|
||||
|
||||
MoveStack mlist[MAX_MOVES];
|
||||
MoveStack* last = generate<MV_LEGAL>(pos, mlist);
|
||||
|
||||
for (MoveStack* cur = mlist; cur != last; cur++)
|
||||
if (str == move_to_uci(cur->move, pos.is_chess960()))
|
||||
return cur->move;
|
||||
|
||||
return MOVE_NONE;
|
||||
}
|
||||
|
||||
|
||||
/// move_to_san() takes a position and a move as input, where it is assumed
|
||||
/// that the move is a legal move from the position. The return value is
|
||||
/// a string containing the move in short algebraic notation.
|
||||
|
||||
const string move_to_san(Position& pos, Move m) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
assert(move_is_ok(m));
|
||||
|
||||
MoveStack mlist[MAX_MOVES];
|
||||
Square from = move_from(m);
|
||||
Square to = move_to(m);
|
||||
PieceType pt = pos.type_of_piece_on(from);
|
||||
string san;
|
||||
|
||||
if (m == MOVE_NONE)
|
||||
return "(none)";
|
||||
|
||||
if (m == MOVE_NULL)
|
||||
return "(null)";
|
||||
|
||||
if (move_is_long_castle(m))
|
||||
san = "O-O-O";
|
||||
else if (move_is_short_castle(m))
|
||||
san = "O-O";
|
||||
else
|
||||
{
|
||||
if (pt != PAWN)
|
||||
{
|
||||
san = piece_type_to_char(pt);
|
||||
|
||||
// Collect all legal moves of piece type 'pt' with destination 'to'
|
||||
MoveStack* last = generate<MV_LEGAL>(pos, mlist);
|
||||
int f = 0, r = 0;
|
||||
|
||||
for (MoveStack* cur = mlist; cur != last; cur++)
|
||||
if ( move_to(cur->move) == to
|
||||
&& pos.type_of_piece_on(move_from(cur->move)) == pt)
|
||||
{
|
||||
if (square_file(move_from(cur->move)) == square_file(from))
|
||||
f++;
|
||||
|
||||
if (square_rank(move_from(cur->move)) == square_rank(from))
|
||||
r++;
|
||||
}
|
||||
|
||||
assert(f > 0 && r > 0);
|
||||
|
||||
// Disambiguation if we have more then one piece with destination 'to'
|
||||
if (f == 1 && r > 1)
|
||||
san += file_to_char(square_file(from));
|
||||
else if (f > 1 && r == 1)
|
||||
san += rank_to_char(square_rank(from));
|
||||
else if (f > 1 && r > 1)
|
||||
san += square_to_string(from);
|
||||
}
|
||||
|
||||
if (pos.move_is_capture(m))
|
||||
{
|
||||
if (pt == PAWN)
|
||||
san += file_to_char(square_file(from));
|
||||
|
||||
san += 'x';
|
||||
}
|
||||
|
||||
san += square_to_string(to);
|
||||
|
||||
if (move_is_promotion(m))
|
||||
{
|
||||
san += '=';
|
||||
san += piece_type_to_char(move_promotion_piece(m));
|
||||
}
|
||||
}
|
||||
|
||||
// The move gives check? We don't use pos.move_gives_check() here
|
||||
// because we need to test for a mate after the move is done.
|
||||
StateInfo st;
|
||||
pos.do_move(m, st);
|
||||
if (pos.in_check())
|
||||
san += pos.is_mate() ? "#" : "+";
|
||||
pos.undo_move(m);
|
||||
|
||||
return san;
|
||||
}
|
||||
|
||||
|
||||
/// pretty_pv() creates a human-readable string from a position and a PV.
|
||||
/// It is used to write search information to the log file (which is created
|
||||
/// when the UCI parameter "Use Search Log" is "true").
|
||||
|
||||
const string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]) {
|
||||
|
||||
const int64_t K = 1000;
|
||||
const int64_t M = 1000000;
|
||||
const int startColumn = 28;
|
||||
const size_t maxLength = 80 - startColumn;
|
||||
const string lf = string("\n") + string(startColumn, ' ');
|
||||
|
||||
StateInfo state[PLY_MAX_PLUS_2], *st = state;
|
||||
Move* m = pv;
|
||||
string san;
|
||||
std::stringstream s;
|
||||
size_t length = 0;
|
||||
|
||||
// First print depth, score, time and searched nodes...
|
||||
s << std::setw(2) << depth
|
||||
<< std::setw(8) << score_string(score)
|
||||
<< std::setw(8) << time_string(time);
|
||||
|
||||
if (pos.nodes_searched() < M)
|
||||
s << std::setw(8) << pos.nodes_searched() / 1 << " ";
|
||||
else if (pos.nodes_searched() < K * M)
|
||||
s << std::setw(7) << pos.nodes_searched() / K << "K ";
|
||||
else
|
||||
s << std::setw(7) << pos.nodes_searched() / M << "M ";
|
||||
|
||||
// ...then print the full PV line in short algebraic notation
|
||||
while (*m != MOVE_NONE)
|
||||
{
|
||||
san = move_to_san(pos, *m);
|
||||
length += san.length() + 1;
|
||||
|
||||
if (length > maxLength)
|
||||
{
|
||||
length = san.length() + 1;
|
||||
s << lf;
|
||||
}
|
||||
s << san << ' ';
|
||||
|
||||
pos.do_move(*m++, *st++);
|
||||
}
|
||||
|
||||
// Restore original position before to leave
|
||||
while (m != pv) pos.undo_move(*--m);
|
||||
|
||||
return s.str();
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
const string time_string(int millisecs) {
|
||||
|
||||
const int MSecMinute = 1000 * 60;
|
||||
const int MSecHour = 1000 * 60 * 60;
|
||||
|
||||
int hours = millisecs / MSecHour;
|
||||
int minutes = (millisecs % MSecHour) / MSecMinute;
|
||||
int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
|
||||
|
||||
std::stringstream s;
|
||||
|
||||
if (hours)
|
||||
s << hours << ':';
|
||||
|
||||
s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
|
||||
return s.str();
|
||||
}
|
||||
|
||||
|
||||
const string score_string(Value v) {
|
||||
|
||||
std::stringstream s;
|
||||
|
||||
if (v >= VALUE_MATE - 200)
|
||||
s << "#" << (VALUE_MATE - v + 1) / 2;
|
||||
else if (v <= -VALUE_MATE + 200)
|
||||
s << "-#" << (VALUE_MATE + v) / 2;
|
||||
else
|
||||
s << std::setprecision(2) << std::fixed << std::showpos << float(v) / PawnValueMidgame;
|
||||
|
||||
return s.str();
|
||||
}
|
||||
}
|
||||
195
src/move.h
195
src/move.h
@@ -1,195 +0,0 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#if !defined(MOVE_H_INCLUDED)
|
||||
#define MOVE_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "misc.h"
|
||||
#include "types.h"
|
||||
|
||||
// Maximum number of allowed moves per position
|
||||
const int MAX_MOVES = 256;
|
||||
|
||||
/// A move needs 16 bits to be stored
|
||||
///
|
||||
/// bit 0- 5: destination square (from 0 to 63)
|
||||
/// bit 6-11: origin square (from 0 to 63)
|
||||
/// bit 12-13: promotion piece type - 2 (from KNIGHT-2 to QUEEN-2)
|
||||
/// bit 14-15: special move flag: promotion (1), en passant (2), castle (3)
|
||||
///
|
||||
/// Special cases are MOVE_NONE and MOVE_NULL. We can sneak these in
|
||||
/// because in any normal move destination square is always different
|
||||
/// from origin square while MOVE_NONE and MOVE_NULL have the same
|
||||
/// origin and destination square, 0 and 1 respectively.
|
||||
|
||||
enum Move {
|
||||
MOVE_NONE = 0,
|
||||
MOVE_NULL = 65
|
||||
};
|
||||
|
||||
|
||||
struct MoveStack {
|
||||
Move move;
|
||||
int score;
|
||||
};
|
||||
|
||||
inline bool operator<(const MoveStack& f, const MoveStack& s) { return f.score < s.score; }
|
||||
|
||||
// An helper insertion sort implementation, works with pointers and iterators
|
||||
template<typename T, typename K>
|
||||
inline void insertion_sort(K firstMove, K lastMove)
|
||||
{
|
||||
T value;
|
||||
K cur, p, d;
|
||||
|
||||
if (firstMove != lastMove)
|
||||
for (cur = firstMove + 1; cur != lastMove; cur++)
|
||||
{
|
||||
p = d = cur;
|
||||
value = *p--;
|
||||
if (*p < value)
|
||||
{
|
||||
do *d = *p;
|
||||
while (--d != firstMove && *--p < value);
|
||||
*d = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Our dedicated sort in range [firstMove, lastMove), first splits
|
||||
// positive scores from ramining then order seaprately the two sets.
|
||||
template<typename T>
|
||||
inline void sort_moves(T* firstMove, T* lastMove, T** lastPositive)
|
||||
{
|
||||
T tmp;
|
||||
T *p, *d;
|
||||
|
||||
d = lastMove;
|
||||
p = firstMove - 1;
|
||||
|
||||
d->score = -1; // right guard
|
||||
|
||||
// Split positives vs non-positives
|
||||
do {
|
||||
while ((++p)->score > 0) {}
|
||||
|
||||
if (p != d)
|
||||
{
|
||||
while (--d != p && d->score <= 0) {}
|
||||
|
||||
tmp = *p;
|
||||
*p = *d;
|
||||
*d = tmp;
|
||||
}
|
||||
|
||||
} while (p != d);
|
||||
|
||||
// Sort just positive scored moves, remaining only when we get there
|
||||
insertion_sort<T, T*>(firstMove, p);
|
||||
*lastPositive = p;
|
||||
}
|
||||
|
||||
// Picks up the best move in range [curMove, lastMove), one per cycle.
|
||||
// It is faster then sorting all the moves in advance when moves are few,
|
||||
// as normally are the possible captures. Note that is not a stable alghoritm.
|
||||
template<typename T>
|
||||
inline T pick_best(T* curMove, T* lastMove)
|
||||
{
|
||||
T bestMove, tmp;
|
||||
|
||||
bestMove = *curMove;
|
||||
while (++curMove != lastMove)
|
||||
{
|
||||
if (bestMove < *curMove)
|
||||
{
|
||||
tmp = *curMove;
|
||||
*curMove = bestMove;
|
||||
bestMove = tmp;
|
||||
}
|
||||
}
|
||||
return bestMove;
|
||||
}
|
||||
|
||||
|
||||
inline Square move_from(Move m) {
|
||||
return Square((int(m) >> 6) & 0x3F);
|
||||
}
|
||||
|
||||
inline Square move_to(Move m) {
|
||||
return Square(m & 0x3F);
|
||||
}
|
||||
|
||||
inline bool move_is_special(Move m) {
|
||||
return m & (3 << 14);
|
||||
}
|
||||
|
||||
inline bool move_is_promotion(Move m) {
|
||||
return (m & (3 << 14)) == (1 << 14);
|
||||
}
|
||||
|
||||
inline int move_is_ep(Move m) {
|
||||
return (m & (3 << 14)) == (2 << 14);
|
||||
}
|
||||
|
||||
inline int move_is_castle(Move m) {
|
||||
return (m & (3 << 14)) == (3 << 14);
|
||||
}
|
||||
|
||||
inline bool move_is_short_castle(Move m) {
|
||||
return move_is_castle(m) && (move_to(m) > move_from(m));
|
||||
}
|
||||
|
||||
inline bool move_is_long_castle(Move m) {
|
||||
return move_is_castle(m) && (move_to(m) < move_from(m));
|
||||
}
|
||||
|
||||
inline PieceType move_promotion_piece(Move m) {
|
||||
return move_is_promotion(m) ? PieceType(((int(m) >> 12) & 3) + 2) : PIECE_TYPE_NONE;
|
||||
}
|
||||
|
||||
inline Move make_move(Square from, Square to) {
|
||||
return Move(int(to) | (int(from) << 6));
|
||||
}
|
||||
|
||||
inline Move make_promotion_move(Square from, Square to, PieceType promotion) {
|
||||
return Move(int(to) | (int(from) << 6) | ((int(promotion) - 2) << 12) | (1 << 14));
|
||||
}
|
||||
|
||||
inline Move make_ep_move(Square from, Square to) {
|
||||
return Move(int(to) | (int(from) << 6) | (2 << 14));
|
||||
}
|
||||
|
||||
inline Move make_castle_move(Square from, Square to) {
|
||||
return Move(int(to) | (int(from) << 6) | (3 << 14));
|
||||
}
|
||||
|
||||
inline bool move_is_ok(Move m) {
|
||||
return move_from(m) != move_to(m); // Catches also MOVE_NONE
|
||||
}
|
||||
|
||||
class Position;
|
||||
|
||||
extern const std::string move_to_uci(Move m, bool chess960);
|
||||
extern Move move_from_uci(const Position& pos, const std::string& str);
|
||||
extern const std::string move_to_san(Position& pos, Move m);
|
||||
extern const std::string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
|
||||
|
||||
#endif // !defined(MOVE_H_INCLUDED)
|
||||
731
src/movegen.cpp
731
src/movegen.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -19,524 +19,427 @@
|
||||
|
||||
#include <cassert>
|
||||
|
||||
#include "bitcount.h"
|
||||
#include "movegen.h"
|
||||
#include "position.h"
|
||||
|
||||
// Simple macro to wrap a very common while loop, no facny, no flexibility,
|
||||
// hardcoded list name 'mlist' and from square 'from'.
|
||||
#define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
|
||||
|
||||
// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
|
||||
#define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
|
||||
/// Simple macro to wrap a very common while loop, no facny, no flexibility,
|
||||
/// hardcoded names 'mlist' and 'from'.
|
||||
#define SERIALIZE(b) while (b) (*mlist++).move = make_move(from, pop_lsb(&b))
|
||||
|
||||
/// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
|
||||
#define SERIALIZE_PAWNS(b, d) while (b) { Square to = pop_lsb(&b); \
|
||||
(*mlist++).move = make_move(to - (d), to); }
|
||||
namespace {
|
||||
|
||||
enum CastlingSide {
|
||||
KING_SIDE,
|
||||
QUEEN_SIDE
|
||||
};
|
||||
template<CastlingSide Side, bool Checks, bool Chess960>
|
||||
MoveStack* generate_castle(const Position& pos, MoveStack* mlist, Color us) {
|
||||
|
||||
template<CastlingSide>
|
||||
MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
|
||||
|
||||
template<Color, MoveType>
|
||||
MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
|
||||
|
||||
template<PieceType Pt>
|
||||
inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
|
||||
|
||||
assert(Pt != QUEEN);
|
||||
|
||||
Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
|
||||
if (Pt == KING)
|
||||
{
|
||||
Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
|
||||
b &= ~QueenPseudoAttacks[ksq];
|
||||
}
|
||||
SERIALIZE_MOVES(b);
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<PieceType Pt>
|
||||
inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
|
||||
Bitboard dc, Square ksq) {
|
||||
assert(Pt != KING);
|
||||
|
||||
Bitboard checkSqs, b;
|
||||
Square from;
|
||||
const Square* ptr = pos.piece_list_begin(us, Pt);
|
||||
|
||||
if ((from = *ptr++) == SQ_NONE)
|
||||
if (pos.castle_impeded(us, Side) || !pos.can_castle(make_castle_right(us, Side)))
|
||||
return mlist;
|
||||
|
||||
checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
|
||||
// After castling, the rook and king final positions are the same in Chess960
|
||||
// as they would be in standard chess.
|
||||
Square kfrom = pos.king_square(us);
|
||||
Square rfrom = pos.castle_rook_square(us, Side);
|
||||
Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
|
||||
Bitboard enemies = pos.pieces(~us);
|
||||
|
||||
do
|
||||
{
|
||||
if ( (Pt == QUEEN && !(QueenPseudoAttacks[from] & checkSqs))
|
||||
|| (Pt == ROOK && !(RookPseudoAttacks[from] & checkSqs))
|
||||
|| (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
|
||||
continue;
|
||||
assert(!pos.in_check());
|
||||
|
||||
if (dc && bit_is_set(dc, from))
|
||||
continue;
|
||||
const int K = Chess960 ? kto > kfrom ? -1 : 1
|
||||
: Side == KING_SIDE ? -1 : 1;
|
||||
|
||||
b = pos.attacks_from<Pt>(from) & checkSqs;
|
||||
SERIALIZE_MOVES(b);
|
||||
for (Square s = kto; s != kfrom; s += (Square)K)
|
||||
if (pos.attackers_to(s) & enemies)
|
||||
return mlist;
|
||||
|
||||
} while ((from = *ptr++) != SQ_NONE);
|
||||
// Because we generate only legal castling moves we need to verify that
|
||||
// when moving the castling rook we do not discover some hidden checker.
|
||||
// For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
|
||||
if (Chess960 && (pos.attackers_to(kto, pos.pieces() ^ rfrom) & enemies))
|
||||
return mlist;
|
||||
|
||||
(*mlist++).move = make<CASTLE>(kfrom, rfrom);
|
||||
|
||||
if (Checks && !pos.move_gives_check((mlist - 1)->move, CheckInfo(pos)))
|
||||
mlist--;
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<>
|
||||
FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
|
||||
|
||||
return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
|
||||
: generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
|
||||
template<Square Delta>
|
||||
inline Bitboard move_pawns(Bitboard p) {
|
||||
|
||||
return Delta == DELTA_N ? p << 8
|
||||
: Delta == DELTA_S ? p >> 8
|
||||
: Delta == DELTA_NE ? (p & ~FileHBB) << 9
|
||||
: Delta == DELTA_SE ? (p & ~FileHBB) >> 7
|
||||
: Delta == DELTA_NW ? (p & ~FileABB) << 7
|
||||
: Delta == DELTA_SW ? (p & ~FileABB) >> 9 : 0;
|
||||
}
|
||||
|
||||
template<PieceType Pt, MoveType Type>
|
||||
FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
|
||||
|
||||
assert(Pt == PAWN);
|
||||
assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_EVASION);
|
||||
template<GenType Type, Square Delta>
|
||||
inline MoveStack* generate_promotions(MoveStack* mlist, Bitboard pawnsOn7,
|
||||
Bitboard target, const CheckInfo* ci) {
|
||||
|
||||
return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
|
||||
: generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
|
||||
}
|
||||
Bitboard b = move_pawns<Delta>(pawnsOn7) & target;
|
||||
|
||||
template<PieceType Pt>
|
||||
FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
|
||||
|
||||
Bitboard b;
|
||||
Square from;
|
||||
const Square* ptr = pos.piece_list_begin(us, Pt);
|
||||
|
||||
if (*ptr != SQ_NONE)
|
||||
while (b)
|
||||
{
|
||||
do {
|
||||
from = *ptr;
|
||||
b = pos.attacks_from<Pt>(from) & target;
|
||||
SERIALIZE_MOVES(b);
|
||||
} while (*++ptr != SQ_NONE);
|
||||
Square to = pop_lsb(&b);
|
||||
|
||||
if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
(*mlist++).move = make<PROMOTION>(to - Delta, to, QUEEN);
|
||||
|
||||
if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
{
|
||||
(*mlist++).move = make<PROMOTION>(to - Delta, to, ROOK);
|
||||
(*mlist++).move = make<PROMOTION>(to - Delta, to, BISHOP);
|
||||
(*mlist++).move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||
}
|
||||
|
||||
// Knight-promotion is the only one that can give a direct check not
|
||||
// already included in the queen-promotion.
|
||||
if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ci->ksq))
|
||||
(*mlist++).move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||
else
|
||||
(void)ci; // Silence a warning under MSVC
|
||||
}
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<>
|
||||
FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
|
||||
|
||||
Bitboard b;
|
||||
template<Color Us, GenType Type>
|
||||
MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist,
|
||||
Bitboard target, const CheckInfo* ci) {
|
||||
|
||||
// Compute our parametrized parameters at compile time, named according to
|
||||
// the point of view of white side.
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
|
||||
const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
|
||||
const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
|
||||
const Square UP = (Us == WHITE ? DELTA_N : DELTA_S);
|
||||
const Square RIGHT = (Us == WHITE ? DELTA_NE : DELTA_SW);
|
||||
const Square LEFT = (Us == WHITE ? DELTA_NW : DELTA_SE);
|
||||
|
||||
Bitboard b1, b2, dc1, dc2, emptySquares;
|
||||
|
||||
Bitboard pawnsOn7 = pos.pieces(Us, PAWN) & TRank7BB;
|
||||
Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
|
||||
|
||||
Bitboard enemies = (Type == EVASIONS ? pos.pieces(Them) & target:
|
||||
Type == CAPTURES ? target : pos.pieces(Them));
|
||||
|
||||
// Single and double pawn pushes, no promotions
|
||||
if (Type != CAPTURES)
|
||||
{
|
||||
emptySquares = (Type == QUIETS || Type == QUIET_CHECKS ? target : ~pos.pieces());
|
||||
|
||||
b1 = move_pawns<UP>(pawnsNotOn7) & emptySquares;
|
||||
b2 = move_pawns<UP>(b1 & TRank3BB) & emptySquares;
|
||||
|
||||
if (Type == EVASIONS) // Consider only blocking squares
|
||||
{
|
||||
b1 &= target;
|
||||
b2 &= target;
|
||||
}
|
||||
|
||||
if (Type == QUIET_CHECKS)
|
||||
{
|
||||
b1 &= pos.attacks_from<PAWN>(ci->ksq, Them);
|
||||
b2 &= pos.attacks_from<PAWN>(ci->ksq, Them);
|
||||
|
||||
// Add pawn pushes which give discovered check. This is possible only
|
||||
// if the pawn is not on the same file as the enemy king, because we
|
||||
// don't generate captures. Note that a possible discovery check
|
||||
// promotion has been already generated among captures.
|
||||
if (pawnsNotOn7 & ci->dcCandidates)
|
||||
{
|
||||
dc1 = move_pawns<UP>(pawnsNotOn7 & ci->dcCandidates) & emptySquares & ~file_bb(ci->ksq);
|
||||
dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
|
||||
|
||||
b1 |= dc1;
|
||||
b2 |= dc2;
|
||||
}
|
||||
}
|
||||
|
||||
SERIALIZE_PAWNS(b1, UP);
|
||||
SERIALIZE_PAWNS(b2, UP + UP);
|
||||
}
|
||||
|
||||
// Promotions and underpromotions
|
||||
if (pawnsOn7 && (Type != EVASIONS || (target & TRank8BB)))
|
||||
{
|
||||
if (Type == CAPTURES)
|
||||
emptySquares = ~pos.pieces();
|
||||
|
||||
if (Type == EVASIONS)
|
||||
emptySquares &= target;
|
||||
|
||||
mlist = generate_promotions<Type, RIGHT>(mlist, pawnsOn7, enemies, ci);
|
||||
mlist = generate_promotions<Type, LEFT>(mlist, pawnsOn7, enemies, ci);
|
||||
mlist = generate_promotions<Type, UP>(mlist, pawnsOn7, emptySquares, ci);
|
||||
}
|
||||
|
||||
// Standard and en-passant captures
|
||||
if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
||||
{
|
||||
b1 = move_pawns<RIGHT>(pawnsNotOn7) & enemies;
|
||||
b2 = move_pawns<LEFT >(pawnsNotOn7) & enemies;
|
||||
|
||||
SERIALIZE_PAWNS(b1, RIGHT);
|
||||
SERIALIZE_PAWNS(b2, LEFT);
|
||||
|
||||
if (pos.ep_square() != SQ_NONE)
|
||||
{
|
||||
assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
|
||||
|
||||
// An en passant capture can be an evasion only if the checking piece
|
||||
// is the double pushed pawn and so is in the target. Otherwise this
|
||||
// is a discovery check and we are forced to do otherwise.
|
||||
if (Type == EVASIONS && !(target & (pos.ep_square() - UP)))
|
||||
return mlist;
|
||||
|
||||
b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
|
||||
|
||||
assert(b1);
|
||||
|
||||
while (b1)
|
||||
(*mlist++).move = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
|
||||
}
|
||||
}
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
|
||||
template<PieceType Pt, bool Checks> FORCE_INLINE
|
||||
MoveStack* generate_moves(const Position& pos, MoveStack* mlist, Color us,
|
||||
Bitboard target, const CheckInfo* ci) {
|
||||
|
||||
assert(Pt != KING && Pt != PAWN);
|
||||
|
||||
const Square* pl = pos.piece_list(us, Pt);
|
||||
|
||||
for (Square from = *pl; from != SQ_NONE; from = *++pl)
|
||||
{
|
||||
if (Checks)
|
||||
{
|
||||
if ( (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
|
||||
&& !(PseudoAttacks[Pt][from] & target & ci->checkSq[Pt]))
|
||||
continue;
|
||||
|
||||
if (ci->dcCandidates && (ci->dcCandidates & from))
|
||||
continue;
|
||||
}
|
||||
|
||||
Bitboard b = pos.attacks_from<Pt>(from) & target;
|
||||
|
||||
if (Checks)
|
||||
b &= ci->checkSq[Pt];
|
||||
|
||||
SERIALIZE(b);
|
||||
}
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
|
||||
FORCE_INLINE MoveStack* generate_king_moves(const Position& pos, MoveStack* mlist,
|
||||
Color us, Bitboard target) {
|
||||
Square from = pos.king_square(us);
|
||||
|
||||
b = pos.attacks_from<KING>(from) & target;
|
||||
SERIALIZE_MOVES(b);
|
||||
Bitboard b = pos.attacks_from<KING>(from) & target;
|
||||
SERIALIZE(b);
|
||||
return mlist;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
template<GenType Type> FORCE_INLINE
|
||||
MoveStack* generate_all_moves(const Position& pos, MoveStack* mlist, Color us,
|
||||
Bitboard target, const CheckInfo* ci = NULL) {
|
||||
|
||||
mlist = (us == WHITE ? generate_pawn_moves<WHITE, Type>(pos, mlist, target, ci)
|
||||
: generate_pawn_moves<BLACK, Type>(pos, mlist, target, ci));
|
||||
|
||||
mlist = generate_moves<KNIGHT, Type == QUIET_CHECKS>(pos, mlist, us, target, ci);
|
||||
mlist = generate_moves<BISHOP, Type == QUIET_CHECKS>(pos, mlist, us, target, ci);
|
||||
mlist = generate_moves<ROOK, Type == QUIET_CHECKS>(pos, mlist, us, target, ci);
|
||||
mlist = generate_moves<QUEEN, Type == QUIET_CHECKS>(pos, mlist, us, target, ci);
|
||||
|
||||
if (Type != QUIET_CHECKS && Type != EVASIONS)
|
||||
mlist = generate_king_moves(pos, mlist, us, target);
|
||||
|
||||
if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(us))
|
||||
{
|
||||
if (pos.is_chess960())
|
||||
{
|
||||
mlist = generate_castle<KING_SIDE, Type == QUIET_CHECKS, true>(pos, mlist, us);
|
||||
mlist = generate_castle<QUEEN_SIDE, Type == QUIET_CHECKS, true>(pos, mlist, us);
|
||||
}
|
||||
else
|
||||
{
|
||||
mlist = generate_castle<KING_SIDE, Type == QUIET_CHECKS, false>(pos, mlist, us);
|
||||
mlist = generate_castle<QUEEN_SIDE, Type == QUIET_CHECKS, false>(pos, mlist, us);
|
||||
}
|
||||
}
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
|
||||
/// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
|
||||
} // namespace
|
||||
|
||||
|
||||
/// generate<CAPTURES> generates all pseudo-legal captures and queen
|
||||
/// promotions. Returns a pointer to the end of the move list.
|
||||
///
|
||||
/// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
|
||||
/// generate<QUIETS> generates all pseudo-legal non-captures and
|
||||
/// underpromotions. Returns a pointer to the end of the move list.
|
||||
///
|
||||
/// generate<MV_NON_EVASION> generates all pseudo-legal captures and
|
||||
/// generate<NON_EVASIONS> generates all pseudo-legal captures and
|
||||
/// non-captures. Returns a pointer to the end of the move list.
|
||||
|
||||
template<MoveType Type>
|
||||
template<GenType Type>
|
||||
MoveStack* generate(const Position& pos, MoveStack* mlist) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
assert(Type == CAPTURES || Type == QUIETS || Type == NON_EVASIONS);
|
||||
assert(!pos.in_check());
|
||||
|
||||
Color us = pos.side_to_move();
|
||||
Bitboard target;
|
||||
|
||||
if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
|
||||
target = pos.pieces_of_color(opposite_color(us));
|
||||
else if (Type == MV_NON_CAPTURE)
|
||||
target = pos.empty_squares();
|
||||
else
|
||||
assert(false);
|
||||
if (Type == CAPTURES)
|
||||
target = pos.pieces(~us);
|
||||
|
||||
if (Type == MV_NON_EVASION)
|
||||
{
|
||||
mlist = generate_piece_moves<PAWN, MV_CAPTURE>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<PAWN, MV_NON_CAPTURE>(pos, mlist, us, pos.empty_squares());
|
||||
target |= pos.empty_squares();
|
||||
}
|
||||
else
|
||||
mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
|
||||
else if (Type == QUIETS)
|
||||
target = ~pos.pieces();
|
||||
|
||||
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<KING>(pos, mlist, us, target);
|
||||
else if (Type == NON_EVASIONS)
|
||||
target = ~pos.pieces(us);
|
||||
|
||||
if (Type != MV_CAPTURE)
|
||||
{
|
||||
if (pos.can_castle_kingside(us))
|
||||
mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
|
||||
|
||||
if (pos.can_castle_queenside(us))
|
||||
mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
|
||||
}
|
||||
|
||||
return mlist;
|
||||
return generate_all_moves<Type>(pos, mlist, us, target);
|
||||
}
|
||||
|
||||
// Explicit template instantiations
|
||||
template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
|
||||
template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
|
||||
template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
|
||||
template MoveStack* generate<CAPTURES>(const Position&, MoveStack*);
|
||||
template MoveStack* generate<QUIETS>(const Position&, MoveStack*);
|
||||
template MoveStack* generate<NON_EVASIONS>(const Position&, MoveStack*);
|
||||
|
||||
|
||||
/// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
|
||||
/// generate<QUIET_CHECKS> generates all pseudo-legal non-captures and knight
|
||||
/// underpromotions that give check. Returns a pointer to the end of the move list.
|
||||
template<>
|
||||
MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
|
||||
MoveStack* generate<QUIET_CHECKS>(const Position& pos, MoveStack* mlist) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
assert(!pos.in_check());
|
||||
|
||||
Bitboard b, dc;
|
||||
Square from;
|
||||
Color us = pos.side_to_move();
|
||||
Square ksq = pos.king_square(opposite_color(us));
|
||||
CheckInfo ci(pos);
|
||||
Bitboard dc = ci.dcCandidates;
|
||||
|
||||
assert(pos.piece_on(ksq) == make_piece(opposite_color(us), KING));
|
||||
|
||||
// Discovered non-capture checks
|
||||
b = dc = pos.discovered_check_candidates(us);
|
||||
|
||||
while (b)
|
||||
while (dc)
|
||||
{
|
||||
from = pop_1st_bit(&b);
|
||||
switch (pos.type_of_piece_on(from))
|
||||
{
|
||||
case PAWN: /* Will be generated togheter with pawns direct checks */ break;
|
||||
case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
|
||||
case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
|
||||
case ROOK: mlist = generate_discovered_checks<ROOK>(pos, mlist, from); break;
|
||||
case KING: mlist = generate_discovered_checks<KING>(pos, mlist, from); break;
|
||||
default: assert(false); break;
|
||||
}
|
||||
Square from = pop_lsb(&dc);
|
||||
PieceType pt = type_of(pos.piece_on(from));
|
||||
|
||||
if (pt == PAWN)
|
||||
continue; // Will be generated togheter with direct checks
|
||||
|
||||
Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
|
||||
|
||||
if (pt == KING)
|
||||
b &= ~PseudoAttacks[QUEEN][ci.ksq];
|
||||
|
||||
SERIALIZE(b);
|
||||
}
|
||||
|
||||
// Direct non-capture checks
|
||||
mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
|
||||
mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
|
||||
mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
|
||||
mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
|
||||
return generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
|
||||
return generate_all_moves<QUIET_CHECKS>(pos, mlist, us, ~pos.pieces(), &ci);
|
||||
}
|
||||
|
||||
|
||||
/// generate_evasions() generates all pseudo-legal check evasions when
|
||||
/// the side to move is in check. Returns a pointer to the end of the move list.
|
||||
/// generate<EVASIONS> generates all pseudo-legal check evasions when the side
|
||||
/// to move is in check. Returns a pointer to the end of the move list.
|
||||
template<>
|
||||
MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
|
||||
MoveStack* generate<EVASIONS>(const Position& pos, MoveStack* mlist) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
assert(pos.in_check());
|
||||
|
||||
Bitboard b, target;
|
||||
Square from, checksq;
|
||||
int checkersCnt = 0;
|
||||
Color us = pos.side_to_move();
|
||||
Square ksq = pos.king_square(us);
|
||||
Bitboard checkers = pos.checkers();
|
||||
Bitboard sliderAttacks = EmptyBoardBB;
|
||||
Bitboard sliderAttacks = 0;
|
||||
Bitboard b = pos.checkers();
|
||||
|
||||
assert(pos.piece_on(ksq) == make_piece(us, KING));
|
||||
assert(checkers);
|
||||
assert(pos.checkers());
|
||||
|
||||
// Find squares attacked by slider checkers, we will remove
|
||||
// them from the king evasions set so to early skip known
|
||||
// illegal moves and avoid an useless legality check later.
|
||||
b = checkers;
|
||||
// Find squares attacked by slider checkers, we will remove them from the king
|
||||
// evasions so to skip known illegal moves avoiding useless legality check later.
|
||||
do
|
||||
{
|
||||
checkersCnt++;
|
||||
checksq = pop_1st_bit(&b);
|
||||
checksq = pop_lsb(&b);
|
||||
|
||||
assert(pos.color_of_piece_on(checksq) == opposite_color(us));
|
||||
assert(color_of(pos.piece_on(checksq)) == ~us);
|
||||
|
||||
switch (pos.type_of_piece_on(checksq))
|
||||
switch (type_of(pos.piece_on(checksq)))
|
||||
{
|
||||
case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
|
||||
case ROOK: sliderAttacks |= RookPseudoAttacks[checksq]; break;
|
||||
case BISHOP: sliderAttacks |= PseudoAttacks[BISHOP][checksq]; break;
|
||||
case ROOK: sliderAttacks |= PseudoAttacks[ROOK][checksq]; break;
|
||||
case QUEEN:
|
||||
// In case of a queen remove also squares attacked in the other direction to
|
||||
// avoid possible illegal moves when queen and king are on adjacent squares.
|
||||
if (RookPseudoAttacks[checksq] & (1ULL << ksq))
|
||||
sliderAttacks |= RookPseudoAttacks[checksq] | pos.attacks_from<BISHOP>(checksq);
|
||||
// If queen and king are far or not on a diagonal line we can safely
|
||||
// remove all the squares attacked in the other direction becuase are
|
||||
// not reachable by the king anyway.
|
||||
if (between_bb(ksq, checksq) || !(PseudoAttacks[BISHOP][checksq] & ksq))
|
||||
sliderAttacks |= PseudoAttacks[QUEEN][checksq];
|
||||
|
||||
// Otherwise we need to use real rook attacks to check if king is safe
|
||||
// to move in the other direction. For example: king in B2, queen in A1
|
||||
// a knight in B1, and we can safely move to C1.
|
||||
else
|
||||
sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
|
||||
sliderAttacks |= PseudoAttacks[BISHOP][checksq] | pos.attacks_from<ROOK>(checksq);
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} while (b);
|
||||
|
||||
// Generate evasions for king, capture and non capture moves
|
||||
b = pos.attacks_from<KING>(ksq) & ~pos.pieces_of_color(us) & ~sliderAttacks;
|
||||
b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
|
||||
from = ksq;
|
||||
SERIALIZE_MOVES(b);
|
||||
SERIALIZE(b);
|
||||
|
||||
// Generate evasions for other pieces only if not double check
|
||||
if (checkersCnt > 1)
|
||||
return mlist;
|
||||
return mlist; // Double check, only a king move can save the day
|
||||
|
||||
// Find squares where a blocking evasion or a capture of the
|
||||
// checker piece is possible.
|
||||
target = squares_between(checksq, ksq) | checkers;
|
||||
// Generate blocking evasions or captures of the checking piece
|
||||
Bitboard target = between_bb(checksq, ksq) | pos.checkers();
|
||||
|
||||
mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
|
||||
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
|
||||
return generate_piece_moves<QUEEN>(pos, mlist, us, target);
|
||||
return generate_all_moves<EVASIONS>(pos, mlist, us, target);
|
||||
}
|
||||
|
||||
|
||||
/// generate<MV_LEGAL / MV_PSEUDO_LEGAL> computes a complete list of legal
|
||||
/// or pseudo-legal moves in the current position.
|
||||
template<>
|
||||
MoveStack* generate<MV_PSEUDO_LEGAL>(const Position& pos, MoveStack* mlist) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
|
||||
return pos.in_check() ? generate<MV_EVASION>(pos, mlist)
|
||||
: generate<MV_NON_EVASION>(pos, mlist);
|
||||
}
|
||||
/// generate<LEGAL> generates all the legal moves in the given position
|
||||
|
||||
template<>
|
||||
MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
|
||||
MoveStack* generate<LEGAL>(const Position& pos, MoveStack* mlist) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
MoveStack *end, *cur = mlist;
|
||||
Bitboard pinned = pos.pinned_pieces();
|
||||
Square ksq = pos.king_square(pos.side_to_move());
|
||||
|
||||
MoveStack *last, *cur = mlist;
|
||||
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
|
||||
|
||||
last = generate<MV_PSEUDO_LEGAL>(pos, mlist);
|
||||
|
||||
// Remove illegal moves from the list
|
||||
while (cur != last)
|
||||
if (!pos.pl_move_is_legal(cur->move, pinned))
|
||||
cur->move = (--last)->move;
|
||||
end = pos.in_check() ? generate<EVASIONS>(pos, mlist)
|
||||
: generate<NON_EVASIONS>(pos, mlist);
|
||||
while (cur != end)
|
||||
if ( (pinned || from_sq(cur->move) == ksq || type_of(cur->move) == ENPASSANT)
|
||||
&& !pos.pl_move_is_legal(cur->move, pinned))
|
||||
cur->move = (--end)->move;
|
||||
else
|
||||
cur++;
|
||||
|
||||
return last;
|
||||
return end;
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
template<Square Delta>
|
||||
inline Bitboard move_pawns(Bitboard p) {
|
||||
|
||||
return Delta == DELTA_N ? p << 8 : Delta == DELTA_S ? p >> 8 :
|
||||
Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
|
||||
Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
|
||||
}
|
||||
|
||||
template<MoveType Type, Square Delta>
|
||||
inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
|
||||
|
||||
const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
|
||||
|
||||
Bitboard b;
|
||||
Square to;
|
||||
|
||||
// Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
|
||||
b = move_pawns<Delta>(pawns) & target & ~TFileABB;
|
||||
SERIALIZE_MOVES_D(b, -Delta);
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<Color Us, MoveType Type, Square Delta>
|
||||
inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
|
||||
|
||||
const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
|
||||
|
||||
Bitboard b;
|
||||
Square to;
|
||||
|
||||
// Promotions and under-promotions, both captures and non-captures
|
||||
b = move_pawns<Delta>(pawnsOn7) & target;
|
||||
|
||||
if (Delta != DELTA_N && Delta != DELTA_S)
|
||||
b &= ~TFileABB;
|
||||
|
||||
while (b)
|
||||
{
|
||||
to = pop_1st_bit(&b);
|
||||
|
||||
if (Type == MV_CAPTURE || Type == MV_EVASION)
|
||||
(*mlist++).move = make_promotion_move(to - Delta, to, QUEEN);
|
||||
|
||||
if (Type == MV_NON_CAPTURE || Type == MV_EVASION)
|
||||
{
|
||||
(*mlist++).move = make_promotion_move(to - Delta, to, ROOK);
|
||||
(*mlist++).move = make_promotion_move(to - Delta, to, BISHOP);
|
||||
(*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
|
||||
}
|
||||
|
||||
// This is the only possible under promotion that can give a check
|
||||
// not already included in the queen-promotion.
|
||||
if ( Type == MV_CHECK
|
||||
&& bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(opposite_color(Us))))
|
||||
(*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
|
||||
else (void)pos; // Silence a warning under MSVC
|
||||
}
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<Color Us, MoveType Type>
|
||||
MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
|
||||
|
||||
// Calculate our parametrized parameters at compile time, named
|
||||
// according to the point of view of white side.
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
|
||||
const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
|
||||
const Square TDELTA_N = (Us == WHITE ? DELTA_N : DELTA_S);
|
||||
const Square TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
|
||||
const Square TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
|
||||
|
||||
Square to;
|
||||
Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
|
||||
Bitboard pawns = pos.pieces(PAWN, Us);
|
||||
Bitboard pawnsOn7 = pawns & TRank7BB;
|
||||
Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces_of_color(Them));
|
||||
|
||||
// Pre-calculate pawn pushes before changing emptySquares definition
|
||||
if (Type != MV_CAPTURE)
|
||||
{
|
||||
emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
|
||||
pawnPushes = move_pawns<TDELTA_N>(pawns & ~TRank7BB) & emptySquares;
|
||||
}
|
||||
|
||||
if (Type == MV_EVASION)
|
||||
{
|
||||
emptySquares &= target; // Only blocking squares
|
||||
enemyPieces &= target; // Capture only the checker piece
|
||||
}
|
||||
|
||||
// Promotions and underpromotions
|
||||
if (pawnsOn7)
|
||||
{
|
||||
if (Type == MV_CAPTURE)
|
||||
emptySquares = pos.empty_squares();
|
||||
|
||||
pawns &= ~TRank7BB;
|
||||
mlist = generate_promotions<Us, Type, TDELTA_NE>(pos, mlist, pawnsOn7, enemyPieces);
|
||||
mlist = generate_promotions<Us, Type, TDELTA_NW>(pos, mlist, pawnsOn7, enemyPieces);
|
||||
mlist = generate_promotions<Us, Type, TDELTA_N >(pos, mlist, pawnsOn7, emptySquares);
|
||||
}
|
||||
|
||||
// Standard captures
|
||||
if (Type == MV_CAPTURE || Type == MV_EVASION)
|
||||
{
|
||||
mlist = generate_pawn_captures<Type, TDELTA_NE>(mlist, pawns, enemyPieces);
|
||||
mlist = generate_pawn_captures<Type, TDELTA_NW>(mlist, pawns, enemyPieces);
|
||||
}
|
||||
|
||||
// Single and double pawn pushes
|
||||
if (Type != MV_CAPTURE)
|
||||
{
|
||||
b1 = pawnPushes & emptySquares;
|
||||
b2 = move_pawns<TDELTA_N>(pawnPushes & TRank3BB) & emptySquares;
|
||||
|
||||
if (Type == MV_CHECK)
|
||||
{
|
||||
// Consider only pawn moves which give direct checks
|
||||
b1 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||
b2 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||
|
||||
// Add pawn moves which gives discovered check. This is possible only
|
||||
// if the pawn is not on the same file as the enemy king, because we
|
||||
// don't generate captures.
|
||||
if (pawns & target) // For CHECK type target is dc bitboard
|
||||
{
|
||||
dc1 = move_pawns<TDELTA_N>(pawns & target & ~file_bb(ksq)) & emptySquares;
|
||||
dc2 = move_pawns<TDELTA_N>(dc1 & TRank3BB) & emptySquares;
|
||||
|
||||
b1 |= dc1;
|
||||
b2 |= dc2;
|
||||
}
|
||||
}
|
||||
SERIALIZE_MOVES_D(b1, -TDELTA_N);
|
||||
SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
|
||||
}
|
||||
|
||||
// En passant captures
|
||||
if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
|
||||
{
|
||||
assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
|
||||
assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
|
||||
|
||||
// An en passant capture can be an evasion only if the checking piece
|
||||
// is the double pushed pawn and so is in the target. Otherwise this
|
||||
// is a discovery check and we are forced to do otherwise.
|
||||
if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - TDELTA_N))
|
||||
return mlist;
|
||||
|
||||
b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
|
||||
|
||||
assert(b1 != EmptyBoardBB);
|
||||
|
||||
while (b1)
|
||||
{
|
||||
to = pop_1st_bit(&b1);
|
||||
(*mlist++).move = make_ep_move(to, pos.ep_square());
|
||||
}
|
||||
}
|
||||
return mlist;
|
||||
}
|
||||
|
||||
template<CastlingSide Side>
|
||||
MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
|
||||
|
||||
Color them = opposite_color(us);
|
||||
Square ksq = pos.king_square(us);
|
||||
|
||||
assert(pos.piece_on(ksq) == make_piece(us, KING));
|
||||
|
||||
Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
|
||||
Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
|
||||
Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
|
||||
Square s;
|
||||
bool illegal = false;
|
||||
|
||||
assert(pos.piece_on(rsq) == make_piece(us, ROOK));
|
||||
|
||||
// It is a bit complicated to correctly handle Chess960
|
||||
for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
|
||||
if ( (s != ksq && s != rsq && pos.square_is_occupied(s))
|
||||
||(pos.attackers_to(s) & pos.pieces_of_color(them)))
|
||||
illegal = true;
|
||||
|
||||
for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
|
||||
if (s != ksq && s != rsq && pos.square_is_occupied(s))
|
||||
illegal = true;
|
||||
|
||||
if ( Side == QUEEN_SIDE
|
||||
&& square_file(rsq) == FILE_B
|
||||
&& ( pos.piece_on(relative_square(us, SQ_A1)) == make_piece(them, ROOK)
|
||||
|| pos.piece_on(relative_square(us, SQ_A1)) == make_piece(them, QUEEN)))
|
||||
illegal = true;
|
||||
|
||||
if (!illegal)
|
||||
(*mlist++).move = make_castle_move(ksq, rsq);
|
||||
|
||||
return mlist;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,21 +20,36 @@
|
||||
#if !defined(MOVEGEN_H_INCLUDED)
|
||||
#define MOVEGEN_H_INCLUDED
|
||||
|
||||
#include "move.h"
|
||||
#include "position.h"
|
||||
#include "types.h"
|
||||
|
||||
enum MoveType {
|
||||
MV_CAPTURE,
|
||||
MV_NON_CAPTURE,
|
||||
MV_CHECK,
|
||||
MV_NON_CAPTURE_CHECK,
|
||||
MV_EVASION,
|
||||
MV_NON_EVASION,
|
||||
MV_LEGAL,
|
||||
MV_PSEUDO_LEGAL
|
||||
enum GenType {
|
||||
CAPTURES,
|
||||
QUIETS,
|
||||
QUIET_CHECKS,
|
||||
EVASIONS,
|
||||
NON_EVASIONS,
|
||||
LEGAL
|
||||
};
|
||||
|
||||
template<MoveType>
|
||||
class Position;
|
||||
|
||||
template<GenType>
|
||||
MoveStack* generate(const Position& pos, MoveStack* mlist);
|
||||
|
||||
/// The MoveList struct is a simple wrapper around generate(), sometimes comes
|
||||
/// handy to use this class instead of the low level generate() function.
|
||||
template<GenType T>
|
||||
struct MoveList {
|
||||
|
||||
explicit MoveList(const Position& pos) : cur(mlist), last(generate<T>(pos, mlist)) {}
|
||||
void operator++() { cur++; }
|
||||
bool end() const { return cur == last; }
|
||||
Move move() const { return cur->move; }
|
||||
size_t size() const { return last - mlist; }
|
||||
|
||||
private:
|
||||
MoveStack mlist[MAX_MOVES];
|
||||
MoveStack *cur, *last;
|
||||
};
|
||||
|
||||
#endif // !defined(MOVEGEN_H_INCLUDED)
|
||||
|
||||
410
src/movepick.cpp
410
src/movepick.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -18,174 +18,133 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
|
||||
#include "movegen.h"
|
||||
#include "movepick.h"
|
||||
#include "search.h"
|
||||
#include "types.h"
|
||||
#include "thread.h"
|
||||
|
||||
namespace {
|
||||
|
||||
enum MovegenPhase {
|
||||
PH_TT_MOVES, // Transposition table move and mate killer
|
||||
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0
|
||||
PH_KILLERS, // Killer moves from the current ply
|
||||
PH_NONCAPTURES, // Non-captures and underpromotions
|
||||
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < 0
|
||||
PH_EVASIONS, // Check evasions
|
||||
PH_QCAPTURES, // Captures in quiescence search
|
||||
PH_QCHECKS, // Non-capture checks in quiescence search
|
||||
PH_STOP
|
||||
enum Sequencer {
|
||||
MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
|
||||
EVASION, EVASIONS_S2,
|
||||
QSEARCH_0, CAPTURES_S3, QUIET_CHECKS_S3,
|
||||
QSEARCH_1, CAPTURES_S4,
|
||||
PROBCUT, CAPTURES_S5,
|
||||
RECAPTURE, CAPTURES_S6,
|
||||
STOP
|
||||
};
|
||||
|
||||
CACHE_LINE_ALIGNMENT
|
||||
const uint8_t MainSearchTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP };
|
||||
const uint8_t EvasionTable[] = { PH_TT_MOVES, PH_EVASIONS, PH_STOP };
|
||||
const uint8_t QsearchWithChecksTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP };
|
||||
const uint8_t QsearchWithoutChecksTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP };
|
||||
// Unary predicate used by std::partition to split positive scores from remaining
|
||||
// ones so to sort separately the two sets, and with the second sort delayed.
|
||||
inline bool has_positive_score(const MoveStack& ms) { return ms.score > 0; }
|
||||
|
||||
// Picks and moves to the front the best move in the range [begin, end),
|
||||
// it is faster than sorting all the moves in advance when moves are few, as
|
||||
// normally are the possible captures.
|
||||
inline MoveStack* pick_best(MoveStack* begin, MoveStack* end)
|
||||
{
|
||||
std::swap(*begin, *std::max_element(begin, end));
|
||||
return begin;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Constructor for the MovePicker class. Apart from the position for which
|
||||
/// it is asked to pick legal moves, MovePicker also wants some information
|
||||
/// Constructors of the MovePicker class. As arguments we pass information
|
||||
/// to help it to return the presumably good moves first, to decide which
|
||||
/// moves to return (in the quiescence search, for instance, we only want to
|
||||
/// search captures, promotions and some checks) and about how important good
|
||||
/// move ordering is at the current node.
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
|
||||
SearchStack* ss, Value beta) : pos(p), H(h) {
|
||||
int searchTT = ttm;
|
||||
ttMoves[0].move = ttm;
|
||||
badCaptureThreshold = 0;
|
||||
badCaptures = moves + MAX_MOVES;
|
||||
Search::Stack* s, Value beta) : pos(p), H(h), depth(d) {
|
||||
|
||||
assert(d > DEPTH_ZERO);
|
||||
|
||||
pinned = p.pinned_pieces(pos.side_to_move());
|
||||
captureThreshold = 0;
|
||||
cur = end = moves;
|
||||
endBadCaptures = moves + MAX_MOVES - 1;
|
||||
ss = s;
|
||||
|
||||
if (p.in_check())
|
||||
{
|
||||
ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
|
||||
phasePtr = EvasionTable;
|
||||
}
|
||||
phase = EVASION;
|
||||
|
||||
else
|
||||
{
|
||||
ttMoves[1].move = (ss->mateKiller == ttm) ? MOVE_NONE : ss->mateKiller;
|
||||
searchTT |= ttMoves[1].move;
|
||||
phase = MAIN_SEARCH;
|
||||
|
||||
killers[0].move = ss->killers[0];
|
||||
killers[1].move = ss->killers[1];
|
||||
|
||||
// Consider sligtly negative captures as good if at low
|
||||
// depth and far from beta.
|
||||
if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
|
||||
badCaptureThreshold = -PawnValueMidgame;
|
||||
// Consider sligtly negative captures as good if at low depth and far from beta
|
||||
if (ss && ss->eval < beta - PawnValueMg && d < 3 * ONE_PLY)
|
||||
captureThreshold = -PawnValueMg;
|
||||
|
||||
phasePtr = MainSearchTable;
|
||||
// Consider negative captures as good if still enough to reach beta
|
||||
else if (ss && ss->eval > beta)
|
||||
captureThreshold = beta - ss->eval;
|
||||
}
|
||||
|
||||
phasePtr += int(!searchTT) - 1;
|
||||
go_next_phase();
|
||||
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
end += (ttMove != MOVE_NONE);
|
||||
}
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h)
|
||||
: pos(p), H(h) {
|
||||
int searchTT = ttm;
|
||||
ttMoves[0].move = ttm;
|
||||
ttMoves[1].move = MOVE_NONE;
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
|
||||
Square sq) : pos(p), H(h), cur(moves), end(moves) {
|
||||
|
||||
assert(d <= DEPTH_ZERO);
|
||||
|
||||
pinned = p.pinned_pieces(pos.side_to_move());
|
||||
|
||||
if (p.in_check())
|
||||
phasePtr = EvasionTable;
|
||||
else if (d >= DEPTH_QS_CHECKS)
|
||||
phasePtr = QsearchWithChecksTable;
|
||||
phase = EVASION;
|
||||
|
||||
else if (d > DEPTH_QS_NO_CHECKS)
|
||||
phase = QSEARCH_0;
|
||||
|
||||
else if (d > DEPTH_QS_RECAPTURES)
|
||||
{
|
||||
phase = QSEARCH_1;
|
||||
|
||||
// Skip TT move if is not a capture or a promotion, this avoids qsearch
|
||||
// tree explosion due to a possible perpetual check or similar rare cases
|
||||
// when TT table is full.
|
||||
if (ttm && !pos.is_capture_or_promotion(ttm))
|
||||
ttm = MOVE_NONE;
|
||||
}
|
||||
else
|
||||
{
|
||||
phasePtr = QsearchWithoutChecksTable;
|
||||
|
||||
// Skip TT move if is not a capture or a promotion, this avoids
|
||||
// qsearch tree explosion due to a possible perpetual check or
|
||||
// similar rare cases when TT table is full.
|
||||
if (ttm != MOVE_NONE && !pos.move_is_capture_or_promotion(ttm))
|
||||
searchTT = ttMoves[0].move = MOVE_NONE;
|
||||
phase = RECAPTURE;
|
||||
recaptureSquare = sq;
|
||||
ttm = MOVE_NONE;
|
||||
}
|
||||
|
||||
phasePtr += int(!searchTT) - 1;
|
||||
go_next_phase();
|
||||
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
end += (ttMove != MOVE_NONE);
|
||||
}
|
||||
|
||||
MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType pt)
|
||||
: pos(p), H(h), cur(moves), end(moves) {
|
||||
|
||||
/// MovePicker::go_next_phase() generates, scores and sorts the next bunch
|
||||
/// of moves when there are no more moves to try for the current phase.
|
||||
assert(!pos.in_check());
|
||||
|
||||
void MovePicker::go_next_phase() {
|
||||
phase = PROBCUT;
|
||||
|
||||
curMove = moves;
|
||||
phase = *(++phasePtr);
|
||||
switch (phase) {
|
||||
// In ProbCut we generate only captures better than parent's captured piece
|
||||
captureThreshold = PieceValue[Mg][pt];
|
||||
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||
|
||||
case PH_TT_MOVES:
|
||||
curMove = ttMoves;
|
||||
lastMove = curMove + 2;
|
||||
return;
|
||||
if (ttMove && (!pos.is_capture(ttMove) || pos.see(ttMove) <= captureThreshold))
|
||||
ttMove = MOVE_NONE;
|
||||
|
||||
case PH_GOOD_CAPTURES:
|
||||
lastMove = generate<MV_CAPTURE>(pos, moves);
|
||||
score_captures();
|
||||
return;
|
||||
|
||||
case PH_KILLERS:
|
||||
curMove = killers;
|
||||
lastMove = curMove + 2;
|
||||
return;
|
||||
|
||||
case PH_NONCAPTURES:
|
||||
lastMove = generate<MV_NON_CAPTURE>(pos, moves);
|
||||
score_noncaptures();
|
||||
sort_moves(moves, lastMove, &lastGoodNonCapture);
|
||||
return;
|
||||
|
||||
case PH_BAD_CAPTURES:
|
||||
// Bad captures SEE value is already calculated so just pick
|
||||
// them in order to get SEE move ordering.
|
||||
curMove = badCaptures;
|
||||
lastMove = moves + MAX_MOVES;
|
||||
return;
|
||||
|
||||
case PH_EVASIONS:
|
||||
assert(pos.in_check());
|
||||
lastMove = generate<MV_EVASION>(pos, moves);
|
||||
score_evasions();
|
||||
return;
|
||||
|
||||
case PH_QCAPTURES:
|
||||
lastMove = generate<MV_CAPTURE>(pos, moves);
|
||||
score_captures();
|
||||
return;
|
||||
|
||||
case PH_QCHECKS:
|
||||
lastMove = generate<MV_NON_CAPTURE_CHECK>(pos, moves);
|
||||
return;
|
||||
|
||||
case PH_STOP:
|
||||
lastMove = curMove + 1; // Avoid another go_next_phase() call
|
||||
return;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
return;
|
||||
}
|
||||
end += (ttMove != MOVE_NONE);
|
||||
}
|
||||
|
||||
|
||||
/// MovePicker::score_captures(), MovePicker::score_noncaptures() and
|
||||
/// MovePicker::score_evasions() assign a numerical move ordering score
|
||||
/// to each move in a move list. The moves with highest scores will be
|
||||
/// picked first by get_next_move().
|
||||
/// picked first by next_move().
|
||||
|
||||
void MovePicker::score_captures() {
|
||||
// Winning and equal captures in the main search are ordered by MVV/LVA.
|
||||
@@ -203,148 +162,203 @@ void MovePicker::score_captures() {
|
||||
// some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
|
||||
Move m;
|
||||
|
||||
// Use MVV/LVA ordering
|
||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||
for (MoveStack* it = moves; it != end; ++it)
|
||||
{
|
||||
m = cur->move;
|
||||
if (move_is_promotion(m))
|
||||
cur->score = QueenValueMidgame;
|
||||
else
|
||||
cur->score = pos.midgame_value_of_piece_on(move_to(m))
|
||||
- pos.type_of_piece_on(move_from(m));
|
||||
m = it->move;
|
||||
it->score = PieceValue[Mg][pos.piece_on(to_sq(m))]
|
||||
- type_of(pos.piece_moved(m));
|
||||
|
||||
if (type_of(m) == PROMOTION)
|
||||
it->score += PieceValue[Mg][promotion_type(m)];
|
||||
}
|
||||
}
|
||||
|
||||
void MovePicker::score_noncaptures() {
|
||||
|
||||
Move m;
|
||||
Square from;
|
||||
|
||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||
for (MoveStack* it = moves; it != end; ++it)
|
||||
{
|
||||
m = cur->move;
|
||||
from = move_from(m);
|
||||
cur->score = H.value(pos.piece_on(from), move_to(m));
|
||||
m = it->move;
|
||||
it->score = H.value(pos.piece_moved(m), to_sq(m));
|
||||
}
|
||||
}
|
||||
|
||||
void MovePicker::score_evasions() {
|
||||
// Try good captures ordered by MVV/LVA, then non-captures if
|
||||
// destination square is not under attack, ordered by history
|
||||
// value, and at the end bad-captures and non-captures with a
|
||||
// negative SEE. This last group is ordered by the SEE score.
|
||||
// Try good captures ordered by MVV/LVA, then non-captures if destination square
|
||||
// is not under attack, ordered by history value, then bad-captures and quiet
|
||||
// moves with a negative SEE. This last group is ordered by the SEE score.
|
||||
Move m;
|
||||
int seeScore;
|
||||
|
||||
// Skip if we don't have at least two moves to order
|
||||
if (lastMove < moves + 2)
|
||||
if (end < moves + 2)
|
||||
return;
|
||||
|
||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||
for (MoveStack* it = moves; it != end; ++it)
|
||||
{
|
||||
m = cur->move;
|
||||
m = it->move;
|
||||
if ((seeScore = pos.see_sign(m)) < 0)
|
||||
cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
|
||||
else if (pos.move_is_capture(m))
|
||||
cur->score = pos.midgame_value_of_piece_on(move_to(m))
|
||||
- pos.type_of_piece_on(move_from(m)) + History::MaxValue;
|
||||
it->score = seeScore - History::MaxValue; // Be sure we are at the bottom
|
||||
else if (pos.is_capture(m))
|
||||
it->score = PieceValue[Mg][pos.piece_on(to_sq(m))]
|
||||
- type_of(pos.piece_moved(m)) + History::MaxValue;
|
||||
else
|
||||
cur->score = H.value(pos.piece_on(move_from(m)), move_to(m));
|
||||
it->score = H.value(pos.piece_moved(m), to_sq(m));
|
||||
}
|
||||
}
|
||||
|
||||
/// MovePicker::get_next_move() is the most important method of the MovePicker
|
||||
/// class. It returns a new legal move every time it is called, until there
|
||||
|
||||
/// MovePicker::generate_next() generates, scores and sorts the next bunch of moves,
|
||||
/// when there are no more moves to try for the current phase.
|
||||
|
||||
void MovePicker::generate_next() {
|
||||
|
||||
cur = moves;
|
||||
|
||||
switch (++phase) {
|
||||
|
||||
case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
|
||||
end = generate<CAPTURES>(pos, moves);
|
||||
score_captures();
|
||||
return;
|
||||
|
||||
case KILLERS_S1:
|
||||
cur = killers;
|
||||
end = cur + 2;
|
||||
return;
|
||||
|
||||
case QUIETS_1_S1:
|
||||
endQuiets = end = generate<QUIETS>(pos, moves);
|
||||
score_noncaptures();
|
||||
end = std::partition(cur, end, has_positive_score);
|
||||
sort<MoveStack>(cur, end);
|
||||
return;
|
||||
|
||||
case QUIETS_2_S1:
|
||||
cur = end;
|
||||
end = endQuiets;
|
||||
if (depth >= 3 * ONE_PLY)
|
||||
sort<MoveStack>(cur, end);
|
||||
return;
|
||||
|
||||
case BAD_CAPTURES_S1:
|
||||
// Just pick them in reverse order to get MVV/LVA ordering
|
||||
cur = moves + MAX_MOVES - 1;
|
||||
end = endBadCaptures;
|
||||
return;
|
||||
|
||||
case EVASIONS_S2:
|
||||
end = generate<EVASIONS>(pos, moves);
|
||||
score_evasions();
|
||||
return;
|
||||
|
||||
case QUIET_CHECKS_S3:
|
||||
end = generate<QUIET_CHECKS>(pos, moves);
|
||||
return;
|
||||
|
||||
case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
|
||||
phase = STOP;
|
||||
case STOP:
|
||||
end = cur + 1; // Avoid another next_phase() call
|
||||
return;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// MovePicker::next_move() is the most important method of the MovePicker class.
|
||||
/// It returns a new pseudo legal move every time it is called, until there
|
||||
/// are no more moves left. It picks the move with the biggest score from a list
|
||||
/// of generated moves taking care not to return the tt move if has already been
|
||||
/// searched previously. Note that this function is not thread safe so should be
|
||||
/// lock protected by caller when accessed through a shared MovePicker object.
|
||||
|
||||
Move MovePicker::get_next_move() {
|
||||
/// searched previously.
|
||||
template<>
|
||||
Move MovePicker::next_move<false>() {
|
||||
|
||||
Move move;
|
||||
|
||||
while (true)
|
||||
{
|
||||
while (curMove == lastMove)
|
||||
go_next_phase();
|
||||
while (cur == end)
|
||||
generate_next();
|
||||
|
||||
switch (phase) {
|
||||
|
||||
case PH_TT_MOVES:
|
||||
move = (curMove++)->move;
|
||||
if ( move != MOVE_NONE
|
||||
&& pos.move_is_legal(move, pinned))
|
||||
return move;
|
||||
break;
|
||||
case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
|
||||
cur++;
|
||||
return ttMove;
|
||||
|
||||
case PH_GOOD_CAPTURES:
|
||||
move = pick_best(curMove++, lastMove).move;
|
||||
if ( move != ttMoves[0].move
|
||||
&& move != ttMoves[1].move
|
||||
&& pos.pl_move_is_legal(move, pinned))
|
||||
case CAPTURES_S1:
|
||||
move = pick_best(cur++, end)->move;
|
||||
if (move != ttMove)
|
||||
{
|
||||
// Check for a non negative SEE now
|
||||
int seeValue = pos.see_sign(move);
|
||||
if (seeValue >= badCaptureThreshold)
|
||||
assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
|
||||
|
||||
if (pos.see_sign(move) >= captureThreshold)
|
||||
return move;
|
||||
|
||||
// Losing capture, move it to the tail of the array, note
|
||||
// that move has now been already checked for legality.
|
||||
(--badCaptures)->move = move;
|
||||
badCaptures->score = seeValue;
|
||||
// Losing capture, move it to the tail of the array
|
||||
(endBadCaptures--)->move = move;
|
||||
}
|
||||
break;
|
||||
|
||||
case PH_KILLERS:
|
||||
move = (curMove++)->move;
|
||||
if ( move != MOVE_NONE
|
||||
&& pos.move_is_legal(move, pinned)
|
||||
&& move != ttMoves[0].move
|
||||
&& move != ttMoves[1].move
|
||||
&& !pos.move_is_capture(move))
|
||||
case KILLERS_S1:
|
||||
move = (cur++)->move;
|
||||
if ( move != MOVE_NONE
|
||||
&& pos.is_pseudo_legal(move)
|
||||
&& move != ttMove
|
||||
&& !pos.is_capture(move))
|
||||
return move;
|
||||
break;
|
||||
|
||||
case PH_NONCAPTURES:
|
||||
// Sort negative scored moves only when we get there
|
||||
if (curMove == lastGoodNonCapture)
|
||||
insertion_sort<MoveStack>(lastGoodNonCapture, lastMove);
|
||||
|
||||
move = (curMove++)->move;
|
||||
if ( move != ttMoves[0].move
|
||||
&& move != ttMoves[1].move
|
||||
case QUIETS_1_S1: case QUIETS_2_S1:
|
||||
move = (cur++)->move;
|
||||
if ( move != ttMove
|
||||
&& move != killers[0].move
|
||||
&& move != killers[1].move
|
||||
&& pos.pl_move_is_legal(move, pinned))
|
||||
&& move != killers[1].move)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case PH_BAD_CAPTURES:
|
||||
move = pick_best(curMove++, lastMove).move;
|
||||
return move;
|
||||
case BAD_CAPTURES_S1:
|
||||
return (cur--)->move;
|
||||
|
||||
case PH_EVASIONS:
|
||||
case PH_QCAPTURES:
|
||||
move = pick_best(curMove++, lastMove).move;
|
||||
if ( move != ttMoves[0].move
|
||||
&& pos.pl_move_is_legal(move, pinned))
|
||||
case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
|
||||
move = pick_best(cur++, end)->move;
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case PH_QCHECKS:
|
||||
move = (curMove++)->move;
|
||||
if ( move != ttMoves[0].move
|
||||
&& pos.pl_move_is_legal(move, pinned))
|
||||
case CAPTURES_S5:
|
||||
move = pick_best(cur++, end)->move;
|
||||
if (move != ttMove && pos.see(move) > captureThreshold)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case CAPTURES_S6:
|
||||
move = pick_best(cur++, end)->move;
|
||||
if (to_sq(move) == recaptureSquare)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case PH_STOP:
|
||||
case QUIET_CHECKS_S3:
|
||||
move = (cur++)->move;
|
||||
if (move != ttMove)
|
||||
return move;
|
||||
break;
|
||||
|
||||
case STOP:
|
||||
return MOVE_NONE;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Version of next_move() to use at split point nodes where the move is grabbed
|
||||
/// from the split point's shared MovePicker object. This function is not thread
|
||||
/// safe so should be lock protected by the caller.
|
||||
template<>
|
||||
Move MovePicker::next_move<true>() { return ss->sp->mp->next_move<false>(); }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -21,42 +21,43 @@
|
||||
#define MOVEPICK_H_INCLUDED
|
||||
|
||||
#include "history.h"
|
||||
#include "move.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "types.h"
|
||||
|
||||
struct SearchStack;
|
||||
|
||||
/// MovePicker is a class which is used to pick one legal move at a time from
|
||||
/// the current position. It is initialized with a Position object and a few
|
||||
/// moves we have reason to believe are good. The most important method is
|
||||
/// MovePicker::get_next_move(), which returns a new legal move each time it
|
||||
/// is called, until there are no legal moves left, when MOVE_NONE is returned.
|
||||
/// In order to improve the efficiency of the alpha beta algorithm, MovePicker
|
||||
/// attempts to return the moves which are most likely to get a cut-off first.
|
||||
/// MovePicker class is used to pick one pseudo legal move at a time from the
|
||||
/// current position. The most important method is next_move(), which returns a
|
||||
/// new pseudo legal move each time it is called, until there are no moves left,
|
||||
/// when MOVE_NONE is returned. In order to improve the efficiency of the alpha
|
||||
/// beta algorithm, MovePicker attempts to return the moves which are most likely
|
||||
/// to get a cut-off first.
|
||||
|
||||
class MovePicker {
|
||||
|
||||
MovePicker& operator=(const MovePicker&); // Silence a warning under MSVC
|
||||
|
||||
public:
|
||||
MovePicker(const Position&, Move, Depth, const History&, SearchStack*, Value);
|
||||
MovePicker(const Position&, Move, Depth, const History&);
|
||||
Move get_next_move();
|
||||
MovePicker(const Position&, Move, Depth, const History&, Search::Stack*, Value);
|
||||
MovePicker(const Position&, Move, Depth, const History&, Square);
|
||||
MovePicker(const Position&, Move, const History&, PieceType);
|
||||
template<bool SpNode> Move next_move();
|
||||
|
||||
private:
|
||||
void score_captures();
|
||||
void score_noncaptures();
|
||||
void score_evasions();
|
||||
void go_next_phase();
|
||||
void generate_next();
|
||||
|
||||
const Position& pos;
|
||||
const History& H;
|
||||
Bitboard pinned;
|
||||
MoveStack ttMoves[2], killers[2];
|
||||
int badCaptureThreshold, phase;
|
||||
const uint8_t* phasePtr;
|
||||
MoveStack *curMove, *lastMove, *lastGoodNonCapture, *badCaptures;
|
||||
Search::Stack* ss;
|
||||
Depth depth;
|
||||
Move ttMove;
|
||||
MoveStack killers[2];
|
||||
Square recaptureSquare;
|
||||
int captureThreshold, phase;
|
||||
MoveStack *cur, *end, *endQuiets, *endBadCaptures;
|
||||
MoveStack moves[MAX_MOVES];
|
||||
};
|
||||
|
||||
|
||||
271
src/notation.cpp
Normal file
271
src/notation.cpp
Normal file
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include "movegen.h"
|
||||
#include "notation.h"
|
||||
#include "position.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
static const char* PieceToChar = " PNBRQK pnbrqk";
|
||||
|
||||
|
||||
/// score_to_uci() converts a value to a string suitable for use with the UCI
|
||||
/// protocol specifications:
|
||||
///
|
||||
/// cp <x> The score from the engine's point of view in centipawns.
|
||||
/// mate <y> Mate in y moves, not plies. If the engine is getting mated
|
||||
/// use negative values for y.
|
||||
|
||||
string score_to_uci(Value v, Value alpha, Value beta) {
|
||||
|
||||
stringstream s;
|
||||
|
||||
if (abs(v) < VALUE_MATE_IN_MAX_PLY)
|
||||
s << "cp " << v * 100 / int(PawnValueMg);
|
||||
else
|
||||
s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
|
||||
|
||||
s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
|
||||
|
||||
return s.str();
|
||||
}
|
||||
|
||||
|
||||
/// move_to_uci() converts a move to a string in coordinate notation
|
||||
/// (g1f3, a7a8q, etc.). The only special case is castling moves, where we print
|
||||
/// in the e1g1 notation in normal chess mode, and in e1h1 notation in chess960
|
||||
/// mode. Internally castle moves are always coded as "king captures rook".
|
||||
|
||||
const string move_to_uci(Move m, bool chess960) {
|
||||
|
||||
Square from = from_sq(m);
|
||||
Square to = to_sq(m);
|
||||
|
||||
if (m == MOVE_NONE)
|
||||
return "(none)";
|
||||
|
||||
if (m == MOVE_NULL)
|
||||
return "0000";
|
||||
|
||||
if (type_of(m) == CASTLE && !chess960)
|
||||
to = (to > from ? FILE_G : FILE_C) | rank_of(from);
|
||||
|
||||
string move = square_to_string(from) + square_to_string(to);
|
||||
|
||||
if (type_of(m) == PROMOTION)
|
||||
move += PieceToChar[make_piece(BLACK, promotion_type(m))]; // Lower case
|
||||
|
||||
return move;
|
||||
}
|
||||
|
||||
|
||||
/// move_from_uci() takes a position and a string representing a move in
|
||||
/// simple coordinate notation and returns an equivalent legal Move if any.
|
||||
|
||||
Move move_from_uci(const Position& pos, string& str) {
|
||||
|
||||
if (str.length() == 5) // Junior could send promotion piece in uppercase
|
||||
str[4] = char(tolower(str[4]));
|
||||
|
||||
for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
|
||||
if (str == move_to_uci(ml.move(), pos.is_chess960()))
|
||||
return ml.move();
|
||||
|
||||
return MOVE_NONE;
|
||||
}
|
||||
|
||||
|
||||
/// move_to_san() takes a position and a legal Move as input and returns its
|
||||
/// short algebraic notation representation.
|
||||
|
||||
const string move_to_san(Position& pos, Move m) {
|
||||
|
||||
if (m == MOVE_NONE)
|
||||
return "(none)";
|
||||
|
||||
if (m == MOVE_NULL)
|
||||
return "(null)";
|
||||
|
||||
assert(pos.move_is_legal(m));
|
||||
|
||||
Bitboard attackers;
|
||||
bool ambiguousMove, ambiguousFile, ambiguousRank;
|
||||
string san;
|
||||
Color us = pos.side_to_move();
|
||||
Square from = from_sq(m);
|
||||
Square to = to_sq(m);
|
||||
Piece pc = pos.piece_on(from);
|
||||
PieceType pt = type_of(pc);
|
||||
|
||||
if (type_of(m) == CASTLE)
|
||||
san = to > from ? "O-O" : "O-O-O";
|
||||
else
|
||||
{
|
||||
if (pt != PAWN)
|
||||
{
|
||||
san = PieceToChar[pt]; // Upper case
|
||||
|
||||
// Disambiguation if we have more then one piece with destination 'to'
|
||||
// note that for pawns is not needed because starting file is explicit.
|
||||
ambiguousMove = ambiguousFile = ambiguousRank = false;
|
||||
|
||||
attackers = (pos.attacks_from(pc, to) & pos.pieces(us, pt)) ^ from;
|
||||
|
||||
while (attackers)
|
||||
{
|
||||
Square sq = pop_lsb(&attackers);
|
||||
|
||||
// Pinned pieces are not included in the possible sub-set
|
||||
if (!pos.pl_move_is_legal(make_move(sq, to), pos.pinned_pieces()))
|
||||
continue;
|
||||
|
||||
ambiguousFile |= file_of(sq) == file_of(from);
|
||||
ambiguousRank |= rank_of(sq) == rank_of(from);
|
||||
ambiguousMove = true;
|
||||
}
|
||||
|
||||
if (ambiguousMove)
|
||||
{
|
||||
if (!ambiguousFile)
|
||||
san += file_to_char(file_of(from));
|
||||
|
||||
else if (!ambiguousRank)
|
||||
san += rank_to_char(rank_of(from));
|
||||
|
||||
else
|
||||
san += square_to_string(from);
|
||||
}
|
||||
}
|
||||
else if (pos.is_capture(m))
|
||||
san = file_to_char(file_of(from));
|
||||
|
||||
if (pos.is_capture(m))
|
||||
san += 'x';
|
||||
|
||||
san += square_to_string(to);
|
||||
|
||||
if (type_of(m) == PROMOTION)
|
||||
san += string("=") + PieceToChar[promotion_type(m)];
|
||||
}
|
||||
|
||||
if (pos.move_gives_check(m, CheckInfo(pos)))
|
||||
{
|
||||
StateInfo st;
|
||||
pos.do_move(m, st);
|
||||
san += MoveList<LEGAL>(pos).size() ? "+" : "#";
|
||||
pos.undo_move(m);
|
||||
}
|
||||
|
||||
return san;
|
||||
}
|
||||
|
||||
|
||||
/// pretty_pv() formats human-readable search information, typically to be
|
||||
/// appended to the search log file. It uses the two helpers below to pretty
|
||||
/// format time and score respectively.
|
||||
|
||||
static string time_to_string(int64_t msecs) {
|
||||
|
||||
const int MSecMinute = 1000 * 60;
|
||||
const int MSecHour = 1000 * 60 * 60;
|
||||
|
||||
int64_t hours = msecs / MSecHour;
|
||||
int64_t minutes = (msecs % MSecHour) / MSecMinute;
|
||||
int64_t seconds = ((msecs % MSecHour) % MSecMinute) / 1000;
|
||||
|
||||
stringstream s;
|
||||
|
||||
if (hours)
|
||||
s << hours << ':';
|
||||
|
||||
s << setfill('0') << setw(2) << minutes << ':' << setw(2) << seconds;
|
||||
|
||||
return s.str();
|
||||
}
|
||||
|
||||
static string score_to_string(Value v) {
|
||||
|
||||
stringstream s;
|
||||
|
||||
if (v >= VALUE_MATE_IN_MAX_PLY)
|
||||
s << "#" << (VALUE_MATE - v + 1) / 2;
|
||||
|
||||
else if (v <= VALUE_MATED_IN_MAX_PLY)
|
||||
s << "-#" << (VALUE_MATE + v) / 2;
|
||||
|
||||
else
|
||||
s << setprecision(2) << fixed << showpos << float(v) / PawnValueMg;
|
||||
|
||||
return s.str();
|
||||
}
|
||||
|
||||
string pretty_pv(Position& pos, int depth, Value value, int64_t msecs, Move pv[]) {
|
||||
|
||||
const int64_t K = 1000;
|
||||
const int64_t M = 1000000;
|
||||
|
||||
StateInfo state[MAX_PLY_PLUS_2], *st = state;
|
||||
Move* m = pv;
|
||||
string san, padding;
|
||||
size_t length;
|
||||
stringstream s;
|
||||
|
||||
s << setw(2) << depth
|
||||
<< setw(8) << score_to_string(value)
|
||||
<< setw(8) << time_to_string(msecs);
|
||||
|
||||
if (pos.nodes_searched() < M)
|
||||
s << setw(8) << pos.nodes_searched() / 1 << " ";
|
||||
|
||||
else if (pos.nodes_searched() < K * M)
|
||||
s << setw(7) << pos.nodes_searched() / K << "K ";
|
||||
|
||||
else
|
||||
s << setw(7) << pos.nodes_searched() / M << "M ";
|
||||
|
||||
padding = string(s.str().length(), ' ');
|
||||
length = padding.length();
|
||||
|
||||
while (*m != MOVE_NONE)
|
||||
{
|
||||
san = move_to_san(pos, *m);
|
||||
|
||||
if (length + san.length() > 80)
|
||||
{
|
||||
s << "\n" + padding;
|
||||
length = padding.length();
|
||||
}
|
||||
|
||||
s << san << ' ';
|
||||
length += san.length() + 1;
|
||||
|
||||
pos.do_move(*m++, *st++);
|
||||
}
|
||||
|
||||
while (m != pv)
|
||||
pos.undo_move(*--m);
|
||||
|
||||
return s.str();
|
||||
}
|
||||
35
src/notation.h
Normal file
35
src/notation.h
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#if !defined(NOTATION_H_INCLUDED)
|
||||
#define NOTATION_H_INCLUDED
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
class Position;
|
||||
|
||||
std::string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
|
||||
Move move_from_uci(const Position& pos, std::string& str);
|
||||
const std::string move_to_uci(Move m, bool chess960);
|
||||
const std::string move_to_san(Position& pos, Move m);
|
||||
std::string pretty_pv(Position& pos, int depth, Value score, int64_t msecs, Move pv[]);
|
||||
|
||||
#endif // !defined(NOTATION_H_INCLUDED)
|
||||
188
src/pawns.cpp
188
src/pawns.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -26,6 +26,7 @@
|
||||
|
||||
namespace {
|
||||
|
||||
#define V Value
|
||||
#define S(mg, eg) make_score(mg, eg)
|
||||
|
||||
// Doubled pawn penalty by opposed flag and file
|
||||
@@ -63,62 +64,66 @@ namespace {
|
||||
|
||||
const Score PawnStructureWeight = S(233, 201);
|
||||
|
||||
#undef S
|
||||
// Weakness of our pawn shelter in front of the king indexed by [king pawn][rank]
|
||||
const Value ShelterWeakness[2][8] =
|
||||
{ { V(141), V(0), V(38), V(102), V(128), V(141), V(141) },
|
||||
{ V( 61), V(0), V(16), V( 44), V( 56), V( 61), V( 61) } };
|
||||
|
||||
inline Score apply_weight(Score v, Score w) {
|
||||
return make_score((int(mg_value(v)) * mg_value(w)) / 0x100,
|
||||
(int(eg_value(v)) * eg_value(w)) / 0x100);
|
||||
}
|
||||
// Danger of enemy pawns moving toward our king indexed by [pawn blocked][rank]
|
||||
const Value StormDanger[2][8] =
|
||||
{ { V(26), V(0), V(128), V(51), V(26) },
|
||||
{ V(13), V(0), V( 64), V(25), V(13) } };
|
||||
|
||||
// Max bonus for king safety. Corresponds to start position with all the pawns
|
||||
// in front of the king and no enemy pawn on the horizont.
|
||||
const Value MaxSafetyBonus = V(263);
|
||||
|
||||
#undef S
|
||||
#undef V
|
||||
}
|
||||
|
||||
|
||||
/// PawnInfoTable::get_pawn_info() takes a position object as input, computes
|
||||
/// a PawnInfo object, and returns a pointer to it. The result is also stored
|
||||
/// in an hash table, so we don't have to recompute everything when the same
|
||||
/// pawn structure occurs again.
|
||||
/// PawnTable::probe() takes a position object as input, computes a PawnEntry
|
||||
/// object, and returns a pointer to it. The result is also stored in a hash
|
||||
/// table, so we don't have to recompute everything when the same pawn structure
|
||||
/// occurs again.
|
||||
|
||||
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) const {
|
||||
PawnEntry* PawnTable::probe(const Position& pos) {
|
||||
|
||||
assert(pos.is_ok());
|
||||
Key key = pos.pawn_key();
|
||||
PawnEntry* e = entries[key];
|
||||
|
||||
Key key = pos.get_pawn_key();
|
||||
PawnInfo* pi = probe(key);
|
||||
|
||||
// If pi->key matches the position's pawn hash key, it means that we
|
||||
// If e->key matches the position's pawn hash key, it means that we
|
||||
// have analysed this pawn structure before, and we can simply return
|
||||
// the information we found the last time instead of recomputing it.
|
||||
if (pi->key == key)
|
||||
return pi;
|
||||
if (e->key == key)
|
||||
return e;
|
||||
|
||||
// Initialize PawnInfo entry
|
||||
pi->key = key;
|
||||
pi->passedPawns[WHITE] = pi->passedPawns[BLACK] = 0;
|
||||
pi->kingSquares[WHITE] = pi->kingSquares[BLACK] = SQ_NONE;
|
||||
pi->halfOpenFiles[WHITE] = pi->halfOpenFiles[BLACK] = 0xFF;
|
||||
e->key = key;
|
||||
e->passedPawns[WHITE] = e->passedPawns[BLACK] = 0;
|
||||
e->kingSquares[WHITE] = e->kingSquares[BLACK] = SQ_NONE;
|
||||
e->halfOpenFiles[WHITE] = e->halfOpenFiles[BLACK] = 0xFF;
|
||||
|
||||
// Calculate pawn attacks
|
||||
Bitboard wPawns = pos.pieces(PAWN, WHITE);
|
||||
Bitboard bPawns = pos.pieces(PAWN, BLACK);
|
||||
pi->pawnAttacks[WHITE] = ((wPawns << 9) & ~FileABB) | ((wPawns << 7) & ~FileHBB);
|
||||
pi->pawnAttacks[BLACK] = ((bPawns >> 7) & ~FileABB) | ((bPawns >> 9) & ~FileHBB);
|
||||
Bitboard wPawns = pos.pieces(WHITE, PAWN);
|
||||
Bitboard bPawns = pos.pieces(BLACK, PAWN);
|
||||
e->pawnAttacks[WHITE] = ((wPawns & ~FileHBB) << 9) | ((wPawns & ~FileABB) << 7);
|
||||
e->pawnAttacks[BLACK] = ((bPawns & ~FileHBB) >> 7) | ((bPawns & ~FileABB) >> 9);
|
||||
|
||||
// Evaluate pawns for both colors and weight the result
|
||||
pi->value = evaluate_pawns<WHITE>(pos, wPawns, bPawns, pi)
|
||||
- evaluate_pawns<BLACK>(pos, bPawns, wPawns, pi);
|
||||
e->value = evaluate_pawns<WHITE>(pos, wPawns, bPawns, e)
|
||||
- evaluate_pawns<BLACK>(pos, bPawns, wPawns, e);
|
||||
|
||||
pi->value = apply_weight(pi->value, PawnStructureWeight);
|
||||
e->value = apply_weight(e->value, PawnStructureWeight);
|
||||
|
||||
return pi;
|
||||
return e;
|
||||
}
|
||||
|
||||
|
||||
/// PawnInfoTable::evaluate_pawns() evaluates each pawn of the given color
|
||||
/// PawnTable::evaluate_pawns() evaluates each pawn of the given color
|
||||
|
||||
template<Color Us>
|
||||
Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
Bitboard theirPawns, PawnInfo* pi) {
|
||||
Score PawnTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
Bitboard theirPawns, PawnEntry* e) {
|
||||
|
||||
const BitCountType Max15 = CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
|
||||
Bitboard b;
|
||||
@@ -127,43 +132,43 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
Rank r;
|
||||
bool passed, isolated, doubled, opposed, chain, backward, candidate;
|
||||
Score value = SCORE_ZERO;
|
||||
const Square* ptr = pos.piece_list_begin(Us, PAWN);
|
||||
const Square* pl = pos.piece_list(Us, PAWN);
|
||||
|
||||
// Loop through all pawns of the current color and score each pawn
|
||||
while ((s = *ptr++) != SQ_NONE)
|
||||
while ((s = *pl++) != SQ_NONE)
|
||||
{
|
||||
assert(pos.piece_on(s) == make_piece(Us, PAWN));
|
||||
|
||||
f = square_file(s);
|
||||
r = square_rank(s);
|
||||
f = file_of(s);
|
||||
r = rank_of(s);
|
||||
|
||||
// This file cannot be half open
|
||||
pi->halfOpenFiles[Us] &= ~(1 << f);
|
||||
e->halfOpenFiles[Us] &= ~(1 << f);
|
||||
|
||||
// Our rank plus previous one. Used for chain detection
|
||||
b = rank_bb(r) | rank_bb(Us == WHITE ? r - Rank(1) : r + Rank(1));
|
||||
|
||||
// Flag the pawn as passed, isolated, doubled or member of a pawn
|
||||
// chain (but not the backward one).
|
||||
chain = ourPawns & adjacent_files_bb(f) & b;
|
||||
isolated = !(ourPawns & adjacent_files_bb(f));
|
||||
doubled = ourPawns & forward_bb(Us, s);
|
||||
opposed = theirPawns & forward_bb(Us, s);
|
||||
passed = !(theirPawns & passed_pawn_mask(Us, s));
|
||||
doubled = ourPawns & squares_in_front_of(Us, s);
|
||||
opposed = theirPawns & squares_in_front_of(Us, s);
|
||||
isolated = !(ourPawns & neighboring_files_bb(f));
|
||||
chain = ourPawns & neighboring_files_bb(f) & b;
|
||||
|
||||
// Test for backward pawn
|
||||
backward = false;
|
||||
|
||||
// If the pawn is passed, isolated, or member of a pawn chain it cannot
|
||||
// be backward. If there are friendly pawns behind on neighboring files
|
||||
// be backward. If there are friendly pawns behind on adjacent files
|
||||
// or if can capture an enemy pawn it cannot be backward either.
|
||||
if ( !(passed | isolated | chain)
|
||||
&& !(ourPawns & attack_span_mask(Them, s))
|
||||
&& !(pos.attacks_from<PAWN>(s, Us) & theirPawns))
|
||||
{
|
||||
// We now know that there are no friendly pawns beside or behind this
|
||||
// pawn on neighboring files. We now check whether the pawn is
|
||||
// backward by looking in the forward direction on the neighboring
|
||||
// pawn on adjacent files. We now check whether the pawn is
|
||||
// backward by looking in the forward direction on the adjacent
|
||||
// files, and seeing whether we meet a friendly or an enemy pawn first.
|
||||
b = pos.attacks_from<PAWN>(s, Us);
|
||||
|
||||
@@ -181,17 +186,17 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
|
||||
// A not passed pawn is a candidate to become passed if it is free to
|
||||
// advance and if the number of friendly pawns beside or behind this
|
||||
// pawn on neighboring files is higher or equal than the number of
|
||||
// enemy pawns in the forward direction on the neighboring files.
|
||||
// pawn on adjacent files is higher or equal than the number of
|
||||
// enemy pawns in the forward direction on the adjacent files.
|
||||
candidate = !(opposed | passed | backward | isolated)
|
||||
&& (b = attack_span_mask(Them, s + pawn_push(Us)) & ourPawns) != EmptyBoardBB
|
||||
&& count_1s<Max15>(b) >= count_1s<Max15>(attack_span_mask(Us, s) & theirPawns);
|
||||
&& (b = attack_span_mask(Them, s + pawn_push(Us)) & ourPawns) != 0
|
||||
&& popcount<Max15>(b) >= popcount<Max15>(attack_span_mask(Us, s) & theirPawns);
|
||||
|
||||
// Passed pawns will be properly scored in evaluation because we need
|
||||
// full attack info to evaluate passed pawns. Only the frontmost passed
|
||||
// pawn on each file is considered a true passed pawn.
|
||||
if (passed && !doubled)
|
||||
set_bit(&(pi->passedPawns[Us]), s);
|
||||
e->passedPawns[Us] |= s;
|
||||
|
||||
// Score this pawn
|
||||
if (isolated)
|
||||
@@ -209,35 +214,74 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
if (candidate)
|
||||
value += CandidateBonus[relative_rank(Us, s)];
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
/// PawnInfo::updateShelter() calculates and caches king shelter. It is called
|
||||
/// only when king square changes, about 20% of total king_shelter() calls.
|
||||
/// PawnEntry::shelter_storm() calculates shelter and storm penalties for the file
|
||||
/// the king is on, as well as the two adjacent files.
|
||||
|
||||
template<Color Us>
|
||||
Score PawnInfo::updateShelter(const Position& pos, Square ksq) {
|
||||
Value PawnEntry::shelter_storm(const Position& pos, Square ksq) {
|
||||
|
||||
const int Shift = (Us == WHITE ? 8 : -8);
|
||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||
|
||||
Bitboard pawns;
|
||||
int r, shelter = 0;
|
||||
Value safety = MaxSafetyBonus;
|
||||
Bitboard b = pos.pieces(PAWN) & (in_front_bb(Us, ksq) | rank_bb(ksq));
|
||||
Bitboard ourPawns = b & pos.pieces(Us) & ~rank_bb(ksq);
|
||||
Bitboard theirPawns = b & pos.pieces(Them);
|
||||
Rank rkUs, rkThem;
|
||||
File kf = file_of(ksq);
|
||||
|
||||
if (relative_rank(Us, ksq) <= RANK_4)
|
||||
kf = (kf == FILE_A) ? kf++ : (kf == FILE_H) ? kf-- : kf;
|
||||
|
||||
for (int f = kf - 1; f <= kf + 1; f++)
|
||||
{
|
||||
pawns = pos.pieces(PAWN, Us) & this_and_neighboring_files_bb(ksq);
|
||||
r = ksq & (7 << 3);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
r += Shift;
|
||||
shelter += BitCount8Bit[(pawns >> r) & 0xFF] * (64 >> i);
|
||||
}
|
||||
// Shelter penalty is higher for the pawn in front of the king
|
||||
b = ourPawns & FileBB[f];
|
||||
rkUs = b ? rank_of(Us == WHITE ? lsb(b) : ~msb(b)) : RANK_1;
|
||||
safety -= ShelterWeakness[f != kf][rkUs];
|
||||
|
||||
// Storm danger is smaller if enemy pawn is blocked
|
||||
b = theirPawns & FileBB[f];
|
||||
rkThem = b ? rank_of(Us == WHITE ? lsb(b) : ~msb(b)) : RANK_1;
|
||||
safety -= StormDanger[rkThem == rkUs + 1][rkThem];
|
||||
}
|
||||
|
||||
return safety;
|
||||
}
|
||||
|
||||
|
||||
/// PawnEntry::update_safety() calculates and caches a bonus for king safety. It is
|
||||
/// called only when king square changes, about 20% of total king_safety() calls.
|
||||
|
||||
template<Color Us>
|
||||
Score PawnEntry::update_safety(const Position& pos, Square ksq) {
|
||||
|
||||
kingSquares[Us] = ksq;
|
||||
kingShelters[Us] = make_score(shelter, 0);
|
||||
return kingShelters[Us];
|
||||
castleRights[Us] = pos.can_castle(Us);
|
||||
minKPdistance[Us] = 0;
|
||||
|
||||
Bitboard pawns = pos.pieces(Us, PAWN);
|
||||
if (pawns)
|
||||
while (!(DistanceRingsBB[ksq][minKPdistance[Us]++] & pawns)) {}
|
||||
|
||||
if (relative_rank(Us, ksq) > RANK_4)
|
||||
return kingSafety[Us] = make_score(0, -16 * minKPdistance[Us]);
|
||||
|
||||
Value bonus = shelter_storm<Us>(pos, ksq);
|
||||
|
||||
// If we can castle use the bonus after the castle if is bigger
|
||||
if (pos.can_castle(make_castle_right(Us, KING_SIDE)))
|
||||
bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_G1)));
|
||||
|
||||
if (pos.can_castle(make_castle_right(Us, QUEEN_SIDE)))
|
||||
bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_C1)));
|
||||
|
||||
return kingSafety[Us] = make_score(bonus, -16 * minKPdistance[Us]);
|
||||
}
|
||||
|
||||
// Explicit template instantiation
|
||||
template Score PawnInfo::updateShelter<WHITE>(const Position& pos, Square ksq);
|
||||
template Score PawnInfo::updateShelter<BLACK>(const Position& pos, Square ksq);
|
||||
template Score PawnEntry::update_safety<WHITE>(const Position& pos, Square ksq);
|
||||
template Score PawnEntry::update_safety<BLACK>(const Position& pos, Square ksq);
|
||||
|
||||
60
src/pawns.h
60
src/pawns.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,22 +20,22 @@
|
||||
#if !defined(PAWNS_H_INCLUDED)
|
||||
#define PAWNS_H_INCLUDED
|
||||
|
||||
#include "misc.h"
|
||||
#include "position.h"
|
||||
#include "tt.h"
|
||||
#include "types.h"
|
||||
|
||||
const int PawnTableSize = 16384;
|
||||
|
||||
/// PawnInfo is a class which contains various information about a pawn
|
||||
/// PawnEntry is a class which contains various information about a pawn
|
||||
/// structure. Currently, it only includes a middle game and an end game
|
||||
/// pawn structure evaluation, and a bitboard of passed pawns. We may want
|
||||
/// to add further information in the future. A lookup to the pawn hash table
|
||||
/// (performed by calling the get_pawn_info method in a PawnInfoTable object)
|
||||
/// returns a pointer to a PawnInfo object.
|
||||
/// to add further information in the future. A lookup to the pawn hash
|
||||
/// table (performed by calling the probe method in a PawnTable object)
|
||||
/// returns a pointer to a PawnEntry object.
|
||||
|
||||
class PawnInfo {
|
||||
class PawnEntry {
|
||||
|
||||
friend class PawnInfoTable;
|
||||
friend struct PawnTable;
|
||||
|
||||
public:
|
||||
Score pawns_value() const;
|
||||
@@ -46,62 +46,70 @@ public:
|
||||
int has_open_file_to_right(Color c, File f) const;
|
||||
|
||||
template<Color Us>
|
||||
Score king_shelter(const Position& pos, Square ksq);
|
||||
Score king_safety(const Position& pos, Square ksq);
|
||||
|
||||
private:
|
||||
template<Color Us>
|
||||
Score updateShelter(const Position& pos, Square ksq);
|
||||
Score update_safety(const Position& pos, Square ksq);
|
||||
|
||||
template<Color Us>
|
||||
Value shelter_storm(const Position& pos, Square ksq);
|
||||
|
||||
Key key;
|
||||
Bitboard passedPawns[2];
|
||||
Bitboard pawnAttacks[2];
|
||||
Square kingSquares[2];
|
||||
int minKPdistance[2];
|
||||
int castleRights[2];
|
||||
Score value;
|
||||
int halfOpenFiles[2];
|
||||
Score kingShelters[2];
|
||||
Score kingSafety[2];
|
||||
};
|
||||
|
||||
|
||||
/// The PawnInfoTable class represents a pawn hash table. The most important
|
||||
/// method is get_pawn_info, which returns a pointer to a PawnInfo object.
|
||||
/// The PawnTable class represents a pawn hash table. The most important
|
||||
/// method is probe, which returns a pointer to a PawnEntry object.
|
||||
|
||||
class PawnInfoTable : public SimpleHash<PawnInfo, PawnTableSize> {
|
||||
public:
|
||||
PawnInfo* get_pawn_info(const Position& pos) const;
|
||||
struct PawnTable {
|
||||
|
||||
PawnEntry* probe(const Position& pos);
|
||||
|
||||
private:
|
||||
template<Color Us>
|
||||
static Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi);
|
||||
static Score evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||
Bitboard theirPawns, PawnEntry* e);
|
||||
|
||||
HashTable<PawnEntry, PawnTableSize> entries;
|
||||
};
|
||||
|
||||
|
||||
inline Score PawnInfo::pawns_value() const {
|
||||
inline Score PawnEntry::pawns_value() const {
|
||||
return value;
|
||||
}
|
||||
|
||||
inline Bitboard PawnInfo::pawn_attacks(Color c) const {
|
||||
inline Bitboard PawnEntry::pawn_attacks(Color c) const {
|
||||
return pawnAttacks[c];
|
||||
}
|
||||
|
||||
inline Bitboard PawnInfo::passed_pawns(Color c) const {
|
||||
inline Bitboard PawnEntry::passed_pawns(Color c) const {
|
||||
return passedPawns[c];
|
||||
}
|
||||
|
||||
inline int PawnInfo::file_is_half_open(Color c, File f) const {
|
||||
inline int PawnEntry::file_is_half_open(Color c, File f) const {
|
||||
return halfOpenFiles[c] & (1 << int(f));
|
||||
}
|
||||
|
||||
inline int PawnInfo::has_open_file_to_left(Color c, File f) const {
|
||||
inline int PawnEntry::has_open_file_to_left(Color c, File f) const {
|
||||
return halfOpenFiles[c] & ((1 << int(f)) - 1);
|
||||
}
|
||||
|
||||
inline int PawnInfo::has_open_file_to_right(Color c, File f) const {
|
||||
inline int PawnEntry::has_open_file_to_right(Color c, File f) const {
|
||||
return halfOpenFiles[c] & ~((1 << int(f+1)) - 1);
|
||||
}
|
||||
|
||||
template<Color Us>
|
||||
inline Score PawnInfo::king_shelter(const Position& pos, Square ksq) {
|
||||
return kingSquares[Us] == ksq ? kingShelters[Us] : updateShelter<Us>(pos, ksq);
|
||||
inline Score PawnEntry::king_safety(const Position& pos, Square ksq) {
|
||||
return kingSquares[Us] == ksq && castleRights[Us] == pos.can_castle(Us)
|
||||
? kingSafety[Us] : update_safety<Us>(pos, ksq);
|
||||
}
|
||||
|
||||
#endif // !defined(PAWNS_H_INCLUDED)
|
||||
|
||||
109
src/platform.h
Normal file
109
src/platform.h
Normal file
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Stockfish is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#if !defined(PLATFORM_H_INCLUDED)
|
||||
#define PLATFORM_H_INCLUDED
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
|
||||
// Disable some silly and noisy warning from MSVC compiler
|
||||
#pragma warning(disable: 4127) // Conditional expression is constant
|
||||
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
|
||||
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
|
||||
#pragma warning(disable: 4996) // Function _ftime() may be unsafe
|
||||
|
||||
// MSVC does not support <inttypes.h>
|
||||
typedef signed __int8 int8_t;
|
||||
typedef unsigned __int8 uint8_t;
|
||||
typedef signed __int16 int16_t;
|
||||
typedef unsigned __int16 uint16_t;
|
||||
typedef signed __int32 int32_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
typedef signed __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
|
||||
#else
|
||||
# include <inttypes.h>
|
||||
#endif
|
||||
|
||||
#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
|
||||
|
||||
# include <sys/time.h>
|
||||
typedef timeval sys_time_t;
|
||||
|
||||
inline void system_time(sys_time_t* t) { gettimeofday(t, NULL); }
|
||||
inline int64_t time_to_msec(const sys_time_t& t) { return t.tv_sec * 1000LL + t.tv_usec / 1000; }
|
||||
|
||||
# include <pthread.h>
|
||||
typedef pthread_mutex_t Lock;
|
||||
typedef pthread_cond_t WaitCondition;
|
||||
typedef pthread_t NativeHandle;
|
||||
typedef void*(*pt_start_fn)(void*);
|
||||
|
||||
# define lock_init(x) pthread_mutex_init(&(x), NULL)
|
||||
# define lock_grab(x) pthread_mutex_lock(&(x))
|
||||
# define lock_release(x) pthread_mutex_unlock(&(x))
|
||||
# define lock_destroy(x) pthread_mutex_destroy(&(x))
|
||||
# define cond_destroy(x) pthread_cond_destroy(&(x))
|
||||
# define cond_init(x) pthread_cond_init(&(x), NULL)
|
||||
# define cond_signal(x) pthread_cond_signal(&(x))
|
||||
# define cond_wait(x,y) pthread_cond_wait(&(x),&(y))
|
||||
# define cond_timedwait(x,y,z) pthread_cond_timedwait(&(x),&(y),z)
|
||||
# define thread_create(x,f,t) !pthread_create(&(x),NULL,(pt_start_fn)f,t)
|
||||
# define thread_join(x) pthread_join(x, NULL)
|
||||
|
||||
#else // Windows and MinGW
|
||||
|
||||
# include <sys/timeb.h>
|
||||
typedef _timeb sys_time_t;
|
||||
|
||||
inline void system_time(sys_time_t* t) { _ftime(t); }
|
||||
inline int64_t time_to_msec(const sys_time_t& t) { return t.time * 1000LL + t.millitm; }
|
||||
|
||||
#if !defined(NOMINMAX)
|
||||
# define NOMINMAX // disable macros min() and max()
|
||||
#endif
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#undef NOMINMAX
|
||||
|
||||
// We use critical sections on Windows to support Windows XP and older versions,
|
||||
// unfortunatly cond_wait() is racy between lock_release() and WaitForSingleObject()
|
||||
// but apart from this they have the same speed performance of SRW locks.
|
||||
typedef CRITICAL_SECTION Lock;
|
||||
typedef HANDLE WaitCondition;
|
||||
typedef HANDLE NativeHandle;
|
||||
|
||||
# define lock_init(x) InitializeCriticalSection(&(x))
|
||||
# define lock_grab(x) EnterCriticalSection(&(x))
|
||||
# define lock_release(x) LeaveCriticalSection(&(x))
|
||||
# define lock_destroy(x) DeleteCriticalSection(&(x))
|
||||
# define cond_init(x) { x = CreateEvent(0, FALSE, FALSE, 0); }
|
||||
# define cond_destroy(x) CloseHandle(x)
|
||||
# define cond_signal(x) SetEvent(x)
|
||||
# define cond_wait(x,y) { lock_release(y); WaitForSingleObject(x, INFINITE); lock_grab(y); }
|
||||
# define cond_timedwait(x,y,z) { lock_release(y); WaitForSingleObject(x,z); lock_grab(y); }
|
||||
# define thread_create(x,f,t) (x = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)f,t,0,NULL), x != NULL)
|
||||
# define thread_join(x) { WaitForSingleObject(x, INFINITE); CloseHandle(x); }
|
||||
|
||||
#endif
|
||||
|
||||
#endif // !defined(PLATFORM_H_INCLUDED)
|
||||
2236
src/position.cpp
2236
src/position.cpp
File diff suppressed because it is too large
Load Diff
467
src/position.h
467
src/position.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,44 +20,25 @@
|
||||
#if !defined(POSITION_H_INCLUDED)
|
||||
#define POSITION_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "move.h"
|
||||
#include "types.h"
|
||||
|
||||
/// Maximum number of plies per game (220 should be enough, because the
|
||||
/// maximum search depth is 100, and during position setup we reset the
|
||||
/// move counter for every non-reversible move).
|
||||
const int MaxGameLength = 220;
|
||||
|
||||
/// The checkInfo struct is initialized at c'tor time and keeps info used
|
||||
/// to detect if a move gives check.
|
||||
class Position;
|
||||
|
||||
/// struct checkInfo is initialized at c'tor time and keeps
|
||||
/// info used to detect if a move gives check.
|
||||
class Thread;
|
||||
|
||||
struct CheckInfo {
|
||||
|
||||
explicit CheckInfo(const Position&);
|
||||
explicit CheckInfo(const Position&);
|
||||
|
||||
Bitboard dcCandidates;
|
||||
Bitboard checkSq[8];
|
||||
Square ksq;
|
||||
};
|
||||
|
||||
/// Castle rights, encoded as bit fields
|
||||
|
||||
enum CastleRights {
|
||||
CASTLES_NONE = 0,
|
||||
WHITE_OO = 1,
|
||||
BLACK_OO = 2,
|
||||
WHITE_OOO = 4,
|
||||
BLACK_OOO = 8,
|
||||
ALL_CASTLES = 15
|
||||
};
|
||||
|
||||
/// Game phase
|
||||
enum Phase {
|
||||
PHASE_ENDGAME = 0,
|
||||
PHASE_MIDGAME = 128
|
||||
Bitboard dcCandidates;
|
||||
Bitboard pinned;
|
||||
Bitboard checkSq[8];
|
||||
Square ksq;
|
||||
};
|
||||
|
||||
|
||||
@@ -68,17 +49,25 @@ enum Phase {
|
||||
|
||||
struct StateInfo {
|
||||
Key pawnKey, materialKey;
|
||||
int castleRights, rule50, gamePly, pliesFromNull;
|
||||
Square epSquare;
|
||||
Score value;
|
||||
Value npMaterial[2];
|
||||
int castleRights, rule50, pliesFromNull;
|
||||
Score psqScore;
|
||||
Square epSquare;
|
||||
|
||||
PieceType capturedType;
|
||||
Key key;
|
||||
Bitboard checkersBB;
|
||||
PieceType capturedType;
|
||||
StateInfo* previous;
|
||||
};
|
||||
|
||||
struct ReducedStateInfo {
|
||||
Key pawnKey, materialKey;
|
||||
Value npMaterial[2];
|
||||
int castleRights, rule50, pliesFromNull;
|
||||
Score psqScore;
|
||||
Square epSquare;
|
||||
};
|
||||
|
||||
|
||||
/// The position data structure. A position consists of the following data:
|
||||
///
|
||||
@@ -103,172 +92,112 @@ struct StateInfo {
|
||||
/// * A counter for detecting 50 move rule draws.
|
||||
|
||||
class Position {
|
||||
|
||||
Position(); // No default or copy c'tor allowed
|
||||
Position(const Position& pos);
|
||||
|
||||
public:
|
||||
enum GamePhase {
|
||||
MidGame,
|
||||
EndGame
|
||||
};
|
||||
|
||||
// Constructors
|
||||
Position(const Position& pos, int threadID);
|
||||
Position(const std::string& fen, bool isChess960, int threadID);
|
||||
Position() {}
|
||||
Position(const Position& p, Thread* t) { *this = p; thisThread = t; }
|
||||
Position(const std::string& f, bool c960, Thread* t) { from_fen(f, c960, t); }
|
||||
Position& operator=(const Position&);
|
||||
|
||||
// Text input/output
|
||||
void from_fen(const std::string& fen, bool isChess960);
|
||||
void from_fen(const std::string& fen, bool isChess960, Thread* th);
|
||||
const std::string to_fen() const;
|
||||
void print(Move m = MOVE_NONE) const;
|
||||
|
||||
// Copying
|
||||
void flip();
|
||||
|
||||
// The piece on a given square
|
||||
Piece piece_on(Square s) const;
|
||||
PieceType type_of_piece_on(Square s) const;
|
||||
Color color_of_piece_on(Square s) const;
|
||||
bool square_is_empty(Square s) const;
|
||||
bool square_is_occupied(Square s) const;
|
||||
Value midgame_value_of_piece_on(Square s) const;
|
||||
Value endgame_value_of_piece_on(Square s) const;
|
||||
|
||||
// Side to move
|
||||
Color side_to_move() const;
|
||||
|
||||
// Bitboard representation of the position
|
||||
Bitboard empty_squares() const;
|
||||
Bitboard occupied_squares() const;
|
||||
Bitboard pieces_of_color(Color c) const;
|
||||
// Position representation
|
||||
Bitboard pieces() const;
|
||||
Bitboard pieces(PieceType pt) const;
|
||||
Bitboard pieces(PieceType pt, Color c) const;
|
||||
Bitboard pieces(PieceType pt1, PieceType pt2) const;
|
||||
Bitboard pieces(PieceType pt1, PieceType pt2, Color c) const;
|
||||
|
||||
// Number of pieces of each color and type
|
||||
Bitboard pieces(Color c) const;
|
||||
Bitboard pieces(Color c, PieceType pt) const;
|
||||
Bitboard pieces(Color c, PieceType pt1, PieceType pt2) const;
|
||||
Piece piece_on(Square s) const;
|
||||
Square king_square(Color c) const;
|
||||
Square ep_square() const;
|
||||
bool is_empty(Square s) const;
|
||||
const Square* piece_list(Color c, PieceType pt) const;
|
||||
int piece_count(Color c, PieceType pt) const;
|
||||
|
||||
// The en passant square
|
||||
Square ep_square() const;
|
||||
// Castling
|
||||
int can_castle(CastleRight f) const;
|
||||
int can_castle(Color c) const;
|
||||
bool castle_impeded(Color c, CastlingSide s) const;
|
||||
Square castle_rook_square(Color c, CastlingSide s) const;
|
||||
|
||||
// Current king position for each color
|
||||
Square king_square(Color c) const;
|
||||
|
||||
// Castling rights
|
||||
bool can_castle_kingside(Color c) const;
|
||||
bool can_castle_queenside(Color c) const;
|
||||
bool can_castle(Color c) const;
|
||||
Square initial_kr_square(Color c) const;
|
||||
Square initial_qr_square(Color c) const;
|
||||
|
||||
// Bitboards for pinned pieces and discovered check candidates
|
||||
Bitboard discovered_check_candidates(Color c) const;
|
||||
Bitboard pinned_pieces(Color c) const;
|
||||
|
||||
// Checking pieces and under check information
|
||||
Bitboard checkers() const;
|
||||
// Checking
|
||||
bool in_check() const;
|
||||
Bitboard checkers() const;
|
||||
Bitboard discovered_check_candidates() const;
|
||||
Bitboard pinned_pieces() const;
|
||||
|
||||
// Piece lists
|
||||
Square piece_list(Color c, PieceType pt, int index) const;
|
||||
const Square* piece_list_begin(Color c, PieceType pt) const;
|
||||
|
||||
// Information about attacks to or from a given square
|
||||
// Attacks to/from a given square
|
||||
Bitboard attackers_to(Square s) const;
|
||||
Bitboard attackers_to(Square s, Bitboard occ) const;
|
||||
Bitboard attacks_from(Piece p, Square s) const;
|
||||
static Bitboard attacks_from(Piece p, Square s, Bitboard occ);
|
||||
template<PieceType> Bitboard attacks_from(Square s) const;
|
||||
template<PieceType> Bitboard attacks_from(Square s, Color c) const;
|
||||
|
||||
// Properties of moves
|
||||
bool pl_move_is_legal(Move m, Bitboard pinned) const;
|
||||
bool pl_move_is_evasion(Move m, Bitboard pinned) const;
|
||||
bool move_is_legal(const Move m) const;
|
||||
bool move_is_legal(const Move m, Bitboard pinned) const;
|
||||
bool move_gives_check(Move m) const;
|
||||
bool move_gives_check(Move m, const CheckInfo& ci) const;
|
||||
bool move_is_capture(Move m) const;
|
||||
bool move_is_capture_or_promotion(Move m) const;
|
||||
bool move_is_passed_pawn_push(Move m) const;
|
||||
bool move_attacks_square(Move m, Square s) const;
|
||||
|
||||
// Piece captured with previous moves
|
||||
bool move_is_legal(const Move m) const;
|
||||
bool pl_move_is_legal(Move m, Bitboard pinned) const;
|
||||
bool is_pseudo_legal(const Move m) const;
|
||||
bool is_capture(Move m) const;
|
||||
bool is_capture_or_promotion(Move m) const;
|
||||
bool is_passed_pawn_push(Move m) const;
|
||||
Piece piece_moved(Move m) const;
|
||||
PieceType captured_piece_type() const;
|
||||
|
||||
// Information about pawns
|
||||
// Piece specific
|
||||
bool pawn_is_passed(Color c, Square s) const;
|
||||
|
||||
// Weak squares
|
||||
bool square_is_weak(Square s, Color c) const;
|
||||
bool pawn_on_7th(Color c) const;
|
||||
bool opposite_bishops() const;
|
||||
bool bishop_pair(Color c) const;
|
||||
|
||||
// Doing and undoing moves
|
||||
void do_setup_move(Move m);
|
||||
void do_move(Move m, StateInfo& st);
|
||||
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
|
||||
void undo_move(Move m);
|
||||
void do_null_move(StateInfo& st);
|
||||
void undo_null_move();
|
||||
template<bool Do> void do_null_move(StateInfo& st);
|
||||
|
||||
// Static exchange evaluation
|
||||
int see(Square from, Square to) const;
|
||||
int see(Move m) const;
|
||||
int see_sign(Move m) const;
|
||||
|
||||
// Accessing hash keys
|
||||
Key get_key() const;
|
||||
Key get_exclusion_key() const;
|
||||
Key get_pawn_key() const;
|
||||
Key get_material_key() const;
|
||||
Key key() const;
|
||||
Key exclusion_key() const;
|
||||
Key pawn_key() const;
|
||||
Key material_key() const;
|
||||
|
||||
// Incremental evaluation
|
||||
Score value() const;
|
||||
// Incremental piece-square evaluation
|
||||
Score psq_score() const;
|
||||
Score psq_delta(Piece p, Square from, Square to) const;
|
||||
Value non_pawn_material(Color c) const;
|
||||
static Score pst_delta(Piece piece, Square from, Square to);
|
||||
|
||||
// Game termination checks
|
||||
bool is_mate() const;
|
||||
bool is_draw() const;
|
||||
|
||||
// Number of plies from starting position
|
||||
int startpos_ply_counter() const;
|
||||
|
||||
// Other properties of the position
|
||||
bool opposite_colored_bishops() const;
|
||||
bool has_pawn_on_7th(Color c) const;
|
||||
Color side_to_move() const;
|
||||
int startpos_ply_counter() const;
|
||||
bool is_chess960() const;
|
||||
|
||||
// Current thread ID searching on the position
|
||||
int thread() const;
|
||||
|
||||
Thread* this_thread() const;
|
||||
int64_t nodes_searched() const;
|
||||
void set_nodes_searched(int64_t n);
|
||||
template<bool SkipRepetition> bool is_draw() const;
|
||||
|
||||
// Position consistency check, for debugging
|
||||
bool is_ok(int* failedStep = NULL) const;
|
||||
|
||||
// Static member functions
|
||||
static void init_zobrist();
|
||||
static void init_piece_square_tables();
|
||||
bool pos_is_ok(int* failedStep = NULL) const;
|
||||
void flip();
|
||||
|
||||
private:
|
||||
|
||||
// Initialization helper functions (used while setting up a position)
|
||||
// Initialization helpers (used while setting up a position)
|
||||
void clear();
|
||||
void detach();
|
||||
void put_piece(Piece p, Square s);
|
||||
void do_allow_oo(Color c);
|
||||
void do_allow_ooo(Color c);
|
||||
bool set_castling_rights(char token);
|
||||
void set_castle_right(Color c, Square rfrom);
|
||||
|
||||
// Helper functions for doing and undoing moves
|
||||
void do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep);
|
||||
void do_castle_move(Move m);
|
||||
void undo_castle_move(Move m);
|
||||
void find_checkers();
|
||||
|
||||
template<bool FindPinned>
|
||||
Bitboard hidden_checkers(Color c) const;
|
||||
// Helper template functions
|
||||
template<bool Do> void do_castle_move(Move m);
|
||||
template<bool FindPinned> Bitboard hidden_checkers() const;
|
||||
|
||||
// Computing hash keys from scratch (for initialization and debugging)
|
||||
Key compute_key() const;
|
||||
@@ -276,45 +205,28 @@ private:
|
||||
Key compute_material_key() const;
|
||||
|
||||
// Computing incremental evaluation scores and material counts
|
||||
static Score pst(Color c, PieceType pt, Square s);
|
||||
Score compute_value() const;
|
||||
Score compute_psq_score() const;
|
||||
Value compute_non_pawn_material(Color c) const;
|
||||
|
||||
// Board
|
||||
Piece board[64];
|
||||
|
||||
// Bitboards
|
||||
Bitboard byTypeBB[8], byColorBB[2];
|
||||
|
||||
// Piece counts
|
||||
int pieceCount[2][8]; // [color][pieceType]
|
||||
|
||||
// Piece lists
|
||||
Square pieceList[2][8][16]; // [color][pieceType][index]
|
||||
int index[64]; // [square]
|
||||
// Board and pieces
|
||||
Piece board[64]; // [square]
|
||||
Bitboard byTypeBB[8]; // [pieceType]
|
||||
Bitboard byColorBB[2]; // [color]
|
||||
int pieceCount[2][8]; // [color][pieceType]
|
||||
Square pieceList[2][8][16]; // [color][pieceType][index]
|
||||
int index[64]; // [square]
|
||||
|
||||
// Other info
|
||||
Color sideToMove;
|
||||
Key history[MaxGameLength];
|
||||
int castleRightsMask[64];
|
||||
int castleRightsMask[64]; // [square]
|
||||
Square castleRookSquare[2][2]; // [color][side]
|
||||
Bitboard castlePath[2][2]; // [color][side]
|
||||
StateInfo startState;
|
||||
File initialKFile, initialKRFile, initialQRFile;
|
||||
bool chess960;
|
||||
int startPosPlyCounter;
|
||||
int threadID;
|
||||
int64_t nodes;
|
||||
int startPosPly;
|
||||
Color sideToMove;
|
||||
Thread* thisThread;
|
||||
StateInfo* st;
|
||||
|
||||
// Static variables
|
||||
static Key zobrist[2][8][64];
|
||||
static Key zobEp[64];
|
||||
static Key zobCastle[16];
|
||||
static Key zobSideToMove;
|
||||
static Score PieceSquareTable[16][64];
|
||||
static Key zobExclusion;
|
||||
static const Value seeValues[8];
|
||||
static const Value PieceValueMidgame[17];
|
||||
static const Value PieceValueEndgame[17];
|
||||
int chess960;
|
||||
};
|
||||
|
||||
inline int64_t Position::nodes_searched() const {
|
||||
@@ -329,71 +241,47 @@ inline Piece Position::piece_on(Square s) const {
|
||||
return board[s];
|
||||
}
|
||||
|
||||
inline Color Position::color_of_piece_on(Square s) const {
|
||||
return color_of_piece(piece_on(s));
|
||||
inline Piece Position::piece_moved(Move m) const {
|
||||
return board[from_sq(m)];
|
||||
}
|
||||
|
||||
inline PieceType Position::type_of_piece_on(Square s) const {
|
||||
return type_of_piece(piece_on(s));
|
||||
}
|
||||
|
||||
inline bool Position::square_is_empty(Square s) const {
|
||||
return piece_on(s) == PIECE_NONE;
|
||||
}
|
||||
|
||||
inline bool Position::square_is_occupied(Square s) const {
|
||||
return !square_is_empty(s);
|
||||
}
|
||||
|
||||
inline Value Position::midgame_value_of_piece_on(Square s) const {
|
||||
return PieceValueMidgame[piece_on(s)];
|
||||
}
|
||||
|
||||
inline Value Position::endgame_value_of_piece_on(Square s) const {
|
||||
return PieceValueEndgame[piece_on(s)];
|
||||
inline bool Position::is_empty(Square s) const {
|
||||
return board[s] == NO_PIECE;
|
||||
}
|
||||
|
||||
inline Color Position::side_to_move() const {
|
||||
return sideToMove;
|
||||
}
|
||||
|
||||
inline Bitboard Position::occupied_squares() const {
|
||||
return byTypeBB[0];
|
||||
}
|
||||
|
||||
inline Bitboard Position::empty_squares() const {
|
||||
return ~occupied_squares();
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces_of_color(Color c) const {
|
||||
return byColorBB[c];
|
||||
inline Bitboard Position::pieces() const {
|
||||
return byTypeBB[ALL_PIECES];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(PieceType pt) const {
|
||||
return byTypeBB[pt];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(PieceType pt, Color c) const {
|
||||
return byTypeBB[pt] & byColorBB[c];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
|
||||
return byTypeBB[pt1] | byTypeBB[pt2];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2, Color c) const {
|
||||
return (byTypeBB[pt1] | byTypeBB[pt2]) & byColorBB[c];
|
||||
inline Bitboard Position::pieces(Color c) const {
|
||||
return byColorBB[c];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(Color c, PieceType pt) const {
|
||||
return byColorBB[c] & byTypeBB[pt];
|
||||
}
|
||||
|
||||
inline Bitboard Position::pieces(Color c, PieceType pt1, PieceType pt2) const {
|
||||
return byColorBB[c] & (byTypeBB[pt1] | byTypeBB[pt2]);
|
||||
}
|
||||
|
||||
inline int Position::piece_count(Color c, PieceType pt) const {
|
||||
return pieceCount[c][pt];
|
||||
}
|
||||
|
||||
inline Square Position::piece_list(Color c, PieceType pt, int idx) const {
|
||||
return pieceList[c][pt][idx];
|
||||
}
|
||||
|
||||
inline const Square* Position::piece_list_begin(Color c, PieceType pt) const {
|
||||
inline const Square* Position::piece_list(Color c, PieceType pt) const {
|
||||
return pieceList[c][pt];
|
||||
}
|
||||
|
||||
@@ -405,24 +293,28 @@ inline Square Position::king_square(Color c) const {
|
||||
return pieceList[c][KING][0];
|
||||
}
|
||||
|
||||
inline bool Position::can_castle_kingside(Color side) const {
|
||||
return st->castleRights & (1+int(side));
|
||||
inline int Position::can_castle(CastleRight f) const {
|
||||
return st->castleRights & f;
|
||||
}
|
||||
|
||||
inline bool Position::can_castle_queenside(Color side) const {
|
||||
return st->castleRights & (4+4*int(side));
|
||||
inline int Position::can_castle(Color c) const {
|
||||
return st->castleRights & ((WHITE_OO | WHITE_OOO) << (2 * c));
|
||||
}
|
||||
|
||||
inline bool Position::can_castle(Color side) const {
|
||||
return can_castle_kingside(side) || can_castle_queenside(side);
|
||||
inline bool Position::castle_impeded(Color c, CastlingSide s) const {
|
||||
return byTypeBB[ALL_PIECES] & castlePath[c][s];
|
||||
}
|
||||
|
||||
inline Square Position::initial_kr_square(Color c) const {
|
||||
return relative_square(c, make_square(initialKRFile, RANK_1));
|
||||
inline Square Position::castle_rook_square(Color c, CastlingSide s) const {
|
||||
return castleRookSquare[c][s];
|
||||
}
|
||||
|
||||
inline Square Position::initial_qr_square(Color c) const {
|
||||
return relative_square(c, make_square(initialQRFile, RANK_1));
|
||||
template<PieceType Pt>
|
||||
inline Bitboard Position::attacks_from(Square s) const {
|
||||
|
||||
return Pt == BISHOP || Pt == ROOK ? attacks_bb<Pt>(s, pieces())
|
||||
: Pt == QUEEN ? attacks_from<ROOK>(s) | attacks_from<BISHOP>(s)
|
||||
: StepAttacksBB[Pt][s];
|
||||
}
|
||||
|
||||
template<>
|
||||
@@ -430,24 +322,12 @@ inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
|
||||
return StepAttacksBB[make_piece(c, PAWN)][s];
|
||||
}
|
||||
|
||||
template<PieceType Piece> // Knight and King and white pawns
|
||||
inline Bitboard Position::attacks_from(Square s) const {
|
||||
return StepAttacksBB[Piece][s];
|
||||
inline Bitboard Position::attacks_from(Piece p, Square s) const {
|
||||
return attacks_from(p, s, byTypeBB[ALL_PIECES]);
|
||||
}
|
||||
|
||||
template<>
|
||||
inline Bitboard Position::attacks_from<BISHOP>(Square s) const {
|
||||
return bishop_attacks_bb(s, occupied_squares());
|
||||
}
|
||||
|
||||
template<>
|
||||
inline Bitboard Position::attacks_from<ROOK>(Square s) const {
|
||||
return rook_attacks_bb(s, occupied_squares());
|
||||
}
|
||||
|
||||
template<>
|
||||
inline Bitboard Position::attacks_from<QUEEN>(Square s) const {
|
||||
return attacks_from<ROOK>(s) | attacks_from<BISHOP>(s);
|
||||
inline Bitboard Position::attackers_to(Square s) const {
|
||||
return attackers_to(s, byTypeBB[ALL_PIECES]);
|
||||
}
|
||||
|
||||
inline Bitboard Position::checkers() const {
|
||||
@@ -455,100 +335,99 @@ inline Bitboard Position::checkers() const {
|
||||
}
|
||||
|
||||
inline bool Position::in_check() const {
|
||||
return st->checkersBB != EmptyBoardBB;
|
||||
return st->checkersBB != 0;
|
||||
}
|
||||
|
||||
inline Bitboard Position::discovered_check_candidates() const {
|
||||
return hidden_checkers<false>();
|
||||
}
|
||||
|
||||
inline Bitboard Position::pinned_pieces() const {
|
||||
return hidden_checkers<true>();
|
||||
}
|
||||
|
||||
inline bool Position::pawn_is_passed(Color c, Square s) const {
|
||||
return !(pieces(PAWN, opposite_color(c)) & passed_pawn_mask(c, s));
|
||||
return !(pieces(~c, PAWN) & passed_pawn_mask(c, s));
|
||||
}
|
||||
|
||||
inline bool Position::square_is_weak(Square s, Color c) const {
|
||||
return !(pieces(PAWN, opposite_color(c)) & attack_span_mask(c, s));
|
||||
}
|
||||
|
||||
inline Key Position::get_key() const {
|
||||
inline Key Position::key() const {
|
||||
return st->key;
|
||||
}
|
||||
|
||||
inline Key Position::get_exclusion_key() const {
|
||||
return st->key ^ zobExclusion;
|
||||
inline Key Position::exclusion_key() const {
|
||||
return st->key ^ Zobrist::exclusion;
|
||||
}
|
||||
|
||||
inline Key Position::get_pawn_key() const {
|
||||
inline Key Position::pawn_key() const {
|
||||
return st->pawnKey;
|
||||
}
|
||||
|
||||
inline Key Position::get_material_key() const {
|
||||
inline Key Position::material_key() const {
|
||||
return st->materialKey;
|
||||
}
|
||||
|
||||
inline Score Position::pst(Color c, PieceType pt, Square s) {
|
||||
return PieceSquareTable[make_piece(c, pt)][s];
|
||||
inline Score Position::psq_delta(Piece p, Square from, Square to) const {
|
||||
return pieceSquareTable[p][to] - pieceSquareTable[p][from];
|
||||
}
|
||||
|
||||
inline Score Position::pst_delta(Piece piece, Square from, Square to) {
|
||||
return PieceSquareTable[piece][to] - PieceSquareTable[piece][from];
|
||||
}
|
||||
|
||||
inline Score Position::value() const {
|
||||
return st->value;
|
||||
inline Score Position::psq_score() const {
|
||||
return st->psqScore;
|
||||
}
|
||||
|
||||
inline Value Position::non_pawn_material(Color c) const {
|
||||
return st->npMaterial[c];
|
||||
}
|
||||
|
||||
inline bool Position::move_is_passed_pawn_push(Move m) const {
|
||||
inline bool Position::is_passed_pawn_push(Move m) const {
|
||||
|
||||
Color c = side_to_move();
|
||||
return piece_on(move_from(m)) == make_piece(c, PAWN)
|
||||
&& pawn_is_passed(c, move_to(m));
|
||||
return type_of(piece_moved(m)) == PAWN
|
||||
&& pawn_is_passed(sideToMove, to_sq(m));
|
||||
}
|
||||
|
||||
inline int Position::startpos_ply_counter() const {
|
||||
return startPosPlyCounter;
|
||||
return startPosPly + st->pliesFromNull; // HACK
|
||||
}
|
||||
|
||||
inline bool Position::opposite_colored_bishops() const {
|
||||
inline bool Position::opposite_bishops() const {
|
||||
|
||||
return piece_count(WHITE, BISHOP) == 1 && piece_count(BLACK, BISHOP) == 1
|
||||
&& opposite_color_squares(piece_list(WHITE, BISHOP, 0), piece_list(BLACK, BISHOP, 0));
|
||||
return pieceCount[WHITE][BISHOP] == 1
|
||||
&& pieceCount[BLACK][BISHOP] == 1
|
||||
&& opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
|
||||
}
|
||||
|
||||
inline bool Position::has_pawn_on_7th(Color c) const {
|
||||
return pieces(PAWN, c) & rank_bb(relative_rank(c, RANK_7));
|
||||
inline bool Position::bishop_pair(Color c) const {
|
||||
|
||||
return pieceCount[c][BISHOP] >= 2
|
||||
&& opposite_colors(pieceList[c][BISHOP][0], pieceList[c][BISHOP][1]);
|
||||
}
|
||||
|
||||
inline bool Position::pawn_on_7th(Color c) const {
|
||||
return pieces(c, PAWN) & rank_bb(relative_rank(c, RANK_7));
|
||||
}
|
||||
|
||||
inline bool Position::is_chess960() const {
|
||||
return chess960;
|
||||
}
|
||||
|
||||
inline bool Position::move_is_capture(Move m) const {
|
||||
inline bool Position::is_capture_or_promotion(Move m) const {
|
||||
|
||||
// Move must not be MOVE_NONE !
|
||||
return (m & (3 << 15)) ? !move_is_castle(m) : !square_is_empty(move_to(m));
|
||||
assert(is_ok(m));
|
||||
return type_of(m) ? type_of(m) != CASTLE : !is_empty(to_sq(m));
|
||||
}
|
||||
|
||||
inline bool Position::move_is_capture_or_promotion(Move m) const {
|
||||
inline bool Position::is_capture(Move m) const {
|
||||
|
||||
// Move must not be MOVE_NONE !
|
||||
return (m & (0x1F << 12)) ? !move_is_castle(m) : !square_is_empty(move_to(m));
|
||||
// Note that castle is coded as "king captures the rook"
|
||||
assert(is_ok(m));
|
||||
return (!is_empty(to_sq(m)) && type_of(m) != CASTLE) || type_of(m) == ENPASSANT;
|
||||
}
|
||||
|
||||
inline PieceType Position::captured_piece_type() const {
|
||||
return st->capturedType;
|
||||
}
|
||||
|
||||
inline int Position::thread() const {
|
||||
return threadID;
|
||||
}
|
||||
|
||||
inline void Position::do_allow_oo(Color c) {
|
||||
st->castleRights |= (1 + int(c));
|
||||
}
|
||||
|
||||
inline void Position::do_allow_ooo(Color c) {
|
||||
st->castleRights |= (4 + 4*int(c));
|
||||
inline Thread* Position::this_thread() const {
|
||||
return thisThread;
|
||||
}
|
||||
|
||||
#endif // !defined(POSITION_H_INCLUDED)
|
||||
|
||||
209
src/psqtab.h
209
src/psqtab.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -22,164 +22,77 @@
|
||||
|
||||
#include "types.h"
|
||||
|
||||
namespace {
|
||||
#define S(mg, eg) make_score(mg, eg)
|
||||
|
||||
////
|
||||
//// Constants modified by Joona Kiiski
|
||||
////
|
||||
|
||||
const Value MP = PawnValueMidgame;
|
||||
const Value MK = KnightValueMidgame;
|
||||
const Value MB = BishopValueMidgame;
|
||||
const Value MR = RookValueMidgame;
|
||||
const Value MQ = QueenValueMidgame;
|
||||
/// PSQT[PieceType][Square] contains Piece-Square scores. For each piece type on
|
||||
/// a given square a (midgame, endgame) score pair is assigned. PSQT is defined
|
||||
/// for white side, for black side the tables are symmetric.
|
||||
|
||||
const Value EP = PawnValueEndgame;
|
||||
const Value EK = KnightValueEndgame;
|
||||
const Value EB = BishopValueEndgame;
|
||||
const Value ER = RookValueEndgame;
|
||||
const Value EQ = QueenValueEndgame;
|
||||
|
||||
const int MgPST[][64] = {
|
||||
static const Score PSQT[][64] = {
|
||||
{ },
|
||||
{// Pawn
|
||||
// A B C D E F G H
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
|
||||
MP-28, MP-6, MP+ 9, MP+36, MP+36, MP+ 9, MP-6, MP-28,
|
||||
MP-28, MP-6, MP+17, MP+58, MP+58, MP+17, MP-6, MP-28,
|
||||
MP-28, MP-6, MP+17, MP+36, MP+36, MP+17, MP-6, MP-28,
|
||||
MP-28, MP-6, MP+ 9, MP+14, MP+14, MP+ 9, MP-6, MP-28,
|
||||
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
{ // Pawn
|
||||
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0),
|
||||
S(-28,-8), S(-6,-8), S( 4,-8), S(14,-8), S(14,-8), S( 4,-8), S(-6,-8), S(-28,-8),
|
||||
S(-28,-8), S(-6,-8), S( 9,-8), S(36,-8), S(36,-8), S( 9,-8), S(-6,-8), S(-28,-8),
|
||||
S(-28,-8), S(-6,-8), S(17,-8), S(58,-8), S(58,-8), S(17,-8), S(-6,-8), S(-28,-8),
|
||||
S(-28,-8), S(-6,-8), S(17,-8), S(36,-8), S(36,-8), S(17,-8), S(-6,-8), S(-28,-8),
|
||||
S(-28,-8), S(-6,-8), S( 9,-8), S(14,-8), S(14,-8), S( 9,-8), S(-6,-8), S(-28,-8),
|
||||
S(-28,-8), S(-6,-8), S( 4,-8), S(14,-8), S(14,-8), S( 4,-8), S(-6,-8), S(-28,-8),
|
||||
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0)
|
||||
},
|
||||
{// Knight
|
||||
// A B C D E F G H
|
||||
MK-135, MK-107, MK-80, MK-67, MK-67, MK-80, MK-107, MK-135,
|
||||
MK- 93, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK- 93,
|
||||
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
|
||||
MK- 25, MK+ 1, MK+27, MK+41, MK+41, MK+27, MK+ 1, MK- 25,
|
||||
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
|
||||
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
|
||||
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
|
||||
MK-193, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK-193
|
||||
{ // Knight
|
||||
S(-135,-104), S(-107,-79), S(-80,-55), S(-67,-42), S(-67,-42), S(-80,-55), S(-107,-79), S(-135,-104),
|
||||
S( -93, -79), S( -67,-55), S(-39,-30), S(-25,-17), S(-25,-17), S(-39,-30), S( -67,-55), S( -93, -79),
|
||||
S( -53, -55), S( -25,-30), S( 1, -6), S( 13, 5), S( 13, 5), S( 1, -6), S( -25,-30), S( -53, -55),
|
||||
S( -25, -42), S( 1,-17), S( 27, 5), S( 41, 18), S( 41, 18), S( 27, 5), S( 1,-17), S( -25, -42),
|
||||
S( -11, -42), S( 13,-17), S( 41, 5), S( 55, 18), S( 55, 18), S( 41, 5), S( 13,-17), S( -11, -42),
|
||||
S( -11, -55), S( 13,-30), S( 41, -6), S( 55, 5), S( 55, 5), S( 41, -6), S( 13,-30), S( -11, -55),
|
||||
S( -53, -79), S( -25,-55), S( 1,-30), S( 13,-17), S( 13,-17), S( 1,-30), S( -25,-55), S( -53, -79),
|
||||
S(-193,-104), S( -67,-79), S(-39,-55), S(-25,-42), S(-25,-42), S(-39,-55), S( -67,-79), S(-193,-104)
|
||||
},
|
||||
{// Bishop
|
||||
// A B C D E F G H
|
||||
MB-40, MB-40, MB-35, MB-30, MB-30, MB-35, MB-40, MB-40,
|
||||
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
|
||||
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
|
||||
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
|
||||
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
|
||||
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
|
||||
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
|
||||
MB-17, MB-17, MB-13, MB- 8, MB- 8, MB-13, MB-17, MB-17
|
||||
{ // Bishop
|
||||
S(-40,-59), S(-40,-42), S(-35,-35), S(-30,-26), S(-30,-26), S(-35,-35), S(-40,-42), S(-40,-59),
|
||||
S(-17,-42), S( 0,-26), S( -4,-18), S( 0,-11), S( 0,-11), S( -4,-18), S( 0,-26), S(-17,-42),
|
||||
S(-13,-35), S( -4,-18), S( 8,-11), S( 4, -4), S( 4, -4), S( 8,-11), S( -4,-18), S(-13,-35),
|
||||
S( -8,-26), S( 0,-11), S( 4, -4), S( 17, 4), S( 17, 4), S( 4, -4), S( 0,-11), S( -8,-26),
|
||||
S( -8,-26), S( 0,-11), S( 4, -4), S( 17, 4), S( 17, 4), S( 4, -4), S( 0,-11), S( -8,-26),
|
||||
S(-13,-35), S( -4,-18), S( 8,-11), S( 4, -4), S( 4, -4), S( 8,-11), S( -4,-18), S(-13,-35),
|
||||
S(-17,-42), S( 0,-26), S( -4,-18), S( 0,-11), S( 0,-11), S( -4,-18), S( 0,-26), S(-17,-42),
|
||||
S(-17,-59), S(-17,-42), S(-13,-35), S( -8,-26), S( -8,-26), S(-13,-35), S(-17,-42), S(-17,-59)
|
||||
},
|
||||
{// Rook
|
||||
// A B C D E F G H
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12
|
||||
{ // Rook
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
|
||||
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3)
|
||||
},
|
||||
{// Queen
|
||||
// A B C D E F G H
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8
|
||||
{ // Queen
|
||||
S(8,-80), S(8,-54), S(8,-42), S(8,-30), S(8,-30), S(8,-42), S(8,-54), S(8,-80),
|
||||
S(8,-54), S(8,-30), S(8,-18), S(8, -6), S(8, -6), S(8,-18), S(8,-30), S(8,-54),
|
||||
S(8,-42), S(8,-18), S(8, -6), S(8, 6), S(8, 6), S(8, -6), S(8,-18), S(8,-42),
|
||||
S(8,-30), S(8, -6), S(8, 6), S(8, 18), S(8, 18), S(8, 6), S(8, -6), S(8,-30),
|
||||
S(8,-30), S(8, -6), S(8, 6), S(8, 18), S(8, 18), S(8, 6), S(8, -6), S(8,-30),
|
||||
S(8,-42), S(8,-18), S(8, -6), S(8, 6), S(8, 6), S(8, -6), S(8,-18), S(8,-42),
|
||||
S(8,-54), S(8,-30), S(8,-18), S(8, -6), S(8, -6), S(8,-18), S(8,-30), S(8,-54),
|
||||
S(8,-80), S(8,-54), S(8,-42), S(8,-30), S(8,-30), S(8,-42), S(8,-54), S(8,-80)
|
||||
},
|
||||
{// King
|
||||
//A B C D E F G H
|
||||
287, 311, 262, 214, 214, 262, 311, 287,
|
||||
262, 287, 238, 190, 190, 238, 287, 262,
|
||||
214, 238, 190, 142, 142, 190, 238, 214,
|
||||
190, 214, 167, 119, 119, 167, 214, 190,
|
||||
167, 190, 142, 94, 94, 142, 190, 167,
|
||||
142, 167, 119, 69, 69, 119, 167, 142,
|
||||
119, 142, 94, 46, 46, 94, 142, 119,
|
||||
94, 119, 69, 21, 21, 69, 119, 94
|
||||
{ // King
|
||||
S(287, 18), S(311, 77), S(262,105), S(214,135), S(214,135), S(262,105), S(311, 77), S(287, 18),
|
||||
S(262, 77), S(287,135), S(238,165), S(190,193), S(190,193), S(238,165), S(287,135), S(262, 77),
|
||||
S(214,105), S(238,165), S(190,193), S(142,222), S(142,222), S(190,193), S(238,165), S(214,105),
|
||||
S(190,135), S(214,193), S(167,222), S(119,251), S(119,251), S(167,222), S(214,193), S(190,135),
|
||||
S(167,135), S(190,193), S(142,222), S( 94,251), S( 94,251), S(142,222), S(190,193), S(167,135),
|
||||
S(142,105), S(167,165), S(119,193), S( 69,222), S( 69,222), S(119,193), S(167,165), S(142,105),
|
||||
S(119, 77), S(142,135), S( 94,165), S( 46,193), S( 46,193), S( 94,165), S(142,135), S(119, 77),
|
||||
S(94, 18), S(119, 77), S( 69,105), S( 21,135), S( 21,135), S( 69,105), S(119, 77), S( 94, 18)
|
||||
}
|
||||
};
|
||||
|
||||
const int EgPST[][64] = {
|
||||
{ },
|
||||
{// Pawn
|
||||
// A B C D E F G H
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
},
|
||||
{// Knight
|
||||
// A B C D E F G H
|
||||
EK-104, EK-79, EK-55, EK-42, EK-42, EK-55, EK-79, EK-104,
|
||||
EK- 79, EK-55, EK-30, EK-17, EK-17, EK-30, EK-55, EK- 79,
|
||||
EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
|
||||
EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
|
||||
EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
|
||||
EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
|
||||
EK- 79, EK-55, EK-30, EK-17, EK-17, EK-30, EK-55, EK- 79,
|
||||
EK-104, EK-79, EK-55, EK-42, EK-42, EK-55, EK-79, EK-104
|
||||
},
|
||||
{// Bishop
|
||||
// A B C D E F G H
|
||||
EB-59, EB-42, EB-35, EB-26, EB-26, EB-35, EB-42, EB-59,
|
||||
EB-42, EB-26, EB-18, EB-11, EB-11, EB-18, EB-26, EB-42,
|
||||
EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
|
||||
EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
|
||||
EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
|
||||
EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
|
||||
EB-42, EB-26, EB-18, EB-11, EB-11, EB-18, EB-26, EB-42,
|
||||
EB-59, EB-42, EB-35, EB-26, EB-26, EB-35, EB-42, EB-59
|
||||
},
|
||||
{// Rook
|
||||
// A B C D E F G H
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3
|
||||
},
|
||||
{// Queen
|
||||
// A B C D E F G H
|
||||
EQ-80, EQ-54, EQ-42, EQ-30, EQ-30, EQ-42, EQ-54, EQ-80,
|
||||
EQ-54, EQ-30, EQ-18, EQ- 6, EQ- 6, EQ-18, EQ-30, EQ-54,
|
||||
EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
|
||||
EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
|
||||
EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
|
||||
EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
|
||||
EQ-54, EQ-30, EQ-18, EQ- 6, EQ- 6, EQ-18, EQ-30, EQ-54,
|
||||
EQ-80, EQ-54, EQ-42, EQ-30, EQ-30, EQ-42, EQ-54, EQ-80
|
||||
},
|
||||
{// King
|
||||
//A B C D E F G H
|
||||
18, 77, 105, 135, 135, 105, 77, 18,
|
||||
77, 135, 165, 193, 193, 165, 135, 77,
|
||||
105, 165, 193, 222, 222, 193, 165, 105,
|
||||
135, 193, 222, 251, 251, 222, 193, 135,
|
||||
135, 193, 222, 251, 251, 222, 193, 135,
|
||||
105, 165, 193, 222, 222, 193, 165, 105,
|
||||
77, 135, 165, 193, 193, 165, 135, 77,
|
||||
18, 77, 105, 135, 135, 105, 77, 18
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
#undef S
|
||||
|
||||
#endif // !defined(PSQTAB_H_INCLUDED)
|
||||
|
||||
29
src/rkiss.h
29
src/rkiss.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,19 +20,6 @@
|
||||
available under the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
** George Marsaglia invented the RNG-Kiss-family in the early 90's.
|
||||
** This is a specific version that Heinz van Saanen derived and
|
||||
** tested from some public domain code by Bob Jenkins:
|
||||
**
|
||||
** Quite platform independent
|
||||
** Passes ALL dieharder tests! Here *nix sys-rand() e.g. fails miserably:-)
|
||||
** ~12 times faster than my *nix sys-rand()
|
||||
** ~4 times faster than SSE2-version of Mersenne twister
|
||||
** Average cycle length: ~2^126
|
||||
** 64 bit seed
|
||||
** Return doubles with a full 53 bit mantissa
|
||||
** Thread safe
|
||||
*/
|
||||
|
||||
#if !defined(RKISS_H_INCLUDED)
|
||||
@@ -40,6 +27,20 @@
|
||||
|
||||
#include "types.h"
|
||||
|
||||
/// RKISS is our pseudo random number generator (PRNG) used to compute hash keys.
|
||||
/// George Marsaglia invented the RNG-Kiss-family in the early 90's. This is a
|
||||
/// specific version that Heinz van Saanen derived from some public domain code
|
||||
/// by Bob Jenkins. Following the feature list, as tested by Heinz.
|
||||
///
|
||||
/// - Quite platform independent
|
||||
/// - Passes ALL dieharder tests! Here *nix sys-rand() e.g. fails miserably:-)
|
||||
/// - ~12 times faster than my *nix sys-rand()
|
||||
/// - ~4 times faster than SSE2-version of Mersenne twister
|
||||
/// - Average cycle length: ~2^126
|
||||
/// - 64 bit seed
|
||||
/// - Return doubles with a full 53 bit mantissa
|
||||
/// - Thread safe
|
||||
|
||||
class RKISS {
|
||||
|
||||
// Keep variables always together
|
||||
|
||||
2309
src/search.cpp
2309
src/search.cpp
File diff suppressed because it is too large
Load Diff
90
src/search.h
90
src/search.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -21,53 +21,91 @@
|
||||
#define SEARCH_H_INCLUDED
|
||||
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <stack>
|
||||
#include <vector>
|
||||
|
||||
#include "move.h"
|
||||
#include "misc.h"
|
||||
#include "position.h"
|
||||
#include "types.h"
|
||||
|
||||
class Position;
|
||||
struct SplitPoint;
|
||||
|
||||
/// The SearchStack struct keeps track of the information we need to remember
|
||||
/// from nodes shallower and deeper in the tree during the search. Each
|
||||
/// search thread has its own array of SearchStack objects, indexed by the
|
||||
/// current ply.
|
||||
namespace Search {
|
||||
|
||||
struct SearchStack {
|
||||
/// The Stack struct keeps track of the information we need to remember from
|
||||
/// nodes shallower and deeper in the tree during the search. Each search thread
|
||||
/// has its own array of Stack objects, indexed by the current ply.
|
||||
|
||||
struct Stack {
|
||||
SplitPoint* sp;
|
||||
int ply;
|
||||
Move currentMove;
|
||||
Move mateKiller;
|
||||
Move excludedMove;
|
||||
Move bestMove;
|
||||
Move killers[2];
|
||||
Depth reduction;
|
||||
Value eval;
|
||||
Value evalMargin;
|
||||
bool skipNullMove;
|
||||
SplitPoint* sp;
|
||||
int skipNullMove;
|
||||
};
|
||||
|
||||
|
||||
/// The SearchLimits struct stores information sent by GUI about available time
|
||||
/// RootMove struct is used for moves at the root of the tree. For each root
|
||||
/// move we store a score, a node count, and a PV (really a refutation in the
|
||||
/// case of moves which fail low). Score is normally set at -VALUE_INFINITE for
|
||||
/// all non-pv moves.
|
||||
struct RootMove {
|
||||
|
||||
RootMove(){} // Needed by sort()
|
||||
RootMove(Move m) : score(-VALUE_INFINITE), prevScore(-VALUE_INFINITE) {
|
||||
pv.push_back(m); pv.push_back(MOVE_NONE);
|
||||
}
|
||||
|
||||
bool operator<(const RootMove& m) const { return score < m.score; }
|
||||
bool operator==(const Move& m) const { return pv[0] == m; }
|
||||
|
||||
void extract_pv_from_tt(Position& pos);
|
||||
void insert_pv_in_tt(Position& pos);
|
||||
|
||||
Value score;
|
||||
Value prevScore;
|
||||
std::vector<Move> pv;
|
||||
};
|
||||
|
||||
|
||||
/// The LimitsType struct stores information sent by GUI about available time
|
||||
/// to search the current move, maximum depth/time, if we are in analysis mode
|
||||
/// or if we have to ponder while is our opponent's side to move.
|
||||
|
||||
struct SearchLimits {
|
||||
struct LimitsType {
|
||||
|
||||
SearchLimits() { memset(this, 0, sizeof(SearchLimits)); }
|
||||
LimitsType() { memset(this, 0, sizeof(LimitsType)); }
|
||||
bool use_time_management() const { return !(movetime | depth | nodes | infinite); }
|
||||
|
||||
SearchLimits(int t, int i, int mtg, int mt, int md, int mn, bool inf, bool pon)
|
||||
: time(t), increment(i), movesToGo(mtg), maxTime(mt), maxDepth(md),
|
||||
maxNodes(mn), infinite(inf), ponder(pon) {}
|
||||
|
||||
bool useTimeManagement() const { return !(maxTime | maxDepth | maxNodes | int(infinite)); }
|
||||
|
||||
int time, increment, movesToGo, maxTime, maxDepth, maxNodes;
|
||||
bool infinite, ponder;
|
||||
int time[2], inc[2], movestogo, depth, nodes, movetime, infinite, ponder;
|
||||
};
|
||||
|
||||
extern void init_search();
|
||||
extern int64_t perft(Position& pos, Depth depth);
|
||||
extern bool think(Position& pos, const SearchLimits& limits, Move searchMoves[]);
|
||||
|
||||
/// The SignalsType struct stores volatile flags updated during the search
|
||||
/// typically in an async fashion, for instance to stop the search by the GUI.
|
||||
|
||||
struct SignalsType {
|
||||
bool stopOnPonderhit, firstRootMove, stop, failedLowAtRoot;
|
||||
};
|
||||
|
||||
typedef std::auto_ptr<std::stack<StateInfo> > StateStackPtr;
|
||||
|
||||
extern volatile SignalsType Signals;
|
||||
extern LimitsType Limits;
|
||||
extern std::vector<RootMove> RootMoves;
|
||||
extern Position RootPosition;
|
||||
extern Time::point SearchTime;
|
||||
extern StateStackPtr SetupStates;
|
||||
|
||||
extern void init();
|
||||
extern size_t perft(Position& pos, Depth depth);
|
||||
extern void think();
|
||||
|
||||
} // namespace Search
|
||||
|
||||
#endif // !defined(SEARCH_H_INCLUDED)
|
||||
|
||||
553
src/thread.cpp
553
src/thread.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,211 +17,256 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
#include "movegen.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "ucioption.h"
|
||||
|
||||
ThreadsManager Threads; // Global object definition
|
||||
using namespace Search;
|
||||
|
||||
ThreadPool Threads; // Global object
|
||||
|
||||
namespace { extern "C" {
|
||||
|
||||
// start_routine() is the C function which is called when a new thread
|
||||
// is launched. It simply calls idle_loop() with the supplied threadID.
|
||||
// There are two versions of this function; one for POSIX threads and
|
||||
// one for Windows threads.
|
||||
// is launched. It is a wrapper to member function pointed by start_fn.
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
|
||||
DWORD WINAPI start_routine(LPVOID threadID) {
|
||||
|
||||
Threads.idle_loop(*(int*)threadID, NULL);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
void* start_routine(void* threadID) {
|
||||
|
||||
Threads.idle_loop(*(int*)threadID, NULL);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
#endif
|
||||
long start_routine(Thread* th) { (th->*(th->start_fn))(); return 0; }
|
||||
|
||||
} }
|
||||
|
||||
|
||||
// wake_up() wakes up the thread, normally at the beginning of the search or,
|
||||
// if "sleeping threads" is used, when there is some work to do.
|
||||
// Thread c'tor starts a newly-created thread of execution that will call
|
||||
// the idle loop function pointed by start_fn going immediately to sleep.
|
||||
|
||||
void Thread::wake_up() {
|
||||
Thread::Thread(Fn fn) {
|
||||
|
||||
lock_grab(&sleepLock);
|
||||
cond_signal(&sleepCond);
|
||||
lock_release(&sleepLock);
|
||||
is_searching = do_exit = false;
|
||||
maxPly = splitPointsCnt = 0;
|
||||
curSplitPoint = NULL;
|
||||
start_fn = fn;
|
||||
idx = Threads.size();
|
||||
|
||||
do_sleep = (fn != &Thread::main_loop); // Avoid a race with start_searching()
|
||||
|
||||
if (!thread_create(handle, start_routine, this))
|
||||
{
|
||||
std::cerr << "Failed to create thread number " << idx << std::endl;
|
||||
::exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// cutoff_occurred() checks whether a beta cutoff has occurred in
|
||||
// the thread's currently active split point, or in some ancestor of
|
||||
// the current split point.
|
||||
// Thread d'tor waits for thread termination before to return.
|
||||
|
||||
Thread::~Thread() {
|
||||
|
||||
assert(do_sleep);
|
||||
|
||||
do_exit = true; // Search must be already finished
|
||||
wake_up();
|
||||
thread_join(handle); // Wait for thread termination
|
||||
}
|
||||
|
||||
|
||||
// Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
|
||||
// then calls check_time(). If maxPly is 0 thread sleeps until is woken up.
|
||||
extern void check_time();
|
||||
|
||||
void Thread::timer_loop() {
|
||||
|
||||
while (!do_exit)
|
||||
{
|
||||
mutex.lock();
|
||||
sleepCondition.wait_for(mutex, maxPly ? maxPly : INT_MAX);
|
||||
mutex.unlock();
|
||||
check_time();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Thread::main_loop() is where the main thread is parked waiting to be started
|
||||
// when there is a new search. Main thread will launch all the slave threads.
|
||||
|
||||
void Thread::main_loop() {
|
||||
|
||||
while (true)
|
||||
{
|
||||
mutex.lock();
|
||||
|
||||
do_sleep = true; // Always return to sleep after a search
|
||||
is_searching = false;
|
||||
|
||||
while (do_sleep && !do_exit)
|
||||
{
|
||||
Threads.sleepCondition.notify_one(); // Wake up UI thread if needed
|
||||
sleepCondition.wait(mutex);
|
||||
}
|
||||
|
||||
mutex.unlock();
|
||||
|
||||
if (do_exit)
|
||||
return;
|
||||
|
||||
is_searching = true;
|
||||
|
||||
Search::think();
|
||||
|
||||
assert(is_searching);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Thread::wake_up() wakes up the thread, normally at the beginning of the search
|
||||
// or, if "sleeping threads" is used at split time.
|
||||
|
||||
void Thread::wake_up() {
|
||||
|
||||
mutex.lock();
|
||||
sleepCondition.notify_one();
|
||||
mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
// Thread::wait_for_stop_or_ponderhit() is called when the maximum depth is
|
||||
// reached while the program is pondering. The point is to work around a wrinkle
|
||||
// in the UCI protocol: When pondering, the engine is not allowed to give a
|
||||
// "bestmove" before the GUI sends it a "stop" or "ponderhit" command. We simply
|
||||
// wait here until one of these commands (that raise StopRequest) is sent and
|
||||
// then return, after which the bestmove and pondermove will be printed.
|
||||
|
||||
void Thread::wait_for_stop_or_ponderhit() {
|
||||
|
||||
Signals.stopOnPonderhit = true;
|
||||
|
||||
mutex.lock();
|
||||
while (!Signals.stop) sleepCondition.wait(mutex);;
|
||||
mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
// Thread::cutoff_occurred() checks whether a beta cutoff has occurred in the
|
||||
// current active split point, or in some ancestor of the split point.
|
||||
|
||||
bool Thread::cutoff_occurred() const {
|
||||
|
||||
for (SplitPoint* sp = splitPoint; sp; sp = sp->parent)
|
||||
if (sp->is_betaCutoff)
|
||||
for (SplitPoint* sp = curSplitPoint; sp; sp = sp->parent)
|
||||
if (sp->cutoff)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// is_available_to() checks whether the thread is available to help the thread with
|
||||
// threadID "master" at a split point. An obvious requirement is that thread must be
|
||||
// idle. With more than two threads, this is not by itself sufficient: If the thread
|
||||
// is the master of some active split point, it is only available as a slave to the
|
||||
// threads which are busy searching the split point at the top of "slave"'s split
|
||||
// Thread::is_available_to() checks whether the thread is available to help the
|
||||
// thread 'master' at a split point. An obvious requirement is that thread must
|
||||
// be idle. With more than two threads, this is not sufficient: If the thread is
|
||||
// the master of some active split point, it is only available as a slave to the
|
||||
// slaves which are busy searching the split point at the top of slaves split
|
||||
// point stack (the "helpful master concept" in YBWC terminology).
|
||||
|
||||
bool Thread::is_available_to(int master) const {
|
||||
bool Thread::is_available_to(Thread* master) const {
|
||||
|
||||
if (state != AVAILABLE)
|
||||
if (is_searching)
|
||||
return false;
|
||||
|
||||
// Make a local copy to be sure doesn't become zero under our feet while
|
||||
// testing next condition and so leading to an out of bound access.
|
||||
int localActiveSplitPoints = activeSplitPoints;
|
||||
int spCnt = splitPointsCnt;
|
||||
|
||||
// No active split points means that the thread is available as a slave for any
|
||||
// other thread otherwise apply the "helpful master" concept if possible.
|
||||
if ( !localActiveSplitPoints
|
||||
|| splitPoints[localActiveSplitPoints - 1].is_slave[master])
|
||||
return true;
|
||||
|
||||
return false;
|
||||
return !spCnt || (splitPoints[spCnt - 1].slavesMask & (1ULL << master->idx));
|
||||
}
|
||||
|
||||
|
||||
// read_uci_options() updates number of active threads and other internal
|
||||
// parameters according to the UCI options values. It is called before
|
||||
// to start a new search.
|
||||
// init() is called at startup. Initializes lock and condition variable and
|
||||
// launches requested threads sending them immediately to sleep. We cannot use
|
||||
// a c'tor becuase Threads is a static object and we need a fully initialized
|
||||
// engine at this point due to allocation of endgames in Thread c'tor.
|
||||
|
||||
void ThreadsManager::read_uci_options() {
|
||||
void ThreadPool::init() {
|
||||
|
||||
maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
|
||||
minimumSplitDepth = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
|
||||
useSleepingThreads = Options["Use Sleeping Threads"].value<bool>();
|
||||
activeThreads = Options["Threads"].value<int>();
|
||||
timer = new Thread(&Thread::timer_loop);
|
||||
threads.push_back(new Thread(&Thread::main_loop));
|
||||
read_uci_options();
|
||||
}
|
||||
|
||||
|
||||
// init() is called during startup. Initializes locks and condition variables
|
||||
// and launches all threads sending them immediately to sleep.
|
||||
// exit() cleanly terminates the threads before the program exits.
|
||||
|
||||
void ThreadsManager::init() {
|
||||
void ThreadPool::exit() {
|
||||
|
||||
int threadID[MAX_THREADS];
|
||||
for (size_t i = 0; i < threads.size(); i++)
|
||||
delete threads[i];
|
||||
|
||||
// This flag is needed to properly end the threads when program exits
|
||||
allThreadsShouldExit = false;
|
||||
delete timer;
|
||||
}
|
||||
|
||||
// Threads will sent to sleep as soon as created, only main thread is kept alive
|
||||
activeThreads = 1;
|
||||
threads[0].state = Thread::SEARCHING;
|
||||
|
||||
// Allocate pawn and material hash tables for main thread
|
||||
init_hash_tables();
|
||||
// read_uci_options() updates internal threads parameters from the corresponding
|
||||
// UCI options and creates/destroys threads to match the requested number. Thread
|
||||
// objects are dynamically allocated to avoid creating in advance all possible
|
||||
// threads, with included pawns and material tables, if only few are used.
|
||||
|
||||
lock_init(&mpLock);
|
||||
void ThreadPool::read_uci_options() {
|
||||
|
||||
// Initialize thread and split point locks
|
||||
for (int i = 0; i < MAX_THREADS; i++)
|
||||
maxThreadsPerSplitPoint = Options["Max Threads per Split Point"];
|
||||
minimumSplitDepth = Options["Min Split Depth"] * ONE_PLY;
|
||||
useSleepingThreads = Options["Use Sleeping Threads"];
|
||||
size_t requested = Options["Threads"];
|
||||
|
||||
assert(requested > 0);
|
||||
|
||||
while (threads.size() < requested)
|
||||
threads.push_back(new Thread(&Thread::idle_loop));
|
||||
|
||||
while (threads.size() > requested)
|
||||
{
|
||||
lock_init(&threads[i].sleepLock);
|
||||
cond_init(&threads[i].sleepCond);
|
||||
|
||||
for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
|
||||
lock_init(&(threads[i].splitPoints[j].lock));
|
||||
}
|
||||
|
||||
// Create and startup all the threads but the main that is already running
|
||||
for (int i = 1; i < MAX_THREADS; i++)
|
||||
{
|
||||
threads[i].state = Thread::INITIALIZING;
|
||||
threadID[i] = i;
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
bool ok = (CreateThread(NULL, 0, start_routine, (LPVOID)&threadID[i], 0, NULL) != NULL);
|
||||
#else
|
||||
pthread_t pthreadID;
|
||||
bool ok = (pthread_create(&pthreadID, NULL, start_routine, (void*)&threadID[i]) == 0);
|
||||
pthread_detach(pthreadID);
|
||||
#endif
|
||||
if (!ok)
|
||||
{
|
||||
std::cout << "Failed to create thread number " << i << std::endl;
|
||||
::exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Wait until the thread has finished launching and is gone to sleep
|
||||
while (threads[i].state == Thread::INITIALIZING) {}
|
||||
delete threads.back();
|
||||
threads.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// exit() is called to cleanly exit the threads when the program finishes
|
||||
// wake_up() is called before a new search to start the threads that are waiting
|
||||
// on the sleep condition and to reset maxPly. When useSleepingThreads is set
|
||||
// threads will be woken up at split time.
|
||||
|
||||
void ThreadsManager::exit() {
|
||||
void ThreadPool::wake_up() const {
|
||||
|
||||
// Force the woken up threads to exit idle_loop() and hence terminate
|
||||
allThreadsShouldExit = true;
|
||||
|
||||
for (int i = 0; i < MAX_THREADS; i++)
|
||||
for (size_t i = 0; i < threads.size(); i++)
|
||||
{
|
||||
// Wake up all the threads and waits for termination
|
||||
if (i != 0)
|
||||
{
|
||||
threads[i].wake_up();
|
||||
while (threads[i].state != Thread::TERMINATED) {}
|
||||
}
|
||||
threads[i]->maxPly = 0;
|
||||
threads[i]->do_sleep = false;
|
||||
|
||||
// Now we can safely destroy the locks and wait conditions
|
||||
lock_destroy(&threads[i].sleepLock);
|
||||
cond_destroy(&threads[i].sleepCond);
|
||||
|
||||
for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
|
||||
lock_destroy(&(threads[i].splitPoints[j].lock));
|
||||
if (!useSleepingThreads)
|
||||
threads[i]->wake_up();
|
||||
}
|
||||
|
||||
lock_destroy(&mpLock);
|
||||
}
|
||||
|
||||
|
||||
// init_hash_tables() dynamically allocates pawn and material hash tables
|
||||
// according to the number of active threads. This avoids preallocating
|
||||
// memory for all possible threads if only few are used as, for instance,
|
||||
// on mobile devices where memory is scarce and allocating for MAX_THREADS
|
||||
// threads could even result in a crash.
|
||||
// sleep() is called after the search finishes to ask all the threads but the
|
||||
// main one to go waiting on a sleep condition.
|
||||
|
||||
void ThreadsManager::init_hash_tables() {
|
||||
void ThreadPool::sleep() const {
|
||||
|
||||
for (int i = 0; i < activeThreads; i++)
|
||||
{
|
||||
threads[i].pawnTable.init();
|
||||
threads[i].materialTable.init();
|
||||
}
|
||||
// Main thread will go to sleep by itself to avoid a race with start_searching()
|
||||
for (size_t i = 1; i < threads.size(); i++)
|
||||
threads[i]->do_sleep = true;
|
||||
}
|
||||
|
||||
|
||||
// available_slave_exists() tries to find an idle thread which is available as
|
||||
// a slave for the thread with threadID "master".
|
||||
// a slave for the thread 'master'.
|
||||
|
||||
bool ThreadsManager::available_slave_exists(int master) const {
|
||||
bool ThreadPool::available_slave_exists(Thread* master) const {
|
||||
|
||||
assert(master >= 0 && master < activeThreads);
|
||||
|
||||
for (int i = 0; i < activeThreads; i++)
|
||||
if (i != master && threads[i].is_available_to(master))
|
||||
for (size_t i = 0; i < threads.size(); i++)
|
||||
if (threads[i]->is_available_to(master))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
@@ -229,117 +274,163 @@ bool ThreadsManager::available_slave_exists(int master) const {
|
||||
|
||||
|
||||
// split() does the actual work of distributing the work at a node between
|
||||
// several available threads. If it does not succeed in splitting the
|
||||
// node (because no idle threads are available, or because we have no unused
|
||||
// split point objects), the function immediately returns. If splitting is
|
||||
// possible, a SplitPoint object is initialized with all the data that must be
|
||||
// copied to the helper threads and we tell our helper threads that they have
|
||||
// been assigned work. This will cause them to instantly leave their idle loops and
|
||||
// call search().When all threads have returned from search() then split() returns.
|
||||
// several available threads. If it does not succeed in splitting the node
|
||||
// (because no idle threads are available, or because we have no unused split
|
||||
// point objects), the function immediately returns. If splitting is possible, a
|
||||
// SplitPoint object is initialized with all the data that must be copied to the
|
||||
// helper threads and then helper threads are told that they have been assigned
|
||||
// work. This will cause them to instantly leave their idle loops and call
|
||||
// search(). When all threads have returned from search() then split() returns.
|
||||
|
||||
template <bool Fake>
|
||||
void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
|
||||
Value* bestValue, Depth depth, Move threatMove,
|
||||
int moveCount, MovePicker* mp, bool pvNode) {
|
||||
assert(pos.is_ok());
|
||||
assert(*bestValue >= -VALUE_INFINITE);
|
||||
assert(*bestValue <= *alpha);
|
||||
assert(*alpha < beta);
|
||||
Value ThreadPool::split(Position& pos, Stack* ss, Value alpha, Value beta,
|
||||
Value bestValue, Move* bestMove, Depth depth,
|
||||
Move threatMove, int moveCount, MovePicker* mp, int nodeType) {
|
||||
|
||||
assert(pos.pos_is_ok());
|
||||
assert(bestValue > -VALUE_INFINITE);
|
||||
assert(bestValue <= alpha);
|
||||
assert(alpha < beta);
|
||||
assert(beta <= VALUE_INFINITE);
|
||||
assert(depth > DEPTH_ZERO);
|
||||
assert(pos.thread() >= 0 && pos.thread() < activeThreads);
|
||||
assert(activeThreads > 1);
|
||||
|
||||
int i, master = pos.thread();
|
||||
Thread& masterThread = threads[master];
|
||||
Thread* master = pos.this_thread();
|
||||
|
||||
lock_grab(&mpLock);
|
||||
if (master->splitPointsCnt >= MAX_SPLITPOINTS_PER_THREAD)
|
||||
return bestValue;
|
||||
|
||||
// If no other thread is available to help us, or if we have too many
|
||||
// active split points, don't split.
|
||||
if ( !available_slave_exists(master)
|
||||
|| masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
|
||||
// Pick the next available split point from the split point stack
|
||||
SplitPoint& sp = master->splitPoints[master->splitPointsCnt];
|
||||
|
||||
sp.parent = master->curSplitPoint;
|
||||
sp.master = master;
|
||||
sp.cutoff = false;
|
||||
sp.slavesMask = 1ULL << master->idx;
|
||||
sp.depth = depth;
|
||||
sp.bestMove = *bestMove;
|
||||
sp.threatMove = threatMove;
|
||||
sp.alpha = alpha;
|
||||
sp.beta = beta;
|
||||
sp.nodeType = nodeType;
|
||||
sp.bestValue = bestValue;
|
||||
sp.mp = mp;
|
||||
sp.moveCount = moveCount;
|
||||
sp.pos = &pos;
|
||||
sp.nodes = 0;
|
||||
sp.ss = ss;
|
||||
|
||||
assert(master->is_searching);
|
||||
|
||||
master->curSplitPoint = &sp;
|
||||
int slavesCnt = 0;
|
||||
|
||||
// Try to allocate available threads and ask them to start searching setting
|
||||
// is_searching flag. This must be done under lock protection to avoid concurrent
|
||||
// allocation of the same slave by another master.
|
||||
sp.mutex.lock();
|
||||
mutex.lock();
|
||||
|
||||
for (size_t i = 0; i < threads.size() && !Fake; ++i)
|
||||
if (threads[i]->is_available_to(master))
|
||||
{
|
||||
sp.slavesMask |= 1ULL << i;
|
||||
threads[i]->curSplitPoint = &sp;
|
||||
threads[i]->is_searching = true; // Slave leaves idle_loop()
|
||||
|
||||
if (useSleepingThreads)
|
||||
threads[i]->wake_up();
|
||||
|
||||
if (++slavesCnt + 1 >= maxThreadsPerSplitPoint) // Master is always included
|
||||
break;
|
||||
}
|
||||
|
||||
master->splitPointsCnt++;
|
||||
|
||||
mutex.unlock();
|
||||
sp.mutex.unlock();
|
||||
|
||||
// Everything is set up. The master thread enters the idle loop, from which
|
||||
// it will instantly launch a search, because its is_searching flag is set.
|
||||
// The thread will return from the idle loop when all slaves have finished
|
||||
// their work at this split point.
|
||||
if (slavesCnt || Fake)
|
||||
{
|
||||
lock_release(&mpLock);
|
||||
return;
|
||||
master->idle_loop();
|
||||
|
||||
// In helpful master concept a master can help only a sub-tree of its split
|
||||
// point, and because here is all finished is not possible master is booked.
|
||||
assert(!master->is_searching);
|
||||
}
|
||||
|
||||
// Pick the next available split point object from the split point stack
|
||||
SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
|
||||
|
||||
// Initialize the split point object
|
||||
splitPoint.parent = masterThread.splitPoint;
|
||||
splitPoint.master = master;
|
||||
splitPoint.is_betaCutoff = false;
|
||||
splitPoint.depth = depth;
|
||||
splitPoint.threatMove = threatMove;
|
||||
splitPoint.alpha = *alpha;
|
||||
splitPoint.beta = beta;
|
||||
splitPoint.pvNode = pvNode;
|
||||
splitPoint.bestValue = *bestValue;
|
||||
splitPoint.mp = mp;
|
||||
splitPoint.moveCount = moveCount;
|
||||
splitPoint.pos = &pos;
|
||||
splitPoint.nodes = 0;
|
||||
splitPoint.ss = ss;
|
||||
for (i = 0; i < activeThreads; i++)
|
||||
splitPoint.is_slave[i] = false;
|
||||
|
||||
masterThread.splitPoint = &splitPoint;
|
||||
|
||||
// If we are here it means we are not available
|
||||
assert(masterThread.state != Thread::AVAILABLE);
|
||||
|
||||
int workersCnt = 1; // At least the master is included
|
||||
|
||||
// Allocate available threads setting state to THREAD_BOOKED
|
||||
for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
|
||||
if (i != master && threads[i].is_available_to(master))
|
||||
{
|
||||
threads[i].state = Thread::BOOKED;
|
||||
threads[i].splitPoint = &splitPoint;
|
||||
splitPoint.is_slave[i] = true;
|
||||
workersCnt++;
|
||||
}
|
||||
|
||||
assert(Fake || workersCnt > 1);
|
||||
|
||||
// We can release the lock because slave threads are already booked and master is not available
|
||||
lock_release(&mpLock);
|
||||
|
||||
// Tell the threads that they have work to do. This will make them leave
|
||||
// their idle loop.
|
||||
for (i = 0; i < activeThreads; i++)
|
||||
if (i == master || splitPoint.is_slave[i])
|
||||
{
|
||||
assert(i == master || threads[i].state == Thread::BOOKED);
|
||||
|
||||
threads[i].state = Thread::WORKISWAITING; // This makes the slave to exit from idle_loop()
|
||||
|
||||
if (useSleepingThreads && i != master)
|
||||
threads[i].wake_up();
|
||||
}
|
||||
|
||||
// Everything is set up. The master thread enters the idle loop, from
|
||||
// which it will instantly launch a search, because its state is
|
||||
// THREAD_WORKISWAITING. We send the split point as a second parameter to the
|
||||
// idle loop, which means that the main thread will return from the idle
|
||||
// loop when all threads have finished their work at this split point.
|
||||
idle_loop(master, &splitPoint);
|
||||
|
||||
// We have returned from the idle loop, which means that all threads are
|
||||
// finished. Update alpha and bestValue, and return.
|
||||
lock_grab(&mpLock);
|
||||
// finished. Note that setting is_searching and decreasing splitPointsCnt is
|
||||
// done under lock protection to avoid a race with Thread::is_available_to().
|
||||
sp.mutex.lock(); // To protect sp.nodes
|
||||
mutex.lock();
|
||||
|
||||
*alpha = splitPoint.alpha;
|
||||
*bestValue = splitPoint.bestValue;
|
||||
masterThread.activeSplitPoints--;
|
||||
masterThread.splitPoint = splitPoint.parent;
|
||||
pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
|
||||
master->is_searching = true;
|
||||
master->splitPointsCnt--;
|
||||
master->curSplitPoint = sp.parent;
|
||||
pos.set_nodes_searched(pos.nodes_searched() + sp.nodes);
|
||||
*bestMove = sp.bestMove;
|
||||
|
||||
lock_release(&mpLock);
|
||||
mutex.unlock();
|
||||
sp.mutex.unlock();
|
||||
|
||||
return sp.bestValue;
|
||||
}
|
||||
|
||||
// Explicit template instantiations
|
||||
template void ThreadsManager::split<false>(Position&, SearchStack*, Value*, const Value, Value*, Depth, Move, int, MovePicker*, bool);
|
||||
template void ThreadsManager::split<true>(Position&, SearchStack*, Value*, const Value, Value*, Depth, Move, int, MovePicker*, bool);
|
||||
template Value ThreadPool::split<false>(Position&, Stack*, Value, Value, Value, Move*, Depth, Move, int, MovePicker*, int);
|
||||
template Value ThreadPool::split<true>(Position&, Stack*, Value, Value, Value, Move*, Depth, Move, int, MovePicker*, int);
|
||||
|
||||
|
||||
// set_timer() is used to set the timer to trigger after msec milliseconds.
|
||||
// If msec is 0 then timer is stopped.
|
||||
|
||||
void ThreadPool::set_timer(int msec) {
|
||||
|
||||
timer->mutex.lock();
|
||||
timer->maxPly = msec;
|
||||
timer->sleepCondition.notify_one(); // Wake up and restart the timer
|
||||
timer->mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
// wait_for_search_finished() waits for main thread to go to sleep, this means
|
||||
// search is finished. Then returns.
|
||||
|
||||
void ThreadPool::wait_for_search_finished() {
|
||||
|
||||
Thread* t = main_thread();
|
||||
t->mutex.lock();
|
||||
t->sleepCondition.notify_one(); // In case is waiting for stop or ponderhit
|
||||
while (!t->do_sleep) sleepCondition.wait(t->mutex);
|
||||
t->mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
// start_searching() wakes up the main thread sleeping in main_loop() so to start
|
||||
// a new search, then returns immediately.
|
||||
|
||||
void ThreadPool::start_searching(const Position& pos, const LimitsType& limits,
|
||||
const std::vector<Move>& searchMoves, StateStackPtr& states) {
|
||||
wait_for_search_finished();
|
||||
|
||||
SearchTime = Time::now(); // As early as possible
|
||||
|
||||
Signals.stopOnPonderhit = Signals.firstRootMove = false;
|
||||
Signals.stop = Signals.failedLowAtRoot = false;
|
||||
|
||||
RootPosition = pos;
|
||||
Limits = limits;
|
||||
SetupStates = states; // Ownership transfer here
|
||||
RootMoves.clear();
|
||||
|
||||
for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
|
||||
if (searchMoves.empty() || count(searchMoves.begin(), searchMoves.end(), ml.move()))
|
||||
RootMoves.push_back(RootMove(ml.move()));
|
||||
|
||||
main_thread()->do_sleep = false;
|
||||
main_thread()->wake_up();
|
||||
}
|
||||
|
||||
154
src/thread.h
154
src/thread.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,113 +20,149 @@
|
||||
#if !defined(THREAD_H_INCLUDED)
|
||||
#define THREAD_H_INCLUDED
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "lock.h"
|
||||
#include "material.h"
|
||||
#include "movepick.h"
|
||||
#include "pawns.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
|
||||
const int MAX_THREADS = 32;
|
||||
const int MAX_ACTIVE_SPLIT_POINTS = 8;
|
||||
const int MAX_SPLITPOINTS_PER_THREAD = 8;
|
||||
|
||||
struct Mutex {
|
||||
Mutex() { lock_init(l); }
|
||||
~Mutex() { lock_destroy(l); }
|
||||
|
||||
void lock() { lock_grab(l); }
|
||||
void unlock() { lock_release(l); }
|
||||
|
||||
private:
|
||||
friend struct ConditionVariable;
|
||||
|
||||
Lock l;
|
||||
};
|
||||
|
||||
struct ConditionVariable {
|
||||
ConditionVariable() { cond_init(c); }
|
||||
~ConditionVariable() { cond_destroy(c); }
|
||||
|
||||
void wait(Mutex& m) { cond_wait(c, m.l); }
|
||||
void wait_for(Mutex& m, int ms) { timed_wait(c, m.l, ms); }
|
||||
void notify_one() { cond_signal(c); }
|
||||
|
||||
private:
|
||||
WaitCondition c;
|
||||
};
|
||||
|
||||
class Thread;
|
||||
|
||||
struct SplitPoint {
|
||||
|
||||
// Const data after splitPoint has been setup
|
||||
SplitPoint* parent;
|
||||
// Const data after split point has been setup
|
||||
const Position* pos;
|
||||
const Search::Stack* ss;
|
||||
Depth depth;
|
||||
bool pvNode;
|
||||
Value beta;
|
||||
int ply;
|
||||
int master;
|
||||
int nodeType;
|
||||
Thread* master;
|
||||
Move threatMove;
|
||||
|
||||
// Const pointers to shared data
|
||||
MovePicker* mp;
|
||||
SearchStack* ss;
|
||||
SplitPoint* parent;
|
||||
|
||||
// Shared data
|
||||
Lock lock;
|
||||
Mutex mutex;
|
||||
volatile uint64_t slavesMask;
|
||||
volatile int64_t nodes;
|
||||
volatile Value alpha;
|
||||
volatile Value bestValue;
|
||||
volatile Move bestMove;
|
||||
volatile int moveCount;
|
||||
volatile bool is_betaCutoff;
|
||||
volatile bool is_slave[MAX_THREADS];
|
||||
volatile bool cutoff;
|
||||
};
|
||||
|
||||
|
||||
/// Thread struct is used to keep together all the thread related stuff like locks,
|
||||
/// state and especially split points. We also use per-thread pawn and material hash
|
||||
/// tables so that once we get a pointer to an entry its life time is unlimited and
|
||||
/// we don't have to care about someone changing the entry under our feet.
|
||||
/// Thread struct keeps together all the thread related stuff like locks, state
|
||||
/// and especially split points. We also use per-thread pawn and material hash
|
||||
/// tables so that once we get a pointer to an entry its life time is unlimited
|
||||
/// and we don't have to care about someone changing the entry under our feet.
|
||||
|
||||
struct Thread {
|
||||
class Thread {
|
||||
|
||||
enum ThreadState
|
||||
{
|
||||
INITIALIZING, // Thread is initializing itself
|
||||
SEARCHING, // Thread is performing work
|
||||
AVAILABLE, // Thread is waiting for work
|
||||
BOOKED, // Other thread (master) has booked us as a slave
|
||||
WORKISWAITING, // Master has ordered us to start
|
||||
TERMINATED // We are quitting and thread is terminated
|
||||
};
|
||||
typedef void (Thread::* Fn) (); // Pointer to member function
|
||||
|
||||
public:
|
||||
Thread(Fn fn);
|
||||
~Thread();
|
||||
|
||||
void wake_up();
|
||||
bool cutoff_occurred() const;
|
||||
bool is_available_to(int master) const;
|
||||
bool is_available_to(Thread* master) const;
|
||||
void idle_loop();
|
||||
void main_loop();
|
||||
void timer_loop();
|
||||
void wait_for_stop_or_ponderhit();
|
||||
|
||||
MaterialInfoTable materialTable;
|
||||
PawnInfoTable pawnTable;
|
||||
SplitPoint splitPoints[MAX_SPLITPOINTS_PER_THREAD];
|
||||
MaterialTable materialTable;
|
||||
PawnTable pawnTable;
|
||||
size_t idx;
|
||||
int maxPly;
|
||||
Lock sleepLock;
|
||||
WaitCondition sleepCond;
|
||||
volatile ThreadState state;
|
||||
SplitPoint* volatile splitPoint;
|
||||
volatile int activeSplitPoints;
|
||||
SplitPoint splitPoints[MAX_ACTIVE_SPLIT_POINTS];
|
||||
Mutex mutex;
|
||||
ConditionVariable sleepCondition;
|
||||
NativeHandle handle;
|
||||
Fn start_fn;
|
||||
SplitPoint* volatile curSplitPoint;
|
||||
volatile int splitPointsCnt;
|
||||
volatile bool is_searching;
|
||||
volatile bool do_sleep;
|
||||
volatile bool do_exit;
|
||||
};
|
||||
|
||||
|
||||
/// ThreadsManager class is used to handle all the threads related stuff like init,
|
||||
/// starting, parking and, the most important, launching a slave thread at a split
|
||||
/// point. All the access to shared thread data is done through this class.
|
||||
/// ThreadPool class handles all the threads related stuff like init, starting,
|
||||
/// parking and, the most important, launching a slave thread at a split point.
|
||||
/// All the access to shared thread data is done through this class.
|
||||
|
||||
class ThreadPool {
|
||||
|
||||
class ThreadsManager {
|
||||
/* As long as the single ThreadsManager object is defined as a global we don't
|
||||
need to explicitly initialize to zero its data members because variables with
|
||||
static storage duration are automatically set to zero before enter main()
|
||||
*/
|
||||
public:
|
||||
Thread& operator[](int threadID) { return threads[threadID]; }
|
||||
void init();
|
||||
void exit();
|
||||
void init_hash_tables();
|
||||
void init(); // No c'tor and d'tor, threads rely on globals that should
|
||||
void exit(); // be initialized and valid during the whole thread lifetime.
|
||||
|
||||
Thread& operator[](size_t id) { return *threads[id]; }
|
||||
bool use_sleeping_threads() const { return useSleepingThreads; }
|
||||
int min_split_depth() const { return minimumSplitDepth; }
|
||||
int size() const { return activeThreads; }
|
||||
void set_size(int cnt) { activeThreads = cnt; }
|
||||
size_t size() const { return threads.size(); }
|
||||
Thread* main_thread() { return threads[0]; }
|
||||
|
||||
void wake_up() const;
|
||||
void sleep() const;
|
||||
void read_uci_options();
|
||||
bool available_slave_exists(int master) const;
|
||||
void idle_loop(int threadID, SplitPoint* sp);
|
||||
bool available_slave_exists(Thread* master) const;
|
||||
void set_timer(int msec);
|
||||
void wait_for_search_finished();
|
||||
void start_searching(const Position&, const Search::LimitsType&,
|
||||
const std::vector<Move>&, Search::StateStackPtr&);
|
||||
|
||||
template <bool Fake>
|
||||
void split(Position& pos, SearchStack* ss, Value* alpha, const Value beta, Value* bestValue,
|
||||
Depth depth, Move threatMove, int moveCount, MovePicker* mp, bool pvNode);
|
||||
Value split(Position& pos, Search::Stack* ss, Value alpha, Value beta, Value bestValue, Move* bestMove,
|
||||
Depth depth, Move threatMove, int moveCount, MovePicker* mp, int nodeType);
|
||||
private:
|
||||
Lock mpLock;
|
||||
friend class Thread;
|
||||
|
||||
std::vector<Thread*> threads;
|
||||
Thread* timer;
|
||||
Mutex mutex;
|
||||
ConditionVariable sleepCondition;
|
||||
Depth minimumSplitDepth;
|
||||
int maxThreadsPerSplitPoint;
|
||||
bool useSleepingThreads;
|
||||
int activeThreads;
|
||||
volatile bool allThreadsShouldExit;
|
||||
Thread threads[MAX_THREADS];
|
||||
};
|
||||
|
||||
extern ThreadsManager Threads;
|
||||
extern ThreadPool Threads;
|
||||
|
||||
#endif // !defined(THREAD_H_INCLUDED)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -18,8 +18,8 @@
|
||||
*/
|
||||
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
#include "misc.h"
|
||||
#include "search.h"
|
||||
#include "timeman.h"
|
||||
#include "ucioption.h"
|
||||
@@ -64,7 +64,7 @@ namespace {
|
||||
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 2, 2, 2,
|
||||
2, 1, 1, 1, 1, 1, 1, 1 };
|
||||
|
||||
int move_importance(int ply) { return MoveImportance[Min(ply, 511)]; }
|
||||
int move_importance(int ply) { return MoveImportance[std::min(ply, 511)]; }
|
||||
|
||||
|
||||
/// Function Prototypes
|
||||
@@ -72,18 +72,18 @@ namespace {
|
||||
enum TimeType { OptimumTime, MaxTime };
|
||||
|
||||
template<TimeType>
|
||||
int remaining(int myTime, int movesToGo, int currentPly);
|
||||
int remaining(int myTime, int movesToGo, int fullMoveNumber, int slowMover);
|
||||
}
|
||||
|
||||
|
||||
void TimeManager::pv_instability(int curChanges, int prevChanges) {
|
||||
|
||||
unstablePVExtraTime = curChanges * (optimumSearchTime / 2)
|
||||
+ prevChanges * (optimumSearchTime / 3);
|
||||
unstablePVExtraTime = curChanges * (optimumSearchTime / 2)
|
||||
+ prevChanges * (optimumSearchTime / 3);
|
||||
}
|
||||
|
||||
|
||||
void TimeManager::init(const SearchLimits& limits, int currentPly)
|
||||
void TimeManager::init(const Search::LimitsType& limits, int currentPly, Color us)
|
||||
{
|
||||
/* We support four different kind of time controls:
|
||||
|
||||
@@ -103,51 +103,52 @@ void TimeManager::init(const SearchLimits& limits, int currentPly)
|
||||
int hypMTG, hypMyTime, t1, t2;
|
||||
|
||||
// Read uci parameters
|
||||
int emergencyMoveHorizon = Options["Emergency Move Horizon"].value<int>();
|
||||
int emergencyBaseTime = Options["Emergency Base Time"].value<int>();
|
||||
int emergencyMoveTime = Options["Emergency Move Time"].value<int>();
|
||||
int minThinkingTime = Options["Minimum Thinking Time"].value<int>();
|
||||
int emergencyMoveHorizon = Options["Emergency Move Horizon"];
|
||||
int emergencyBaseTime = Options["Emergency Base Time"];
|
||||
int emergencyMoveTime = Options["Emergency Move Time"];
|
||||
int minThinkingTime = Options["Minimum Thinking Time"];
|
||||
int slowMover = Options["Slow Mover"];
|
||||
|
||||
// Initialize to maximum values but unstablePVExtraTime that is reset
|
||||
unstablePVExtraTime = 0;
|
||||
optimumSearchTime = maximumSearchTime = limits.time;
|
||||
optimumSearchTime = maximumSearchTime = limits.time[us];
|
||||
|
||||
// We calculate optimum time usage for different hypothetic "moves to go"-values and choose the
|
||||
// minimum of calculated search time values. Usually the greatest hypMTG gives the minimum values.
|
||||
for (hypMTG = 1; hypMTG <= (limits.movesToGo ? Min(limits.movesToGo, MoveHorizon) : MoveHorizon); hypMTG++)
|
||||
for (hypMTG = 1; hypMTG <= (limits.movestogo ? std::min(limits.movestogo, MoveHorizon) : MoveHorizon); hypMTG++)
|
||||
{
|
||||
// Calculate thinking time for hypothetic "moves to go"-value
|
||||
hypMyTime = limits.time
|
||||
+ limits.increment * (hypMTG - 1)
|
||||
hypMyTime = limits.time[us]
|
||||
+ limits.inc[us] * (hypMTG - 1)
|
||||
- emergencyBaseTime
|
||||
- emergencyMoveTime * Min(hypMTG, emergencyMoveHorizon);
|
||||
- emergencyMoveTime * std::min(hypMTG, emergencyMoveHorizon);
|
||||
|
||||
hypMyTime = Max(hypMyTime, 0);
|
||||
hypMyTime = std::max(hypMyTime, 0);
|
||||
|
||||
t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, currentPly);
|
||||
t2 = minThinkingTime + remaining<MaxTime>(hypMyTime, hypMTG, currentPly);
|
||||
t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, currentPly, slowMover);
|
||||
t2 = minThinkingTime + remaining<MaxTime>(hypMyTime, hypMTG, currentPly, slowMover);
|
||||
|
||||
optimumSearchTime = Min(optimumSearchTime, t1);
|
||||
maximumSearchTime = Min(maximumSearchTime, t2);
|
||||
optimumSearchTime = std::min(optimumSearchTime, t1);
|
||||
maximumSearchTime = std::min(maximumSearchTime, t2);
|
||||
}
|
||||
|
||||
if (Options["Ponder"].value<bool>())
|
||||
if (Options["Ponder"])
|
||||
optimumSearchTime += optimumSearchTime / 4;
|
||||
|
||||
// Make sure that maxSearchTime is not over absoluteMaxSearchTime
|
||||
optimumSearchTime = Min(optimumSearchTime, maximumSearchTime);
|
||||
optimumSearchTime = std::min(optimumSearchTime, maximumSearchTime);
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
template<TimeType T>
|
||||
int remaining(int myTime, int movesToGo, int currentPly)
|
||||
int remaining(int myTime, int movesToGo, int currentPly, int slowMover)
|
||||
{
|
||||
const float TMaxRatio = (T == OptimumTime ? 1 : MaxRatio);
|
||||
const float TStealRatio = (T == OptimumTime ? 0 : StealRatio);
|
||||
|
||||
int thisMoveImportance = move_importance(currentPly);
|
||||
int thisMoveImportance = move_importance(currentPly) * slowMover / 100;
|
||||
int otherMovesImportance = 0;
|
||||
|
||||
for (int i = 1; i < movesToGo; i++)
|
||||
@@ -156,6 +157,6 @@ namespace {
|
||||
float ratio1 = (TMaxRatio * thisMoveImportance) / float(TMaxRatio * thisMoveImportance + otherMovesImportance);
|
||||
float ratio2 = (thisMoveImportance + TStealRatio * otherMovesImportance) / float(thisMoveImportance + otherMovesImportance);
|
||||
|
||||
return int(floor(myTime * Min(ratio1, ratio2)));
|
||||
return int(floor(myTime * std::min(ratio1, ratio2)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,12 +20,12 @@
|
||||
#if !defined(TIMEMAN_H_INCLUDED)
|
||||
#define TIMEMAN_H_INCLUDED
|
||||
|
||||
struct SearchLimits;
|
||||
/// The TimeManager class computes the optimal time to think depending on the
|
||||
/// maximum available time, the move game number and other parameters.
|
||||
|
||||
class TimeManager {
|
||||
public:
|
||||
|
||||
void init(const SearchLimits& limits, int currentPly);
|
||||
void init(const Search::LimitsType& limits, int currentPly, Color us);
|
||||
void pv_instability(int curChanges, int prevChanges);
|
||||
int available_time() const { return optimumSearchTime + unstablePVExtraTime; }
|
||||
int maximum_time() const { return maximumSearchTime; }
|
||||
|
||||
27
src/tt.cpp
27
src/tt.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,10 +17,10 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
|
||||
#include "bitboard.h"
|
||||
#include "tt.h"
|
||||
|
||||
TranspositionTable TT; // Our global transposition table
|
||||
@@ -38,18 +38,13 @@ TranspositionTable::~TranspositionTable() {
|
||||
|
||||
|
||||
/// TranspositionTable::set_size() sets the size of the transposition table,
|
||||
/// measured in megabytes.
|
||||
/// measured in megabytes. Transposition table consists of a power of 2 number of
|
||||
/// TTCluster and each cluster consists of ClusterSize number of TTEntries. Each
|
||||
/// non-empty entry contains information of exactly one position.
|
||||
|
||||
void TranspositionTable::set_size(size_t mbSize) {
|
||||
|
||||
size_t newSize = 1024;
|
||||
|
||||
// Transposition table consists of clusters and each cluster consists
|
||||
// of ClusterSize number of TTEntries. Each non-empty entry contains
|
||||
// information of exactly one position and newSize is the number of
|
||||
// clusters we are going to allocate.
|
||||
while (2ULL * newSize * sizeof(TTCluster) <= (mbSize << 20))
|
||||
newSize *= 2;
|
||||
size_t newSize = 1ULL << msb((mbSize << 20) / sizeof(TTCluster));
|
||||
|
||||
if (newSize == size)
|
||||
return;
|
||||
@@ -57,13 +52,15 @@ void TranspositionTable::set_size(size_t mbSize) {
|
||||
size = newSize;
|
||||
delete [] entries;
|
||||
entries = new (std::nothrow) TTCluster[size];
|
||||
|
||||
if (!entries)
|
||||
{
|
||||
std::cerr << "Failed to allocate " << mbSize
|
||||
<< " MB for transposition table." << std::endl;
|
||||
<< "MB for transposition table." << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
clear();
|
||||
|
||||
clear(); // Operator new is not guaranteed to initialize memory to zero
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +82,7 @@ void TranspositionTable::clear() {
|
||||
/// more valuable than a TTEntry t2 if t1 is from the current search and t2 is from
|
||||
/// a previous search, or if the depth of t1 is bigger than the depth of t2.
|
||||
|
||||
void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m, Value statV, Value kingD) {
|
||||
void TranspositionTable::store(const Key posKey, Value v, Bound t, Depth d, Move m, Value statV, Value kingD) {
|
||||
|
||||
int c1, c2, c3;
|
||||
TTEntry *tte, *replace;
|
||||
@@ -107,7 +104,7 @@ void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d,
|
||||
|
||||
// Implement replace strategy
|
||||
c1 = (replace->generation() == generation ? 2 : 0);
|
||||
c2 = (tte->generation() == generation || tte->type() == VALUE_TYPE_EXACT ? -2 : 0);
|
||||
c2 = (tte->generation() == generation || tte->type() == BOUND_EXACT ? -2 : 0);
|
||||
c3 = (tte->depth() < replace->depth() ? 1 : 0);
|
||||
|
||||
if (c1 + c2 + c3 > 0)
|
||||
|
||||
51
src/tt.h
51
src/tt.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,12 +20,9 @@
|
||||
#if !defined(TT_H_INCLUDED)
|
||||
#define TT_H_INCLUDED
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "move.h"
|
||||
#include "misc.h"
|
||||
#include "types.h"
|
||||
|
||||
|
||||
/// The TTEntry is the class of transposition table entries
|
||||
///
|
||||
/// A TTEntry needs 128 bits to be stored
|
||||
@@ -47,11 +44,11 @@
|
||||
class TTEntry {
|
||||
|
||||
public:
|
||||
void save(uint32_t k, Value v, ValueType t, Depth d, Move m, int g, Value statV, Value statM) {
|
||||
void save(uint32_t k, Value v, Bound b, Depth d, Move m, int g, Value statV, Value statM) {
|
||||
|
||||
key32 = (uint32_t)k;
|
||||
move16 = (uint16_t)m;
|
||||
valueType = (uint8_t)t;
|
||||
bound = (uint8_t)b;
|
||||
generation8 = (uint8_t)g;
|
||||
value16 = (int16_t)v;
|
||||
depth16 = (int16_t)d;
|
||||
@@ -64,7 +61,7 @@ public:
|
||||
Depth depth() const { return (Depth)depth16; }
|
||||
Move move() const { return (Move)move16; }
|
||||
Value value() const { return (Value)value16; }
|
||||
ValueType type() const { return (ValueType)valueType; }
|
||||
Bound type() const { return (Bound)bound; }
|
||||
int generation() const { return (int)generation8; }
|
||||
Value static_value() const { return (Value)staticValue; }
|
||||
Value static_value_margin() const { return (Value)staticMargin; }
|
||||
@@ -72,7 +69,7 @@ public:
|
||||
private:
|
||||
uint32_t key32;
|
||||
uint16_t move16;
|
||||
uint8_t valueType, generation8;
|
||||
uint8_t bound, generation8;
|
||||
int16_t value16, depth16, staticValue, staticMargin;
|
||||
};
|
||||
|
||||
@@ -103,7 +100,7 @@ public:
|
||||
~TranspositionTable();
|
||||
void set_size(size_t mbSize);
|
||||
void clear();
|
||||
void store(const Key posKey, Value v, ValueType type, Depth d, Move m, Value statV, Value kingD);
|
||||
void store(const Key posKey, Value v, Bound type, Depth d, Move m, Value statV, Value kingD);
|
||||
TTEntry* probe(const Key posKey) const;
|
||||
void new_search();
|
||||
TTEntry* first_entry(const Key posKey) const;
|
||||
@@ -136,38 +133,4 @@ inline void TranspositionTable::refresh(const TTEntry* tte) const {
|
||||
const_cast<TTEntry*>(tte)->set_generation(generation);
|
||||
}
|
||||
|
||||
|
||||
/// A simple fixed size hash table used to store pawns and material
|
||||
/// configurations. It is basically just an array of Entry objects.
|
||||
/// Without cluster concept or overwrite policy.
|
||||
|
||||
template<class Entry, int HashSize>
|
||||
struct SimpleHash {
|
||||
|
||||
typedef SimpleHash<Entry, HashSize> Base;
|
||||
|
||||
void init() {
|
||||
|
||||
if (entries)
|
||||
return;
|
||||
|
||||
entries = new (std::nothrow) Entry[HashSize];
|
||||
if (!entries)
|
||||
{
|
||||
std::cerr << "Failed to allocate " << HashSize * sizeof(Entry)
|
||||
<< " bytes for hash table." << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
memset(entries, 0, HashSize * sizeof(Entry));
|
||||
}
|
||||
|
||||
virtual ~SimpleHash() { delete [] entries; }
|
||||
|
||||
Entry* probe(Key key) const { return entries + ((uint32_t)key & (HashSize - 1)); }
|
||||
void prefetch(Key key) const { ::prefetch((char*)probe(key)); }
|
||||
|
||||
protected:
|
||||
Entry* entries;
|
||||
};
|
||||
|
||||
#endif // !defined(TT_H_INCLUDED)
|
||||
|
||||
575
src/types.h
575
src/types.h
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,152 +20,138 @@
|
||||
#if !defined(TYPES_H_INCLUDED)
|
||||
#define TYPES_H_INCLUDED
|
||||
|
||||
/// For Linux and OSX configuration is done automatically using Makefile. To get
|
||||
/// started type 'make help'.
|
||||
///
|
||||
/// For Windows, part of the configuration is detected automatically, but some
|
||||
/// switches need to be set manually:
|
||||
///
|
||||
/// -DNDEBUG | Disable debugging mode. Use always.
|
||||
///
|
||||
/// -DNO_PREFETCH | Disable use of prefetch asm-instruction. A must if you want
|
||||
/// | the executable to run on some very old machines.
|
||||
///
|
||||
/// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
|
||||
/// | only in 64-bit mode. For compiling requires hardware with
|
||||
/// | popcnt support.
|
||||
|
||||
#include <cctype>
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
|
||||
#if defined(_MSC_VER)
|
||||
#include "platform.h"
|
||||
|
||||
// Disable some silly and noisy warning from MSVC compiler
|
||||
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
|
||||
#pragma warning(disable: 4127) // Conditional expression is constant
|
||||
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
|
||||
|
||||
// MSVC does not support <inttypes.h>
|
||||
typedef signed __int8 int8_t;
|
||||
typedef unsigned __int8 uint8_t;
|
||||
typedef signed __int16 int16_t;
|
||||
typedef unsigned __int16 uint16_t;
|
||||
typedef signed __int32 int32_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
typedef signed __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
|
||||
#else
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#endif
|
||||
|
||||
#define Min(x, y) (((x) < (y)) ? (x) : (y))
|
||||
#define Max(x, y) (((x) < (y)) ? (y) : (x))
|
||||
|
||||
////
|
||||
//// Configuration
|
||||
////
|
||||
|
||||
//// For Linux and OSX configuration is done automatically using Makefile.
|
||||
//// To get started type "make help".
|
||||
////
|
||||
//// For windows part of the configuration is detected automatically, but
|
||||
//// some switches need to be set manually:
|
||||
////
|
||||
//// -DNDEBUG | Disable debugging mode. Use always.
|
||||
////
|
||||
//// -DNO_PREFETCH | Disable use of prefetch asm-instruction. A must if you want the
|
||||
//// | executable to run on some very old machines.
|
||||
////
|
||||
//// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction.
|
||||
//// | Works only in 64-bit mode. For compiling requires hardware
|
||||
//// | with popcnt support. Around 4% speed-up.
|
||||
////
|
||||
//// -DOLD_LOCKS | By default under Windows are used the fast Slim Reader/Writer (SRW)
|
||||
//// | Locks and Condition Variables: these are not supported by Windows XP
|
||||
//// | and older, to compile for those platforms you should enable OLD_LOCKS.
|
||||
|
||||
// Automatic detection for 64-bit under Windows
|
||||
#if defined(_WIN64)
|
||||
#define IS_64BIT
|
||||
# include <intrin.h> // MSVC popcnt and bsfq instrinsics
|
||||
# define IS_64BIT
|
||||
# define USE_BSFQ
|
||||
#endif
|
||||
|
||||
// Automatic detection for use of bsfq asm-instruction under Windows
|
||||
#if defined(_WIN64)
|
||||
#define USE_BSFQ
|
||||
#endif
|
||||
|
||||
// Intel header for _mm_popcnt_u64() intrinsic
|
||||
#if defined(USE_POPCNT) && defined(_MSC_VER) && defined(__INTEL_COMPILER)
|
||||
#include <nmmintrin.h>
|
||||
# include <nmmintrin.h> // Intel header for _mm_popcnt_u64() intrinsic
|
||||
#endif
|
||||
|
||||
// Cache line alignment specification
|
||||
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
|
||||
#define CACHE_LINE_ALIGNMENT __declspec(align(64))
|
||||
# define CACHE_LINE_ALIGNMENT __declspec(align(64))
|
||||
#else
|
||||
#define CACHE_LINE_ALIGNMENT __attribute__ ((aligned(64)))
|
||||
# define CACHE_LINE_ALIGNMENT __attribute__ ((aligned(64)))
|
||||
#endif
|
||||
|
||||
// Define a __cpuid() function for gcc compilers, for Intel and MSVC
|
||||
// is already available as an intrinsic.
|
||||
#if defined(_MSC_VER)
|
||||
#include <intrin.h>
|
||||
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
|
||||
inline void __cpuid(int CPUInfo[4], int InfoType)
|
||||
{
|
||||
int* eax = CPUInfo + 0;
|
||||
int* ebx = CPUInfo + 1;
|
||||
int* ecx = CPUInfo + 2;
|
||||
int* edx = CPUInfo + 3;
|
||||
|
||||
*eax = InfoType;
|
||||
*ecx = 0;
|
||||
__asm__("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
|
||||
: "0" (*eax), "2" (*ecx));
|
||||
}
|
||||
#else
|
||||
inline void __cpuid(int CPUInfo[4], int)
|
||||
{
|
||||
CPUInfo[0] = CPUInfo[1] = CPUInfo[2] = CPUInfo[3] = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Define FORCE_INLINE macro to force inlining overriding compiler choice
|
||||
#if defined(_MSC_VER)
|
||||
#define FORCE_INLINE __forceinline
|
||||
# define FORCE_INLINE __forceinline
|
||||
#elif defined(__GNUC__)
|
||||
#define FORCE_INLINE inline __attribute__((always_inline))
|
||||
# define FORCE_INLINE inline __attribute__((always_inline))
|
||||
#else
|
||||
#define FORCE_INLINE inline
|
||||
# define FORCE_INLINE inline
|
||||
#endif
|
||||
|
||||
/// cpu_has_popcnt() detects support for popcnt instruction at runtime
|
||||
inline bool cpu_has_popcnt() {
|
||||
|
||||
int CPUInfo[4] = {-1};
|
||||
__cpuid(CPUInfo, 0x00000001);
|
||||
return (CPUInfo[2] >> 23) & 1;
|
||||
}
|
||||
|
||||
/// CpuHasPOPCNT is a global constant initialized at startup that
|
||||
/// is set to true if CPU on which application runs supports popcnt
|
||||
/// hardware instruction. Unless USE_POPCNT is not defined.
|
||||
#if defined(USE_POPCNT)
|
||||
const bool CpuHasPOPCNT = cpu_has_popcnt();
|
||||
const bool HasPopCnt = true;
|
||||
#else
|
||||
const bool CpuHasPOPCNT = false;
|
||||
const bool HasPopCnt = false;
|
||||
#endif
|
||||
|
||||
|
||||
/// CpuIs64Bit is a global constant initialized at compile time that
|
||||
/// is set to true if CPU on which application runs is a 64 bits.
|
||||
#if defined(IS_64BIT)
|
||||
const bool CpuIs64Bit = true;
|
||||
const bool Is64Bit = true;
|
||||
#else
|
||||
const bool CpuIs64Bit = false;
|
||||
const bool Is64Bit = false;
|
||||
#endif
|
||||
|
||||
#include <string>
|
||||
|
||||
typedef uint64_t Key;
|
||||
typedef uint64_t Bitboard;
|
||||
|
||||
const int PLY_MAX = 100;
|
||||
const int PLY_MAX_PLUS_2 = PLY_MAX + 2;
|
||||
const int MAX_MOVES = 192;
|
||||
const int MAX_PLY = 100;
|
||||
const int MAX_PLY_PLUS_2 = MAX_PLY + 2;
|
||||
|
||||
enum ValueType {
|
||||
VALUE_TYPE_NONE = 0,
|
||||
VALUE_TYPE_UPPER = 1,
|
||||
VALUE_TYPE_LOWER = 2,
|
||||
VALUE_TYPE_EXACT = VALUE_TYPE_UPPER | VALUE_TYPE_LOWER
|
||||
const Bitboard FileABB = 0x0101010101010101ULL;
|
||||
const Bitboard FileBBB = FileABB << 1;
|
||||
const Bitboard FileCBB = FileABB << 2;
|
||||
const Bitboard FileDBB = FileABB << 3;
|
||||
const Bitboard FileEBB = FileABB << 4;
|
||||
const Bitboard FileFBB = FileABB << 5;
|
||||
const Bitboard FileGBB = FileABB << 6;
|
||||
const Bitboard FileHBB = FileABB << 7;
|
||||
|
||||
const Bitboard Rank1BB = 0xFF;
|
||||
const Bitboard Rank2BB = Rank1BB << (8 * 1);
|
||||
const Bitboard Rank3BB = Rank1BB << (8 * 2);
|
||||
const Bitboard Rank4BB = Rank1BB << (8 * 3);
|
||||
const Bitboard Rank5BB = Rank1BB << (8 * 4);
|
||||
const Bitboard Rank6BB = Rank1BB << (8 * 5);
|
||||
const Bitboard Rank7BB = Rank1BB << (8 * 6);
|
||||
const Bitboard Rank8BB = Rank1BB << (8 * 7);
|
||||
|
||||
|
||||
/// A move needs 16 bits to be stored
|
||||
///
|
||||
/// bit 0- 5: destination square (from 0 to 63)
|
||||
/// bit 6-11: origin square (from 0 to 63)
|
||||
/// bit 12-13: promotion piece type - 2 (from KNIGHT-2 to QUEEN-2)
|
||||
/// bit 14-15: special move flag: promotion (1), en passant (2), castle (3)
|
||||
///
|
||||
/// Special cases are MOVE_NONE and MOVE_NULL. We can sneak these in because in
|
||||
/// any normal move destination square is always different from origin square
|
||||
/// while MOVE_NONE and MOVE_NULL have the same origin and destination square.
|
||||
|
||||
enum Move {
|
||||
MOVE_NONE = 0,
|
||||
MOVE_NULL = 65
|
||||
};
|
||||
|
||||
enum MoveType {
|
||||
NORMAL = 0,
|
||||
PROMOTION = 1 << 14,
|
||||
ENPASSANT = 2 << 14,
|
||||
CASTLE = 3 << 14
|
||||
};
|
||||
|
||||
enum CastleRight { // Defined as in PolyGlot book hash key
|
||||
CASTLES_NONE = 0,
|
||||
WHITE_OO = 1,
|
||||
WHITE_OOO = 2,
|
||||
BLACK_OO = 4,
|
||||
BLACK_OOO = 8,
|
||||
ALL_CASTLES = 15
|
||||
};
|
||||
|
||||
enum CastlingSide {
|
||||
KING_SIDE,
|
||||
QUEEN_SIDE
|
||||
};
|
||||
|
||||
enum ScaleFactor {
|
||||
SCALE_FACTOR_DRAW = 0,
|
||||
SCALE_FACTOR_NORMAL = 64,
|
||||
SCALE_FACTOR_MAX = 128,
|
||||
SCALE_FACTOR_NONE = 255
|
||||
};
|
||||
|
||||
enum Bound {
|
||||
BOUND_NONE = 0,
|
||||
BOUND_UPPER = 1,
|
||||
BOUND_LOWER = 2,
|
||||
BOUND_EXACT = BOUND_UPPER | BOUND_LOWER
|
||||
};
|
||||
|
||||
enum Value {
|
||||
@@ -176,34 +162,44 @@ enum Value {
|
||||
VALUE_INFINITE = 30001,
|
||||
VALUE_NONE = 30002,
|
||||
|
||||
VALUE_MATE_IN_PLY_MAX = VALUE_MATE - PLY_MAX,
|
||||
VALUE_MATED_IN_PLY_MAX = -VALUE_MATE + PLY_MAX,
|
||||
VALUE_MATE_IN_MAX_PLY = VALUE_MATE - MAX_PLY,
|
||||
VALUE_MATED_IN_MAX_PLY = -VALUE_MATE + MAX_PLY,
|
||||
|
||||
VALUE_ENSURE_INTEGER_SIZE_P = INT_MAX,
|
||||
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN
|
||||
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN,
|
||||
|
||||
Mg = 0, Eg = 1,
|
||||
|
||||
PawnValueMg = 198, PawnValueEg = 258,
|
||||
KnightValueMg = 817, KnightValueEg = 846,
|
||||
BishopValueMg = 836, BishopValueEg = 857,
|
||||
RookValueMg = 1270, RookValueEg = 1278,
|
||||
QueenValueMg = 2521, QueenValueEg = 2558
|
||||
};
|
||||
|
||||
enum PieceType {
|
||||
PIECE_TYPE_NONE = 0,
|
||||
NO_PIECE_TYPE = 0, ALL_PIECES = 0,
|
||||
PAWN = 1, KNIGHT = 2, BISHOP = 3, ROOK = 4, QUEEN = 5, KING = 6
|
||||
};
|
||||
|
||||
enum Piece {
|
||||
PIECE_NONE_DARK_SQ = 0, WP = 1, WN = 2, WB = 3, WR = 4, WQ = 5, WK = 6,
|
||||
BP = 9, BN = 10, BB = 11, BR = 12, BQ = 13, BK = 14, PIECE_NONE = 16
|
||||
NO_PIECE = 16, // color_of(NO_PIECE) == NO_COLOR
|
||||
W_PAWN = 1, W_KNIGHT = 2, W_BISHOP = 3, W_ROOK = 4, W_QUEEN = 5, W_KING = 6,
|
||||
B_PAWN = 9, B_KNIGHT = 10, B_BISHOP = 11, B_ROOK = 12, B_QUEEN = 13, B_KING = 14
|
||||
};
|
||||
|
||||
enum Color {
|
||||
WHITE, BLACK, COLOR_NONE
|
||||
WHITE, BLACK, NO_COLOR
|
||||
};
|
||||
|
||||
enum Depth {
|
||||
|
||||
ONE_PLY = 2,
|
||||
|
||||
DEPTH_ZERO = 0 * ONE_PLY,
|
||||
DEPTH_QS_CHECKS = -1 * ONE_PLY,
|
||||
DEPTH_QS_NO_CHECKS = -2 * ONE_PLY,
|
||||
DEPTH_ZERO = 0 * ONE_PLY,
|
||||
DEPTH_QS_CHECKS = -1 * ONE_PLY,
|
||||
DEPTH_QS_NO_CHECKS = -2 * ONE_PLY,
|
||||
DEPTH_QS_RECAPTURES = -5 * ONE_PLY,
|
||||
|
||||
DEPTH_NONE = -127 * ONE_PLY
|
||||
};
|
||||
@@ -240,42 +236,54 @@ enum Rank {
|
||||
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8
|
||||
};
|
||||
|
||||
enum SquareColor {
|
||||
DARK, LIGHT
|
||||
};
|
||||
|
||||
enum ScaleFactor {
|
||||
SCALE_FACTOR_ZERO = 0,
|
||||
SCALE_FACTOR_NORMAL = 64,
|
||||
SCALE_FACTOR_MAX = 128,
|
||||
SCALE_FACTOR_NONE = 255
|
||||
};
|
||||
|
||||
|
||||
/// Score enum keeps a midgame and an endgame value in a single
|
||||
/// integer (enum), first LSB 16 bits are used to store endgame
|
||||
/// value, while upper bits are used for midgame value. Compiler
|
||||
/// is free to choose the enum type as long as can keep its data,
|
||||
/// so ensure Score to be an integer type.
|
||||
/// Score enum keeps a midgame and an endgame value in a single integer (enum),
|
||||
/// first LSB 16 bits are used to store endgame value, while upper bits are used
|
||||
/// for midgame value. Compiler is free to choose the enum type as long as can
|
||||
/// keep its data, so ensure Score to be an integer type.
|
||||
enum Score {
|
||||
SCORE_ZERO = 0,
|
||||
SCORE_ENSURE_INTEGER_SIZE_P = INT_MAX,
|
||||
SCORE_ENSURE_INTEGER_SIZE_N = INT_MIN
|
||||
SCORE_ZERO = 0,
|
||||
SCORE_ENSURE_INTEGER_SIZE_P = INT_MAX,
|
||||
SCORE_ENSURE_INTEGER_SIZE_N = INT_MIN
|
||||
};
|
||||
|
||||
#define ENABLE_OPERATORS_ON(T) \
|
||||
inline T operator+ (const T d1, const T d2) { return T(int(d1) + int(d2)); } \
|
||||
inline T operator- (const T d1, const T d2) { return T(int(d1) - int(d2)); } \
|
||||
inline T operator* (int i, const T d) { return T(i * int(d)); } \
|
||||
inline T operator* (const T d, int i) { return T(int(d) * i); } \
|
||||
inline T operator/ (const T d, int i) { return T(int(d) / i); } \
|
||||
inline T operator- (const T d) { return T(-int(d)); } \
|
||||
inline T operator++ (T& d, int) {d = T(int(d) + 1); return d; } \
|
||||
inline T operator-- (T& d, int) { d = T(int(d) - 1); return d; } \
|
||||
inline void operator+= (T& d1, const T d2) { d1 = d1 + d2; } \
|
||||
inline void operator-= (T& d1, const T d2) { d1 = d1 - d2; } \
|
||||
inline void operator*= (T& d, int i) { d = T(int(d) * i); } \
|
||||
inline void operator/= (T& d, int i) { d = T(int(d) / i); }
|
||||
inline Score make_score(int mg, int eg) { return Score((mg << 16) + eg); }
|
||||
|
||||
/// Extracting the signed lower and upper 16 bits it not so trivial because
|
||||
/// according to the standard a simple cast to short is implementation defined
|
||||
/// and so is a right shift of a signed integer.
|
||||
inline Value mg_value(Score s) { return Value(((s + 32768) & ~0xffff) / 0x10000); }
|
||||
|
||||
/// On Intel 64 bit we have a small speed regression with the standard conforming
|
||||
/// version, so use a faster code in this case that, although not 100% standard
|
||||
/// compliant it seems to work for Intel and MSVC.
|
||||
#if defined(IS_64BIT) && (!defined(__GNUC__) || defined(__INTEL_COMPILER))
|
||||
|
||||
inline Value eg_value(Score s) { return Value(int16_t(s & 0xffff)); }
|
||||
|
||||
#else
|
||||
|
||||
inline Value eg_value(Score s) {
|
||||
return Value((int)(unsigned(s) & 0x7fffu) - (int)(unsigned(s) & 0x8000u));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#define ENABLE_SAFE_OPERATORS_ON(T) \
|
||||
inline T operator+(const T d1, const T d2) { return T(int(d1) + int(d2)); } \
|
||||
inline T operator-(const T d1, const T d2) { return T(int(d1) - int(d2)); } \
|
||||
inline T operator*(int i, const T d) { return T(i * int(d)); } \
|
||||
inline T operator*(const T d, int i) { return T(int(d) * i); } \
|
||||
inline T operator-(const T d) { return T(-int(d)); } \
|
||||
inline T& operator+=(T& d1, const T d2) { d1 = d1 + d2; return d1; } \
|
||||
inline T& operator-=(T& d1, const T d2) { d1 = d1 - d2; return d1; } \
|
||||
inline T& operator*=(T& d, int i) { d = T(int(d) * i); return d; }
|
||||
|
||||
#define ENABLE_OPERATORS_ON(T) ENABLE_SAFE_OPERATORS_ON(T) \
|
||||
inline T operator++(T& d, int) { d = T(int(d) + 1); return d; } \
|
||||
inline T operator--(T& d, int) { d = T(int(d) - 1); return d; } \
|
||||
inline T operator/(const T d, int i) { return T(int(d) / i); } \
|
||||
inline T& operator/=(T& d, int i) { d = T(int(d) / i); return d; }
|
||||
|
||||
ENABLE_OPERATORS_ON(Value)
|
||||
ENABLE_OPERATORS_ON(PieceType)
|
||||
@@ -286,185 +294,200 @@ ENABLE_OPERATORS_ON(Square)
|
||||
ENABLE_OPERATORS_ON(File)
|
||||
ENABLE_OPERATORS_ON(Rank)
|
||||
|
||||
#undef ENABLE_OPERATORS_ON
|
||||
/// Added operators for adding integers to a Value
|
||||
inline Value operator+(Value v, int i) { return Value(int(v) + i); }
|
||||
inline Value operator-(Value v, int i) { return Value(int(v) - i); }
|
||||
|
||||
// Extra operators for adding integers to a Value
|
||||
inline Value operator+ (Value v, int i) { return Value(int(v) + i); }
|
||||
inline Value operator- (Value v, int i) { return Value(int(v) - i); }
|
||||
ENABLE_SAFE_OPERATORS_ON(Score)
|
||||
|
||||
// Extracting the _signed_ lower and upper 16 bits it not so trivial
|
||||
// because according to the standard a simple cast to short is
|
||||
// implementation defined and so is a right shift of a signed integer.
|
||||
inline Value mg_value(Score s) { return Value(((int(s) + 32768) & ~0xffff) / 0x10000); }
|
||||
|
||||
// Unfortunatly on Intel 64 bit we have a small speed regression, so use a faster code in
|
||||
// this case, although not 100% standard compliant it seems to work for Intel and MSVC.
|
||||
#if defined(IS_64BIT) && (!defined(__GNUC__) || defined(__INTEL_COMPILER))
|
||||
inline Value eg_value(Score s) { return Value(int16_t(s & 0xffff)); }
|
||||
#else
|
||||
inline Value eg_value(Score s) { return Value((int)(unsigned(s) & 0x7fffu) - (int)(unsigned(s) & 0x8000u)); }
|
||||
#endif
|
||||
|
||||
inline Score make_score(int mg, int eg) { return Score((mg << 16) + eg); }
|
||||
|
||||
// Division must be handled separately for each term
|
||||
inline Score operator/(Score s, int i) { return make_score(mg_value(s) / i, eg_value(s) / i); }
|
||||
|
||||
// Only declared but not defined. We don't want to multiply two scores due to
|
||||
// a very high risk of overflow. So user should explicitly convert to integer.
|
||||
/// Only declared but not defined. We don't want to multiply two scores due to
|
||||
/// a very high risk of overflow. So user should explicitly convert to integer.
|
||||
inline Score operator*(Score s1, Score s2);
|
||||
|
||||
// Remaining Score operators are standard
|
||||
inline Score operator+ (const Score d1, const Score d2) { return Score(int(d1) + int(d2)); }
|
||||
inline Score operator- (const Score d1, const Score d2) { return Score(int(d1) - int(d2)); }
|
||||
inline Score operator* (int i, const Score d) { return Score(i * int(d)); }
|
||||
inline Score operator* (const Score d, int i) { return Score(int(d) * i); }
|
||||
inline Score operator- (const Score d) { return Score(-int(d)); }
|
||||
inline void operator+= (Score& d1, const Score d2) { d1 = d1 + d2; }
|
||||
inline void operator-= (Score& d1, const Score d2) { d1 = d1 - d2; }
|
||||
inline void operator*= (Score& d, int i) { d = Score(int(d) * i); }
|
||||
inline void operator/= (Score& d, int i) { d = Score(int(d) / i); }
|
||||
/// Division of a Score must be handled separately for each term
|
||||
inline Score operator/(Score s, int i) {
|
||||
return make_score(mg_value(s) / i, eg_value(s) / i);
|
||||
}
|
||||
|
||||
const Value PawnValueMidgame = Value(0x0C6);
|
||||
const Value PawnValueEndgame = Value(0x102);
|
||||
const Value KnightValueMidgame = Value(0x331);
|
||||
const Value KnightValueEndgame = Value(0x34E);
|
||||
const Value BishopValueMidgame = Value(0x344);
|
||||
const Value BishopValueEndgame = Value(0x359);
|
||||
const Value RookValueMidgame = Value(0x4F6);
|
||||
const Value RookValueEndgame = Value(0x4FE);
|
||||
const Value QueenValueMidgame = Value(0x9D9);
|
||||
const Value QueenValueEndgame = Value(0x9FE);
|
||||
/// Weight score v by score w trying to prevent overflow
|
||||
inline Score apply_weight(Score v, Score w) {
|
||||
return make_score((int(mg_value(v)) * mg_value(w)) / 0x100,
|
||||
(int(eg_value(v)) * eg_value(w)) / 0x100);
|
||||
}
|
||||
|
||||
inline Value value_mate_in(int ply) {
|
||||
#undef ENABLE_OPERATORS_ON
|
||||
#undef ENABLE_SAFE_OPERATORS_ON
|
||||
|
||||
namespace Zobrist {
|
||||
|
||||
extern Key psq[2][8][64]; // [color][pieceType][square / piece count]
|
||||
extern Key enpassant[8]; // [file]
|
||||
extern Key castle[16]; // [castleRight]
|
||||
extern Key side;
|
||||
extern Key exclusion;
|
||||
|
||||
void init();
|
||||
}
|
||||
|
||||
CACHE_LINE_ALIGNMENT
|
||||
|
||||
extern Score pieceSquareTable[16][64]; // [piece][square]
|
||||
extern Value PieceValue[2][18]; // [Mg / Eg][piece / pieceType]
|
||||
extern int SquareDistance[64][64]; // [square][square]
|
||||
|
||||
struct MoveStack {
|
||||
Move move;
|
||||
int score;
|
||||
};
|
||||
|
||||
inline bool operator<(const MoveStack& f, const MoveStack& s) {
|
||||
return f.score < s.score;
|
||||
}
|
||||
|
||||
inline Color operator~(Color c) {
|
||||
return Color(c ^ 1);
|
||||
}
|
||||
|
||||
inline Square operator~(Square s) {
|
||||
return Square(s ^ 56); // Vertical flip SQ_A1 -> SQ_A8
|
||||
}
|
||||
|
||||
inline Square operator|(File f, Rank r) {
|
||||
return Square((r << 3) | f);
|
||||
}
|
||||
|
||||
inline Value mate_in(int ply) {
|
||||
return VALUE_MATE - ply;
|
||||
}
|
||||
|
||||
inline Value value_mated_in(int ply) {
|
||||
inline Value mated_in(int ply) {
|
||||
return -VALUE_MATE + ply;
|
||||
}
|
||||
|
||||
inline Piece make_piece(Color c, PieceType pt) {
|
||||
return Piece((int(c) << 3) | int(pt));
|
||||
return Piece((c << 3) | pt);
|
||||
}
|
||||
|
||||
inline PieceType type_of_piece(Piece p) {
|
||||
return PieceType(int(p) & 7);
|
||||
inline CastleRight make_castle_right(Color c, CastlingSide s) {
|
||||
return CastleRight(WHITE_OO << ((s == QUEEN_SIDE) + 2 * c));
|
||||
}
|
||||
|
||||
inline Color color_of_piece(Piece p) {
|
||||
return Color(int(p) >> 3);
|
||||
inline PieceType type_of(Piece p) {
|
||||
return PieceType(p & 7);
|
||||
}
|
||||
|
||||
inline Color opposite_color(Color c) {
|
||||
return Color(int(c) ^ 1);
|
||||
inline Color color_of(Piece p) {
|
||||
return Color(p >> 3);
|
||||
}
|
||||
|
||||
inline bool color_is_ok(Color c) {
|
||||
return c == WHITE || c == BLACK;
|
||||
inline bool is_ok(Square s) {
|
||||
return s >= SQ_A1 && s <= SQ_H8;
|
||||
}
|
||||
|
||||
inline bool piece_type_is_ok(PieceType pt) {
|
||||
return pt >= PAWN && pt <= KING;
|
||||
inline File file_of(Square s) {
|
||||
return File(s & 7);
|
||||
}
|
||||
|
||||
inline bool piece_is_ok(Piece p) {
|
||||
return piece_type_is_ok(type_of_piece(p)) && color_is_ok(color_of_piece(p));
|
||||
inline Rank rank_of(Square s) {
|
||||
return Rank(s >> 3);
|
||||
}
|
||||
|
||||
inline char piece_type_to_char(PieceType pt) {
|
||||
static const char ch[] = " PNBRQK";
|
||||
return ch[pt];
|
||||
}
|
||||
|
||||
inline Square make_square(File f, Rank r) {
|
||||
return Square((int(r) << 3) | int(f));
|
||||
}
|
||||
|
||||
inline File square_file(Square s) {
|
||||
return File(int(s) & 7);
|
||||
}
|
||||
|
||||
inline Rank square_rank(Square s) {
|
||||
return Rank(int(s) >> 3);
|
||||
}
|
||||
|
||||
inline Square flip_square(Square s) {
|
||||
return Square(int(s) ^ 56);
|
||||
}
|
||||
|
||||
inline Square flop_square(Square s) {
|
||||
return Square(int(s) ^ 7);
|
||||
inline Square mirror(Square s) {
|
||||
return Square(s ^ 7); // Horizontal flip SQ_A1 -> SQ_H1
|
||||
}
|
||||
|
||||
inline Square relative_square(Color c, Square s) {
|
||||
return Square(int(s) ^ (int(c) * 56));
|
||||
return Square(s ^ (c * 56));
|
||||
}
|
||||
|
||||
inline Rank relative_rank(Color c, Rank r) {
|
||||
return Rank(int(r) ^ (int(c) * 7));
|
||||
return Rank(r ^ (c * 7));
|
||||
}
|
||||
|
||||
inline Rank relative_rank(Color c, Square s) {
|
||||
return relative_rank(c, square_rank(s));
|
||||
return relative_rank(c, rank_of(s));
|
||||
}
|
||||
|
||||
inline SquareColor square_color(Square s) {
|
||||
return SquareColor(int(square_rank(s) + s) & 1);
|
||||
}
|
||||
|
||||
inline bool opposite_color_squares(Square s1, Square s2) {
|
||||
inline bool opposite_colors(Square s1, Square s2) {
|
||||
int s = int(s1) ^ int(s2);
|
||||
return ((s >> 3) ^ s) & 1;
|
||||
}
|
||||
|
||||
inline int file_distance(Square s1, Square s2) {
|
||||
return abs(square_file(s1) - square_file(s2));
|
||||
return abs(file_of(s1) - file_of(s2));
|
||||
}
|
||||
|
||||
inline int rank_distance(Square s1, Square s2) {
|
||||
return abs(square_rank(s1) - square_rank(s2));
|
||||
return abs(rank_of(s1) - rank_of(s2));
|
||||
}
|
||||
|
||||
inline int square_distance(Square s1, Square s2) {
|
||||
return Max(file_distance(s1, s2), rank_distance(s1, s2));
|
||||
}
|
||||
|
||||
inline File file_from_char(char c) {
|
||||
return File(c - 'a') + FILE_A;
|
||||
return SquareDistance[s1][s2];
|
||||
}
|
||||
|
||||
inline char file_to_char(File f) {
|
||||
return char(f - FILE_A + int('a'));
|
||||
}
|
||||
|
||||
inline Rank rank_from_char(char c) {
|
||||
return Rank(c - '1') + RANK_1;
|
||||
}
|
||||
|
||||
inline char rank_to_char(Rank r) {
|
||||
return char(r - RANK_1 + int('1'));
|
||||
}
|
||||
|
||||
inline const std::string square_to_string(Square s) {
|
||||
char ch[] = { file_to_char(square_file(s)), rank_to_char(square_rank(s)), 0 };
|
||||
return std::string(ch);
|
||||
}
|
||||
|
||||
inline bool file_is_ok(File f) {
|
||||
return f >= FILE_A && f <= FILE_H;
|
||||
}
|
||||
|
||||
inline bool rank_is_ok(Rank r) {
|
||||
return r >= RANK_1 && r <= RANK_8;
|
||||
}
|
||||
|
||||
inline bool square_is_ok(Square s) {
|
||||
return s >= SQ_A1 && s <= SQ_H8;
|
||||
}
|
||||
|
||||
inline Square pawn_push(Color c) {
|
||||
return c == WHITE ? DELTA_N : DELTA_S;
|
||||
}
|
||||
|
||||
inline Square from_sq(Move m) {
|
||||
return Square((m >> 6) & 0x3F);
|
||||
}
|
||||
|
||||
inline Square to_sq(Move m) {
|
||||
return Square(m & 0x3F);
|
||||
}
|
||||
|
||||
inline MoveType type_of(Move m) {
|
||||
return MoveType(m & (3 << 14));
|
||||
}
|
||||
|
||||
inline PieceType promotion_type(Move m) {
|
||||
return PieceType(((m >> 12) & 3) + 2);
|
||||
}
|
||||
|
||||
inline Move make_move(Square from, Square to) {
|
||||
return Move(to | (from << 6));
|
||||
}
|
||||
|
||||
template<MoveType T>
|
||||
inline Move make(Square from, Square to, PieceType pt = KNIGHT) {
|
||||
return Move(to | (from << 6) | T | ((pt - KNIGHT) << 12)) ;
|
||||
}
|
||||
|
||||
inline bool is_ok(Move m) {
|
||||
return from_sq(m) != to_sq(m); // Catches also MOVE_NULL and MOVE_NONE
|
||||
}
|
||||
|
||||
#include <string>
|
||||
|
||||
inline const std::string square_to_string(Square s) {
|
||||
char ch[] = { file_to_char(file_of(s)), rank_to_char(rank_of(s)), 0 };
|
||||
return ch;
|
||||
}
|
||||
|
||||
/// Our insertion sort implementation, works with pointers and iterators and is
|
||||
/// guaranteed to be stable, as is needed.
|
||||
template<typename T, typename K>
|
||||
void sort(K first, K last)
|
||||
{
|
||||
T tmp;
|
||||
K p, q;
|
||||
|
||||
for (p = first + 1; p < last; p++)
|
||||
{
|
||||
tmp = *p;
|
||||
for (q = p; q != first && *(q-1) < tmp; --q)
|
||||
*q = *(q-1);
|
||||
*q = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !defined(TYPES_H_INCLUDED)
|
||||
|
||||
363
src/uci.cpp
363
src/uci.cpp
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,231 +17,236 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include "evaluate.h"
|
||||
#include "misc.h"
|
||||
#include "move.h"
|
||||
#include "notation.h"
|
||||
#include "position.h"
|
||||
#include "search.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "ucioption.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
extern void benchmark(const Position& pos, istream& is);
|
||||
|
||||
namespace {
|
||||
|
||||
// FEN string for the initial position
|
||||
const string StartPositionFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||
// FEN string of the initial position, normal chess
|
||||
const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||
|
||||
// UCIParser is a class for parsing UCI input. The class
|
||||
// is actually a string stream built on a given input string.
|
||||
typedef istringstream UCIParser;
|
||||
// Keep track of position keys along the setup moves (from start position to the
|
||||
// position just before to start searching). Needed by repetition draw detection.
|
||||
Search::StateStackPtr SetupStates;
|
||||
|
||||
void set_option(UCIParser& up);
|
||||
void set_position(Position& pos, UCIParser& up);
|
||||
bool go(Position& pos, UCIParser& up);
|
||||
void perft(Position& pos, UCIParser& up);
|
||||
void set_option(istringstream& up);
|
||||
void set_position(Position& pos, istringstream& up);
|
||||
void go(Position& pos, istringstream& up);
|
||||
}
|
||||
|
||||
|
||||
/// execute_uci_command() takes a string as input, uses a UCIParser
|
||||
/// object to parse this text string as a UCI command, and calls
|
||||
/// the appropriate functions. In addition to the UCI commands,
|
||||
/// the function also supports a few debug commands.
|
||||
/// Wait for a command from the user, parse this text string as an UCI command,
|
||||
/// and call the appropriate functions. Also intercepts EOF from stdin to ensure
|
||||
/// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
|
||||
/// commands, the function also supports a few debug commands.
|
||||
|
||||
bool execute_uci_command(const string& cmd) {
|
||||
void UCI::loop(const string& args) {
|
||||
|
||||
static Position pos(StartPositionFEN, false, 0); // The root position
|
||||
Position pos(StartFEN, false, Threads.main_thread()); // The root position
|
||||
string cmd, token;
|
||||
|
||||
UCIParser up(cmd);
|
||||
string token;
|
||||
|
||||
up >> token; // operator>>() skips any whitespace
|
||||
|
||||
if (token == "quit")
|
||||
return false;
|
||||
|
||||
if (token == "go")
|
||||
return go(pos, up);
|
||||
|
||||
if (token == "ucinewgame")
|
||||
pos.from_fen(StartPositionFEN, false);
|
||||
|
||||
else if (token == "isready")
|
||||
cout << "readyok" << endl;
|
||||
|
||||
else if (token == "position")
|
||||
set_position(pos, up);
|
||||
|
||||
else if (token == "setoption")
|
||||
set_option(up);
|
||||
|
||||
else if (token == "perft")
|
||||
perft(pos, up);
|
||||
|
||||
else if (token == "d")
|
||||
pos.print();
|
||||
|
||||
else if (token == "flip")
|
||||
pos.flip();
|
||||
|
||||
else if (token == "eval")
|
||||
while (token != "quit")
|
||||
{
|
||||
read_evaluation_uci_options(pos.side_to_move());
|
||||
cout << trace_evaluate(pos) << endl;
|
||||
if (!args.empty())
|
||||
cmd = args;
|
||||
|
||||
else if (!getline(cin, cmd)) // Block here waiting for input
|
||||
cmd = "quit";
|
||||
|
||||
istringstream is(cmd);
|
||||
|
||||
is >> skipws >> token;
|
||||
|
||||
if (token == "quit" || token == "stop")
|
||||
{
|
||||
Search::Signals.stop = true;
|
||||
Threads.wait_for_search_finished(); // Cannot quit while threads are running
|
||||
}
|
||||
|
||||
else if (token == "ponderhit")
|
||||
{
|
||||
// The opponent has played the expected move. GUI sends "ponderhit" if
|
||||
// we were told to ponder on the same move the opponent has played. We
|
||||
// should continue searching but switching from pondering to normal search.
|
||||
Search::Limits.ponder = false;
|
||||
|
||||
if (Search::Signals.stopOnPonderhit)
|
||||
{
|
||||
Search::Signals.stop = true;
|
||||
Threads.main_thread()->wake_up(); // Could be sleeping
|
||||
}
|
||||
}
|
||||
|
||||
else if (token == "go")
|
||||
go(pos, is);
|
||||
|
||||
else if (token == "ucinewgame")
|
||||
TT.clear();
|
||||
|
||||
else if (token == "isready")
|
||||
sync_cout << "readyok" << sync_endl;
|
||||
|
||||
else if (token == "position")
|
||||
set_position(pos, is);
|
||||
|
||||
else if (token == "setoption")
|
||||
set_option(is);
|
||||
|
||||
else if (token == "d")
|
||||
pos.print();
|
||||
|
||||
else if (token == "flip")
|
||||
pos.flip();
|
||||
|
||||
else if (token == "eval")
|
||||
sync_cout << Eval::trace(pos) << sync_endl;
|
||||
|
||||
else if (token == "bench")
|
||||
benchmark(pos, is);
|
||||
|
||||
else if (token == "key")
|
||||
sync_cout << "key: " << hex << pos.key()
|
||||
<< "\nmaterial key: " << pos.material_key()
|
||||
<< "\npawn key: " << pos.pawn_key() << sync_endl;
|
||||
|
||||
else if (token == "uci")
|
||||
sync_cout << "id name " << engine_info(true)
|
||||
<< "\n" << Options
|
||||
<< "\nuciok" << sync_endl;
|
||||
|
||||
else if (token == "perft" && (is >> token)) // Read depth
|
||||
{
|
||||
stringstream ss;
|
||||
|
||||
ss << Options["Hash"] << " "
|
||||
<< Options["Threads"] << " " << token << " current perft";
|
||||
|
||||
benchmark(pos, ss);
|
||||
}
|
||||
|
||||
else
|
||||
sync_cout << "Unknown command: " << cmd << sync_endl;
|
||||
|
||||
if (!args.empty()) // Command line arguments have one-shot behaviour
|
||||
{
|
||||
Threads.wait_for_search_finished();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
else if (token == "key")
|
||||
cout << "key: " << hex << pos.get_key()
|
||||
<< "\nmaterial key: " << pos.get_material_key()
|
||||
<< "\npawn key: " << pos.get_pawn_key() << endl;
|
||||
|
||||
else if (token == "uci")
|
||||
cout << "id name " << engine_name()
|
||||
<< "\nid author " << engine_authors()
|
||||
<< "\n" << Options.print_all()
|
||||
<< "\nuciok" << endl;
|
||||
else
|
||||
cout << "Unknown command: " << cmd << endl;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
namespace {
|
||||
|
||||
// set_position() is called when engine receives the "position" UCI
|
||||
// command. The function sets up the position described in the given
|
||||
// fen string ("fen") or the starting position ("startpos") and then
|
||||
// makes the moves given in the following move list ("moves").
|
||||
// set_position() is called when engine receives the "position" UCI command.
|
||||
// The function sets up the position described in the given fen string ("fen")
|
||||
// or the starting position ("startpos") and then makes the moves given in the
|
||||
// following move list ("moves").
|
||||
|
||||
void set_position(Position& pos, UCIParser& up) {
|
||||
void set_position(Position& pos, istringstream& is) {
|
||||
|
||||
Move m;
|
||||
string token, fen;
|
||||
|
||||
up >> token; // operator>>() skips any whitespace
|
||||
is >> token;
|
||||
|
||||
if (token == "startpos")
|
||||
{
|
||||
pos.from_fen(StartPositionFEN, false);
|
||||
up >> token; // Consume "moves" token if any
|
||||
fen = StartFEN;
|
||||
is >> token; // Consume "moves" token if any
|
||||
}
|
||||
else if (token == "fen")
|
||||
{
|
||||
while (up >> token && token != "moves")
|
||||
while (is >> token && token != "moves")
|
||||
fen += token + " ";
|
||||
else
|
||||
return;
|
||||
|
||||
pos.from_fen(fen, Options["UCI_Chess960"].value<bool>());
|
||||
}
|
||||
else return;
|
||||
pos.from_fen(fen, Options["UCI_Chess960"], Threads.main_thread());
|
||||
SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
|
||||
|
||||
// Parse move list (if any)
|
||||
while (up >> token)
|
||||
pos.do_setup_move(move_from_uci(pos, token));
|
||||
}
|
||||
|
||||
|
||||
// set_option() is called when engine receives the "setoption" UCI
|
||||
// command. The function updates the corresponding UCI option ("name")
|
||||
// to the given value ("value").
|
||||
|
||||
void set_option(UCIParser& up) {
|
||||
|
||||
string token, name;
|
||||
string value = "true"; // UCI buttons don't have a "value" field
|
||||
|
||||
up >> token; // Consume "name" token
|
||||
up >> name; // Read option name
|
||||
|
||||
// Handle names with included spaces
|
||||
while (up >> token && token != "value")
|
||||
name += " " + token;
|
||||
|
||||
up >> value; // Read option value
|
||||
|
||||
// Handle values with included spaces
|
||||
while (up >> token)
|
||||
value += " " + token;
|
||||
|
||||
if (Options.find(name) != Options.end())
|
||||
Options[name].set_value(value);
|
||||
else
|
||||
cout << "No such option: " << name << endl;
|
||||
}
|
||||
|
||||
|
||||
// go() is called when engine receives the "go" UCI command. The
|
||||
// function sets the thinking time and other parameters from the input
|
||||
// string, and then calls think(). Returns false if a quit command
|
||||
// is received while thinking, true otherwise.
|
||||
|
||||
bool go(Position& pos, UCIParser& up) {
|
||||
|
||||
string token;
|
||||
SearchLimits limits;
|
||||
Move searchMoves[MAX_MOVES], *cur = searchMoves;
|
||||
int time[] = { 0, 0 }, inc[] = { 0, 0 };
|
||||
|
||||
while (up >> token)
|
||||
while (is >> token && (m = move_from_uci(pos, token)) != MOVE_NONE)
|
||||
{
|
||||
if (token == "infinite")
|
||||
SetupStates->push(StateInfo());
|
||||
pos.do_move(m, SetupStates->top());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// set_option() is called when engine receives the "setoption" UCI command. The
|
||||
// function updates the UCI option ("name") to the given value ("value").
|
||||
|
||||
void set_option(istringstream& is) {
|
||||
|
||||
string token, name, value;
|
||||
|
||||
is >> token; // Consume "name" token
|
||||
|
||||
// Read option name (can contain spaces)
|
||||
while (is >> token && token != "value")
|
||||
name += string(" ", !name.empty()) + token;
|
||||
|
||||
// Read option value (can contain spaces)
|
||||
while (is >> token)
|
||||
value += string(" ", !value.empty()) + token;
|
||||
|
||||
if (Options.count(name))
|
||||
Options[name] = value;
|
||||
else
|
||||
sync_cout << "No such option: " << name << sync_endl;
|
||||
}
|
||||
|
||||
|
||||
// go() is called when engine receives the "go" UCI command. The function sets
|
||||
// the thinking time and other parameters from the input string, and then starts
|
||||
// the search.
|
||||
|
||||
void go(Position& pos, istringstream& is) {
|
||||
|
||||
Search::LimitsType limits;
|
||||
vector<Move> searchMoves;
|
||||
string token;
|
||||
|
||||
while (is >> token)
|
||||
{
|
||||
if (token == "wtime")
|
||||
is >> limits.time[WHITE];
|
||||
else if (token == "btime")
|
||||
is >> limits.time[BLACK];
|
||||
else if (token == "winc")
|
||||
is >> limits.inc[WHITE];
|
||||
else if (token == "binc")
|
||||
is >> limits.inc[BLACK];
|
||||
else if (token == "movestogo")
|
||||
is >> limits.movestogo;
|
||||
else if (token == "depth")
|
||||
is >> limits.depth;
|
||||
else if (token == "nodes")
|
||||
is >> limits.nodes;
|
||||
else if (token == "movetime")
|
||||
is >> limits.movetime;
|
||||
else if (token == "infinite")
|
||||
limits.infinite = true;
|
||||
else if (token == "ponder")
|
||||
limits.ponder = true;
|
||||
else if (token == "wtime")
|
||||
up >> time[WHITE];
|
||||
else if (token == "btime")
|
||||
up >> time[BLACK];
|
||||
else if (token == "winc")
|
||||
up >> inc[WHITE];
|
||||
else if (token == "binc")
|
||||
up >> inc[BLACK];
|
||||
else if (token == "movestogo")
|
||||
up >> limits.movesToGo;
|
||||
else if (token == "depth")
|
||||
up >> limits.maxDepth;
|
||||
else if (token == "nodes")
|
||||
up >> limits.maxNodes;
|
||||
else if (token == "movetime")
|
||||
up >> limits.maxTime;
|
||||
else if (token == "searchmoves")
|
||||
while (up >> token)
|
||||
*cur++ = move_from_uci(pos, token);
|
||||
while (is >> token)
|
||||
searchMoves.push_back(move_from_uci(pos, token));
|
||||
}
|
||||
|
||||
*cur = MOVE_NONE;
|
||||
limits.time = time[pos.side_to_move()];
|
||||
limits.increment = inc[pos.side_to_move()];
|
||||
|
||||
assert(pos.is_ok());
|
||||
|
||||
return think(pos, limits, searchMoves);
|
||||
}
|
||||
|
||||
|
||||
// perft() is called when engine receives the "perft" command.
|
||||
// The function calls perft() passing the required search depth
|
||||
// then prints counted leaf nodes and elapsed time.
|
||||
|
||||
void perft(Position& pos, UCIParser& up) {
|
||||
|
||||
int depth, time;
|
||||
int64_t n;
|
||||
|
||||
if (!(up >> depth))
|
||||
return;
|
||||
|
||||
time = get_system_time();
|
||||
|
||||
n = perft(pos, depth * ONE_PLY);
|
||||
|
||||
time = get_system_time() - time;
|
||||
|
||||
std::cout << "\nNodes " << n
|
||||
<< "\nTime (ms) " << time
|
||||
<< "\nNodes/second " << int(n / (time / 1000.0)) << std::endl;
|
||||
Threads.start_searching(pos, limits, searchMoves, SetupStates);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -17,154 +17,150 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include <cctype>
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
|
||||
#include "evaluate.h"
|
||||
#include "misc.h"
|
||||
#include "thread.h"
|
||||
#include "tt.h"
|
||||
#include "ucioption.h"
|
||||
|
||||
using std::string;
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
|
||||
OptionsMap Options; // Global object
|
||||
UCI::OptionsMap Options; // Global object
|
||||
|
||||
namespace UCI {
|
||||
|
||||
/// 'On change' actions, triggered by an option's value change
|
||||
void on_logger(const Option& o) { start_logger(o); }
|
||||
void on_eval(const Option&) { Eval::init(); }
|
||||
void on_threads(const Option&) { Threads.read_uci_options(); }
|
||||
void on_hash_size(const Option& o) { TT.set_size(o); }
|
||||
void on_clear_hash(const Option&) { TT.clear(); }
|
||||
|
||||
|
||||
// Our case insensitive less() function as required by UCI protocol
|
||||
/// Our case insensitive less() function as required by UCI protocol
|
||||
bool ci_less(char c1, char c2) { return tolower(c1) < tolower(c2); }
|
||||
|
||||
bool CaseInsensitiveLess::operator() (const string& s1, const string& s2) const {
|
||||
|
||||
int c1, c2;
|
||||
size_t i = 0;
|
||||
|
||||
while (i < s1.size() && i < s2.size())
|
||||
{
|
||||
c1 = tolower(s1[i]);
|
||||
c2 = tolower(s2[i++]);
|
||||
|
||||
if (c1 != c2)
|
||||
return c1 < c2;
|
||||
}
|
||||
return s1.size() < s2.size();
|
||||
return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ci_less);
|
||||
}
|
||||
|
||||
|
||||
// stringify() converts a numeric value of type T to a std::string
|
||||
template<typename T>
|
||||
static string stringify(const T& v) {
|
||||
/// init() initializes the UCI options to their hard coded default values
|
||||
/// and initializes the default value of "Threads" and "Min Split Depth"
|
||||
/// parameters according to the number of CPU cores detected.
|
||||
|
||||
std::ostringstream ss;
|
||||
ss << v;
|
||||
return ss.str();
|
||||
void init(OptionsMap& o) {
|
||||
|
||||
int cpus = std::min(cpu_count(), MAX_THREADS);
|
||||
int msd = cpus < 8 ? 4 : 7;
|
||||
|
||||
o["Use Debug Log"] = Option(false, on_logger);
|
||||
o["Use Search Log"] = Option(false);
|
||||
o["Search Log Filename"] = Option("SearchLog.txt");
|
||||
o["Book File"] = Option("book.bin");
|
||||
o["Best Book Move"] = Option(false);
|
||||
o["Mobility (Middle Game)"] = Option(100, 0, 200, on_eval);
|
||||
o["Mobility (Endgame)"] = Option(100, 0, 200, on_eval);
|
||||
o["Passed Pawns (Middle Game)"] = Option(100, 0, 200, on_eval);
|
||||
o["Passed Pawns (Endgame)"] = Option(100, 0, 200, on_eval);
|
||||
o["Space"] = Option(100, 0, 200, on_eval);
|
||||
o["Aggressiveness"] = Option(100, 0, 200, on_eval);
|
||||
o["Cowardice"] = Option(100, 0, 200, on_eval);
|
||||
o["Min Split Depth"] = Option(msd, 4, 7, on_threads);
|
||||
o["Max Threads per Split Point"] = Option(5, 4, 8, on_threads);
|
||||
o["Threads"] = Option(cpus, 1, MAX_THREADS, on_threads);
|
||||
o["Use Sleeping Threads"] = Option(true, on_threads);
|
||||
o["Hash"] = Option(32, 4, 8192, on_hash_size);
|
||||
o["Clear Hash"] = Option(on_clear_hash);
|
||||
o["Ponder"] = Option(true);
|
||||
o["OwnBook"] = Option(false);
|
||||
o["MultiPV"] = Option(1, 1, 500);
|
||||
o["Skill Level"] = Option(20, 0, 20);
|
||||
o["Emergency Move Horizon"] = Option(40, 0, 50);
|
||||
o["Emergency Base Time"] = Option(200, 0, 30000);
|
||||
o["Emergency Move Time"] = Option(70, 0, 5000);
|
||||
o["Minimum Thinking Time"] = Option(20, 0, 5000);
|
||||
o["Slow Mover"] = Option(100, 10, 1000);
|
||||
o["UCI_Chess960"] = Option(false);
|
||||
o["UCI_AnalyseMode"] = Option(false, on_eval);
|
||||
}
|
||||
|
||||
|
||||
/// OptionsMap c'tor initializes the UCI options to their hard coded default
|
||||
/// values and initializes the default value of "Threads" and "Minimum Split Depth"
|
||||
/// parameters according to the number of CPU cores.
|
||||
|
||||
OptionsMap::OptionsMap() {
|
||||
|
||||
OptionsMap& o = *this;
|
||||
|
||||
o["Use Search Log"] = UCIOption(false);
|
||||
o["Search Log Filename"] = UCIOption("SearchLog.txt");
|
||||
o["Book File"] = UCIOption("book.bin");
|
||||
o["Best Book Move"] = UCIOption(false);
|
||||
o["Mobility (Middle Game)"] = UCIOption(100, 0, 200);
|
||||
o["Mobility (Endgame)"] = UCIOption(100, 0, 200);
|
||||
o["Passed Pawns (Middle Game)"] = UCIOption(100, 0, 200);
|
||||
o["Passed Pawns (Endgame)"] = UCIOption(100, 0, 200);
|
||||
o["Space"] = UCIOption(100, 0, 200);
|
||||
o["Aggressiveness"] = UCIOption(100, 0, 200);
|
||||
o["Cowardice"] = UCIOption(100, 0, 200);
|
||||
o["Minimum Split Depth"] = UCIOption(4, 4, 7);
|
||||
o["Maximum Number of Threads per Split Point"] = UCIOption(5, 4, 8);
|
||||
o["Threads"] = UCIOption(1, 1, MAX_THREADS);
|
||||
o["Use Sleeping Threads"] = UCIOption(false);
|
||||
o["Hash"] = UCIOption(32, 4, 8192);
|
||||
o["Clear Hash"] = UCIOption(false, "button");
|
||||
o["Ponder"] = UCIOption(true);
|
||||
o["OwnBook"] = UCIOption(true);
|
||||
o["MultiPV"] = UCIOption(1, 1, 500);
|
||||
o["Skill Level"] = UCIOption(20, 0, 20);
|
||||
o["Emergency Move Horizon"] = UCIOption(40, 0, 50);
|
||||
o["Emergency Base Time"] = UCIOption(200, 0, 30000);
|
||||
o["Emergency Move Time"] = UCIOption(70, 0, 5000);
|
||||
o["Minimum Thinking Time"] = UCIOption(20, 0, 5000);
|
||||
o["UCI_Chess960"] = UCIOption(false);
|
||||
o["UCI_AnalyseMode"] = UCIOption(false);
|
||||
|
||||
// Set some SMP parameters accordingly to the detected CPU count
|
||||
UCIOption& thr = o["Threads"];
|
||||
UCIOption& msd = o["Minimum Split Depth"];
|
||||
|
||||
thr.defaultValue = thr.currentValue = stringify(cpu_count());
|
||||
|
||||
if (cpu_count() >= 8)
|
||||
msd.defaultValue = msd.currentValue = stringify(7);
|
||||
}
|
||||
|
||||
|
||||
/// OptionsMap::print_all() returns a string with all the UCI options in chronological
|
||||
/// operator<<() is used to print all the options default values in chronological
|
||||
/// insertion order (the idx field) and in the format defined by the UCI protocol.
|
||||
|
||||
string OptionsMap::print_all() const {
|
||||
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
||||
|
||||
std::stringstream s;
|
||||
|
||||
for (size_t i = 0; i <= size(); i++)
|
||||
for (OptionsMap::const_iterator it = begin(); it != end(); ++it)
|
||||
if (it->second.idx == i)
|
||||
for (size_t idx = 0; idx < om.size(); idx++)
|
||||
for (OptionsMap::const_iterator it = om.begin(); it != om.end(); ++it)
|
||||
if (it->second.idx == idx)
|
||||
{
|
||||
const UCIOption& o = it->second;
|
||||
s << "\noption name " << it->first << " type " << o.type;
|
||||
const Option& o = it->second;
|
||||
os << "\noption name " << it->first << " type " << o.type;
|
||||
|
||||
if (o.type != "button")
|
||||
s << " default " << o.defaultValue;
|
||||
os << " default " << o.defaultValue;
|
||||
|
||||
if (o.type == "spin")
|
||||
s << " min " << o.minValue << " max " << o.maxValue;
|
||||
os << " min " << o.min << " max " << o.max;
|
||||
|
||||
break;
|
||||
}
|
||||
return s.str();
|
||||
return os;
|
||||
}
|
||||
|
||||
|
||||
/// Option class c'tors
|
||||
/// Option c'tors and conversion operators
|
||||
|
||||
UCIOption::UCIOption(const char* def) : type("string"), minValue(0), maxValue(0), idx(Options.size())
|
||||
{ defaultValue = currentValue = def; }
|
||||
Option::Option(const char* v, Fn* f) : type("string"), min(0), max(0), idx(Options.size()), on_change(f)
|
||||
{ defaultValue = currentValue = v; }
|
||||
|
||||
UCIOption::UCIOption(bool def, string t) : type(t), minValue(0), maxValue(0), idx(Options.size())
|
||||
{ defaultValue = currentValue = (def ? "true" : "false"); }
|
||||
Option::Option(bool v, Fn* f) : type("check"), min(0), max(0), idx(Options.size()), on_change(f)
|
||||
{ defaultValue = currentValue = (v ? "true" : "false"); }
|
||||
|
||||
UCIOption::UCIOption(int def, int minv, int maxv) : type("spin"), minValue(minv), maxValue(maxv), idx(Options.size())
|
||||
{ defaultValue = currentValue = stringify(def); }
|
||||
Option::Option(Fn* f) : type("button"), min(0), max(0), idx(Options.size()), on_change(f)
|
||||
{}
|
||||
|
||||
Option::Option(int v, int minv, int maxv, Fn* f) : type("spin"), min(minv), max(maxv), idx(Options.size()), on_change(f)
|
||||
{ std::ostringstream ss; ss << v; defaultValue = currentValue = ss.str(); }
|
||||
|
||||
|
||||
/// set_value() updates currentValue of the Option object. Normally it's up to
|
||||
/// the GUI to check for option's limits, but we could receive the new value
|
||||
/// directly from the user by teminal window. So let's check the bounds anyway.
|
||||
Option::operator int() const {
|
||||
assert(type == "check" || type == "spin");
|
||||
return (type == "spin" ? atoi(currentValue.c_str()) : currentValue == "true");
|
||||
}
|
||||
|
||||
void UCIOption::set_value(const string& v) {
|
||||
Option::operator std::string() const {
|
||||
assert(type == "string");
|
||||
return currentValue;
|
||||
}
|
||||
|
||||
|
||||
/// operator=() updates currentValue and triggers on_change() action. It's up to
|
||||
/// the GUI to check for option's limits, but we could receive the new value from
|
||||
/// the user by console window, so let's check the bounds anyway.
|
||||
|
||||
Option& Option::operator=(const string& v) {
|
||||
|
||||
assert(!type.empty());
|
||||
|
||||
if (v.empty())
|
||||
return;
|
||||
if ( (type != "button" && v.empty())
|
||||
|| (type == "check" && v != "true" && v != "false")
|
||||
|| (type == "spin" && (atoi(v.c_str()) < min || atoi(v.c_str()) > max)))
|
||||
return *this;
|
||||
|
||||
if ((type == "check" || type == "button") != (v == "true" || v == "false"))
|
||||
return;
|
||||
if (type != "button")
|
||||
currentValue = v;
|
||||
|
||||
if (type == "spin")
|
||||
{
|
||||
int val = atoi(v.c_str());
|
||||
if (val < minValue || val > maxValue)
|
||||
return;
|
||||
}
|
||||
if (on_change)
|
||||
(*on_change)(*this);
|
||||
|
||||
currentValue = v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
} // namespace UCI
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||
|
||||
Stockfish is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
@@ -20,66 +20,50 @@
|
||||
#if !defined(UCIOPTION_H_INCLUDED)
|
||||
#define UCIOPTION_H_INCLUDED
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
class UCIOption {
|
||||
public:
|
||||
UCIOption() {} // To be used in a std::map
|
||||
UCIOption(const char* defaultValue);
|
||||
UCIOption(bool defaultValue, std::string type = "check");
|
||||
UCIOption(int defaultValue, int minValue, int maxValue);
|
||||
namespace UCI {
|
||||
|
||||
void set_value(const std::string& v);
|
||||
template<typename T> T value() const;
|
||||
class Option;
|
||||
|
||||
private:
|
||||
friend class OptionsMap;
|
||||
|
||||
std::string defaultValue, currentValue, type;
|
||||
int minValue, maxValue;
|
||||
size_t idx;
|
||||
};
|
||||
|
||||
|
||||
/// Custom comparator because UCI options should not be case sensitive
|
||||
/// Custom comparator because UCI options should be case insensitive
|
||||
struct CaseInsensitiveLess {
|
||||
bool operator() (const std::string&, const std::string&) const;
|
||||
};
|
||||
|
||||
/// Our options container is actually a std::map
|
||||
typedef std::map<std::string, Option, CaseInsensitiveLess> OptionsMap;
|
||||
|
||||
/// Option class implements an option as defined by UCI protocol
|
||||
class Option {
|
||||
|
||||
typedef void (Fn)(const Option&);
|
||||
|
||||
/// Our options container is actually a map with a customized c'tor
|
||||
class OptionsMap : public std::map<std::string, UCIOption, CaseInsensitiveLess> {
|
||||
public:
|
||||
OptionsMap();
|
||||
std::string print_all() const;
|
||||
Option(Fn* = NULL);
|
||||
Option(bool v, Fn* = NULL);
|
||||
Option(const char* v, Fn* = NULL);
|
||||
Option(int v, int min, int max, Fn* = NULL);
|
||||
|
||||
Option& operator=(const std::string& v);
|
||||
operator int() const;
|
||||
operator std::string() const;
|
||||
|
||||
private:
|
||||
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
|
||||
|
||||
std::string defaultValue, currentValue, type;
|
||||
int min, max;
|
||||
size_t idx;
|
||||
Fn* on_change;
|
||||
};
|
||||
|
||||
extern OptionsMap Options;
|
||||
void init(OptionsMap&);
|
||||
void loop(const std::string&);
|
||||
|
||||
} // namespace UCI
|
||||
|
||||
/// Option::value() definition and specializations
|
||||
template<typename T>
|
||||
T UCIOption::value() const {
|
||||
|
||||
assert(type == "spin");
|
||||
return T(atoi(currentValue.c_str()));
|
||||
}
|
||||
|
||||
template<>
|
||||
inline std::string UCIOption::value<std::string>() const {
|
||||
|
||||
assert(type == "string");
|
||||
return currentValue;
|
||||
}
|
||||
|
||||
template<>
|
||||
inline bool UCIOption::value<bool>() const {
|
||||
|
||||
assert(type == "check" || type == "button");
|
||||
return currentValue == "true";
|
||||
}
|
||||
extern UCI::OptionsMap Options;
|
||||
|
||||
#endif // !defined(UCIOPTION_H_INCLUDED)
|
||||
|
||||
Reference in New Issue
Block a user