mirror of
https://github.com/opelly27/Stockfish.git
synced 2026-05-20 15:37:47 +00:00
Compare commits
580 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aa2368a687 | |||
| 293c44bc09 | |||
| 06b9140e5c | |||
| 156635749b | |||
| 083fe58124 | |||
| e508494a99 | |||
| 2ef53ee368 | |||
| d810441b35 | |||
| 79bcb2ca54 | |||
| 289a767ab3 | |||
| 4381ea23fe | |||
| 817ca1820b | |||
| 8df17204f4 | |||
| f84f04742a | |||
| cc40d1c46a | |||
| 818e0b2d2b | |||
| 3e4dfb49a7 | |||
| 87436e5544 | |||
| fe72c93141 | |||
| 75221fcf5e | |||
| a95cbca568 | |||
| d23454854e | |||
| c2902112e5 | |||
| 9498b2af82 | |||
| 2a5ae34bb2 | |||
| d3fe153fe6 | |||
| 889922041b | |||
| 7bad50773a | |||
| d3c3c4f8e7 | |||
| 2097cd1221 | |||
| 0c1b40c5e2 | |||
| 8c10029df1 | |||
| 6e2371a86b | |||
| 36c82b751c | |||
| 7d42d02ec7 | |||
| c89274d8fb | |||
| f2638816bf | |||
| 0b4ea54da9 | |||
| 09f1fdf52f | |||
| d39b22927e | |||
| 81e9cf043a | |||
| 077e32efc9 | |||
| 52f3e717fa | |||
| 0586b51f9c | |||
| d2eeef89aa | |||
| 70d20326b0 | |||
| ccf4ec6768 | |||
| a24da071f0 | |||
| 3698d9aa55 | |||
| 10429dd616 | |||
| db322e6a63 | |||
| 45dba12c5b | |||
| ccad601389 | |||
| d165d5af91 | |||
| 3ce43c20de | |||
| def50020ad | |||
| 0d68b523a3 | |||
| 0e1ad3ad33 | |||
| 0fc9a01933 | |||
| 68d1bebd8e | |||
| 57b6df4874 | |||
| bc38efd128 | |||
| 335b57b5ef | |||
| dbd28bc7f8 | |||
| ccf21f5595 | |||
| 1d1fcf80a0 | |||
| 373503f4a9 | |||
| 9a1d5f0f1d | |||
| d5e49a3ad4 | |||
| ea4e22be1d | |||
| dc8c6ea2d1 | |||
| c5ec94d0f1 | |||
| d570260a28 | |||
| 76caef8ba1 | |||
| 5a156df719 | |||
| e0dfb0bc34 | |||
| 3922ac2fe4 | |||
| 66a1a77487 | |||
| cd0ecace19 | |||
| 10d29add18 | |||
| f2950ae206 | |||
| d0c2faa5fd | |||
| 671f24ff35 | |||
| f32f899467 | |||
| 17b71fe51d | |||
| 30c2e3828a | |||
| a7cdf7299a | |||
| 733d0099b2 | |||
| 0be7b8c542 | |||
| c698362680 | |||
| fe3352665b | |||
| 3f44be9baa | |||
| 0c06b4509d | |||
| e5bc79fb9c | |||
| 880726c13a | |||
| 50a7200b18 | |||
| c67fb8ef04 | |||
| 14c2c1395b | |||
| 88c3670edf | |||
| f69c185e02 | |||
| bf706c4a4f | |||
| 1a414cd9cb | |||
| 91427c8242 | |||
| b8c5ea869c | |||
| 6560e4cc5b | |||
| 08d615cc95 | |||
| 1c4e6d7ea2 | |||
| 5f58db8c99 | |||
| ddbe6082c4 | |||
| 53051eefc7 | |||
| a72710c660 | |||
| 9f94d22801 | |||
| 0901e12102 | |||
| 58c9fbacc7 | |||
| 483c98a69e | |||
| 2218a5836a | |||
| 76a0d3c05a | |||
| 52cab06fff | |||
| bd87ab9ff5 | |||
| 57797822f8 | |||
| 7062db7cb2 | |||
| 166cc0292c | |||
| 496c7497cb | |||
| e83b9075ff | |||
| 6950d07bf4 | |||
| 054d117d25 | |||
| 62b32a4737 | |||
| 588670e8d2 | |||
| c465f4c4df | |||
| 8737b26a23 | |||
| 78a9531773 | |||
| d1143794a0 | |||
| e70eae2c91 | |||
| 99ae47716a | |||
| dda7de17e7 | |||
| 869c924410 | |||
| ea6c1f7a17 | |||
| 81cd7d787e | |||
| a523cea772 | |||
| a66a7c3870 | |||
| 89a89eb605 | |||
| 3b14b17664 | |||
| 3a836dab59 | |||
| e1191b35e8 | |||
| edce2a8448 | |||
| 9b1cf3cf43 | |||
| bff65a211f | |||
| 2d60995c00 | |||
| 0454bbc54f | |||
| 900e2d4e1e | |||
| 9d1151575d | |||
| 193741218c | |||
| 896420b166 | |||
| 009a0f88e0 | |||
| e1d681458e | |||
| ce063f59cd | |||
| 3cf6471738 | |||
| f78b68b7ff | |||
| e9ab7353de | |||
| 9d1978e217 | |||
| db097921bc | |||
| 894c43a1d6 | |||
| b5b799b5ab | |||
| e82382703c | |||
| 3b49aeb4f2 | |||
| 423c6d8a8a | |||
| 158014b39d | |||
| 231f62baf7 | |||
| 52bbf372bb | |||
| 3ddf91d9d1 | |||
| a2f46446cf | |||
| 9edc7d6958 | |||
| 55db871472 | |||
| da98a45bcb | |||
| feeafb0a50 | |||
| 22c557ca7c | |||
| 6a93488291 | |||
| 6fa83f5188 | |||
| ce248e7920 | |||
| 23bdd06442 | |||
| 98cd8239cc | |||
| 2a585b63b8 | |||
| a5ea3a202e | |||
| 69de670353 | |||
| 4e5d834e8e | |||
| 4502917665 | |||
| 5af8179647 | |||
| 55df3fa2d7 | |||
| 8367cf15da | |||
| 942989939a | |||
| 239d7b3fd1 | |||
| 116234d6c6 | |||
| c45a4e0b48 | |||
| 96d3b1c92b | |||
| 3b87314331 | |||
| c581b7ea36 | |||
| a5b1f4774f | |||
| 37e9802411 | |||
| a87831230d | |||
| dd5b3086f5 | |||
| 47f988f05f | |||
| 07989712af | |||
| d0d69a5358 | |||
| 972de506a0 | |||
| ed1574e46c | |||
| 52f55179a8 | |||
| bbdf9e4737 | |||
| 94ecdef8ac | |||
| e3b0327812 | |||
| c039103b31 | |||
| fe1cbe2638 | |||
| 4e31c39a64 | |||
| 13f90a30ef | |||
| ad1941fd00 | |||
| cee6336515 | |||
| b3d030294b | |||
| cd80762c13 | |||
| 00a853950f | |||
| 4c7a71a44b | |||
| c594b989c0 | |||
| 71f37ac1aa | |||
| 77c91ac1ba | |||
| 5436d98fc5 | |||
| 0587c5b605 | |||
| c1f4000426 | |||
| 22715259a0 | |||
| 4eda653a56 | |||
| e8e5b9f537 | |||
| 9c2b3faec4 | |||
| 70b1b79264 | |||
| 5fc8b27db9 | |||
| dbbbd3880c | |||
| e40b06a050 | |||
| e304db9d1e | |||
| 6b909b2343 | |||
| 55bd27b8f0 | |||
| 1018474853 | |||
| c11edd3b0b | |||
| f0298862f5 | |||
| 739d23f2a3 | |||
| 3aa2d6db18 | |||
| 6a75291ab1 | |||
| eb1a4f11fa | |||
| d023be5a21 | |||
| c2cd75843e | |||
| 189b6fc270 | |||
| 6c8663341e | |||
| aba152ea3a | |||
| 7f9ebf8e86 | |||
| 4e7da9be3d | |||
| 46c01b5083 | |||
| dae843d4d6 | |||
| 78fe0cfb8d | |||
| d77d555c72 | |||
| bbaef048cd | |||
| 7e2d49368d | |||
| 954fc950d9 | |||
| d777c4d789 | |||
| cedbd3332a | |||
| ff9ca3e76e | |||
| b8948e84b8 | |||
| 1ac417edb8 | |||
| d471c49700 | |||
| c9f9262a49 | |||
| bd7a0d4ce4 | |||
| 561eb34aea | |||
| 4c91dbc28e | |||
| 1b6b711c44 | |||
| faaa1f1116 | |||
| ed0fb0b05f | |||
| e5463eb3ae | |||
| d53c928261 | |||
| bc8f5fe0bf | |||
| 9204a60dbb | |||
| 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 |
@@ -0,0 +1,74 @@
|
|||||||
|
### Overview
|
||||||
|
|
||||||
|
Stockfish is a free UCI chess engine derived from Glaurung 2.1. It is
|
||||||
|
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 it.
|
||||||
|
|
||||||
|
This version of Stockfish supports up to 64 CPUs, but has not been
|
||||||
|
tested thoroughly with more than 4. The program tries to detect the
|
||||||
|
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
|
||||||
|
*Threads* UCI parameter, and to make sure it equals the number of CPU
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
### Files
|
||||||
|
|
||||||
|
This distribution of Stockfish consists of the following files:
|
||||||
|
|
||||||
|
* Readme.md, the file you are currently reading.
|
||||||
|
|
||||||
|
* 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 below.
|
||||||
|
|
||||||
|
* polyglot.ini, for using Stockfish with Fabien Letouzey's PolyGlot
|
||||||
|
adapter.
|
||||||
|
|
||||||
|
|
||||||
|
### 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 *Book File*
|
||||||
|
UCI parameter.
|
||||||
|
|
||||||
|
|
||||||
|
### Compiling it yourself
|
||||||
|
|
||||||
|
On Unix-like systems, it should be possible to compile Stockfish
|
||||||
|
directly from the source code with the included Makefile.
|
||||||
|
|
||||||
|
Stockfish has support for 32 or 64-bit CPUs, the hardware POPCNT
|
||||||
|
instruction, big-endian machines such as Power PC, and other platforms.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
### 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
|
||||||
|
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
|
||||||
|
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
|
||||||
|
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*
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
1. Introduction
|
|
||||||
---------------
|
|
||||||
|
|
||||||
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, 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.
|
|
||||||
|
|
||||||
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 accordingly, but
|
|
||||||
please be aware that the detection is not always 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 eight threads, it is recommended to raise the value of
|
|
||||||
"Min Split Depth" UCI parameter to 7.
|
|
||||||
|
|
||||||
|
|
||||||
2. Files
|
|
||||||
--------
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
* 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.
|
|
||||||
|
|
||||||
* polyglot.ini, for using Stockfish with Fabien Letouzey's PolyGlot
|
|
||||||
adapter.
|
|
||||||
|
|
||||||
|
|
||||||
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".
|
|
||||||
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
Stockfish has support for 32 or 64 bits CPUS, big-endian machines, like
|
|
||||||
Power PC, hardware POPCNT instruction and other platforms.
|
|
||||||
|
|
||||||
In general 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 in the compiler
|
|
||||||
command line some swicthes, 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
|
|
||||||
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
|
|
||||||
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
|
|
||||||
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.
|
|
||||||
+1
-1
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
[PolyGlot]
|
[PolyGlot]
|
||||||
|
|
||||||
EngineDir = .
|
EngineDir = .
|
||||||
@@ -19,6 +18,7 @@ Use Search Log = false
|
|||||||
Search Log Filename = SearchLog.txt
|
Search Log Filename = SearchLog.txt
|
||||||
Book File = book.bin
|
Book File = book.bin
|
||||||
Best Book Move = false
|
Best Book Move = false
|
||||||
|
Contempt Factor = 0
|
||||||
Mobility (Middle Game) = 100
|
Mobility (Middle Game) = 100
|
||||||
Mobility (Endgame) = 100
|
Mobility (Endgame) = 100
|
||||||
Passed Pawns (Middle Game) = 100
|
Passed Pawns (Middle Game) = 100
|
||||||
|
|||||||
+96
-85
@@ -1,6 +1,6 @@
|
|||||||
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
# Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
# Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
#
|
#
|
||||||
# Stockfish is free software: you can redistribute it and/or modify
|
# Stockfish is free software: you can redistribute it and/or modify
|
||||||
# it under the terms of the GNU General Public License as published by
|
# it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,11 +20,18 @@
|
|||||||
### Section 1. General Configuration
|
### Section 1. General Configuration
|
||||||
### ==========================================================================
|
### ==========================================================================
|
||||||
|
|
||||||
|
### Establish the operating system name
|
||||||
|
UNAME = $(shell uname)
|
||||||
|
|
||||||
### Executable name
|
### Executable name
|
||||||
EXE = stockfish
|
EXE = stockfish
|
||||||
|
|
||||||
### Installation dir definitions
|
### Installation dir definitions
|
||||||
PREFIX = /usr/local
|
PREFIX = /usr/local
|
||||||
|
# Haiku has a non-standard filesystem layout
|
||||||
|
ifeq ($(UNAME),Haiku)
|
||||||
|
PREFIX=/boot/common
|
||||||
|
endif
|
||||||
BINDIR = $(PREFIX)/bin
|
BINDIR = $(PREFIX)/bin
|
||||||
|
|
||||||
### Built-in benchmark for pgo-builds
|
### Built-in benchmark for pgo-builds
|
||||||
@@ -32,7 +39,7 @@ PGOBENCH = ./$(EXE) bench 32 1 10 default depth
|
|||||||
|
|
||||||
### Object files
|
### Object files
|
||||||
OBJS = benchmark.o bitbase.o bitboard.o book.o endgame.o evaluate.o main.o \
|
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
|
search.o thread.o timeman.o tt.o uci.o ucioption.o
|
||||||
|
|
||||||
### ==========================================================================
|
### ==========================================================================
|
||||||
@@ -47,11 +54,11 @@ OBJS = benchmark.o bitbase.o bitboard.o book.o endgame.o evaluate.o main.o \
|
|||||||
# arch = (name) --- (-arch) --- Target architecture
|
# arch = (name) --- (-arch) --- Target architecture
|
||||||
# os = (name) --- --- Target operating system
|
# os = (name) --- --- Target operating system
|
||||||
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
|
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
|
||||||
# bigendian = yes/no --- -DBIGENDIAN --- big/little-endian byte order
|
|
||||||
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
|
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
|
||||||
# bsfq = yes/no --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction (only
|
# bsfq = yes/no --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction (only
|
||||||
# with GCC and ICC 64-bit)
|
# with GCC and ICC 64-bit)
|
||||||
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
|
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
|
||||||
|
# sse = yes/no --- -msse --- Use Intel Streaming SIMD Extensions
|
||||||
#
|
#
|
||||||
# Note that Makefile is space sensitive, so when adding new architectures
|
# 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
|
# or modifying existing flags, you have to make sure there are no extra spaces
|
||||||
@@ -68,40 +75,20 @@ ifeq ($(ARCH),general-64)
|
|||||||
arch = any
|
arch = any
|
||||||
os = any
|
os = any
|
||||||
bits = 64
|
bits = 64
|
||||||
bigendian = no
|
|
||||||
prefetch = no
|
prefetch = no
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = no
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),general-32)
|
ifeq ($(ARCH),general-32)
|
||||||
arch = any
|
arch = any
|
||||||
os = any
|
os = any
|
||||||
bits = 32
|
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
|
prefetch = no
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = no
|
||||||
endif
|
endif
|
||||||
|
|
||||||
# x86-section
|
# x86-section
|
||||||
@@ -109,40 +96,51 @@ ifeq ($(ARCH),x86-64)
|
|||||||
arch = x86_64
|
arch = x86_64
|
||||||
os = any
|
os = any
|
||||||
bits = 64
|
bits = 64
|
||||||
bigendian = no
|
|
||||||
prefetch = yes
|
prefetch = yes
|
||||||
bsfq = yes
|
bsfq = yes
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = yes
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),x86-64-modern)
|
ifeq ($(ARCH),x86-64-modern)
|
||||||
arch = x86_64
|
arch = x86_64
|
||||||
os = any
|
os = any
|
||||||
bits = 64
|
bits = 64
|
||||||
bigendian = no
|
|
||||||
prefetch = yes
|
prefetch = yes
|
||||||
bsfq = yes
|
bsfq = yes
|
||||||
popcnt = yes
|
popcnt = yes
|
||||||
|
sse = yes
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),x86-32)
|
ifeq ($(ARCH),x86-32)
|
||||||
arch = i386
|
arch = i386
|
||||||
os = any
|
os = any
|
||||||
bits = 32
|
bits = 32
|
||||||
bigendian = no
|
|
||||||
prefetch = yes
|
prefetch = yes
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = yes
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),x86-32-old)
|
ifeq ($(ARCH),x86-32-old)
|
||||||
arch = i386
|
arch = i386
|
||||||
os = any
|
os = any
|
||||||
bits = 32
|
bits = 32
|
||||||
bigendian = no
|
|
||||||
prefetch = no
|
prefetch = no
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = no
|
||||||
|
endif
|
||||||
|
|
||||||
|
#arm section
|
||||||
|
ifeq ($(ARCH),armv7)
|
||||||
|
arch = armv7
|
||||||
|
os = any
|
||||||
|
bits = 32
|
||||||
|
prefetch = yes
|
||||||
|
bsfq = yes
|
||||||
|
popcnt = no
|
||||||
|
sse = no
|
||||||
endif
|
endif
|
||||||
|
|
||||||
# osx-section
|
# osx-section
|
||||||
@@ -150,40 +148,40 @@ ifeq ($(ARCH),osx-ppc-64)
|
|||||||
arch = ppc64
|
arch = ppc64
|
||||||
os = osx
|
os = osx
|
||||||
bits = 64
|
bits = 64
|
||||||
bigendian = yes
|
|
||||||
prefetch = no
|
prefetch = no
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = no
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),osx-ppc-32)
|
ifeq ($(ARCH),osx-ppc-32)
|
||||||
arch = ppc
|
arch = ppc
|
||||||
os = osx
|
os = osx
|
||||||
bits = 32
|
bits = 32
|
||||||
bigendian = yes
|
|
||||||
prefetch = no
|
prefetch = no
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = no
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),osx-x86-64)
|
ifeq ($(ARCH),osx-x86-64)
|
||||||
arch = x86_64
|
arch = x86_64
|
||||||
os = osx
|
os = osx
|
||||||
bits = 64
|
bits = 64
|
||||||
bigendian = no
|
|
||||||
prefetch = yes
|
prefetch = yes
|
||||||
bsfq = yes
|
bsfq = yes
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = yes
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(ARCH),osx-x86-32)
|
ifeq ($(ARCH),osx-x86-32)
|
||||||
arch = i386
|
arch = i386
|
||||||
os = osx
|
os = osx
|
||||||
bits = 32
|
bits = 32
|
||||||
bigendian = no
|
|
||||||
prefetch = yes
|
prefetch = yes
|
||||||
bsfq = no
|
bsfq = no
|
||||||
popcnt = no
|
popcnt = no
|
||||||
|
sse = yes
|
||||||
endif
|
endif
|
||||||
|
|
||||||
|
|
||||||
@@ -223,6 +221,15 @@ ifeq ($(COMP),icc)
|
|||||||
profile_clean = icc-profile-clean
|
profile_clean = icc-profile-clean
|
||||||
endif
|
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
|
### 3.2 General compiler settings
|
||||||
CXXFLAGS = -g -Wall -Wcast-qual -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
|
CXXFLAGS = -g -Wall -Wcast-qual -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
|
||||||
|
|
||||||
@@ -235,18 +242,34 @@ ifeq ($(comp),mingw)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(comp),icc)
|
ifeq ($(comp),icc)
|
||||||
CXXFLAGS += -wd383,981,1418,1419,10187,10188,11505,11503 -Wcheck -Wabi -Wdeprecated -strict-ansi
|
CXXFLAGS += -wd383,981,1418,1419,1476,10187,10188,11505,11503 -Wcheck -Wabi -Wdeprecated -strict-ansi
|
||||||
|
endif
|
||||||
|
|
||||||
|
ifeq ($(comp),clang)
|
||||||
|
CXXFLAGS += -ansi -pedantic -Wno-long-long -Wextra -Wshadow
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(os),osx)
|
ifeq ($(os),osx)
|
||||||
CXXFLAGS += -arch $(arch)
|
CXXFLAGS += -arch $(arch) -mmacosx-version-min=10.0
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.3 General linker settings
|
### 3.3 General linker settings
|
||||||
LDFLAGS = -lpthread $(EXTRALDFLAGS)
|
LDFLAGS = $(EXTRALDFLAGS)
|
||||||
|
|
||||||
|
ifeq ($(comp),mingw)
|
||||||
|
LDFLAGS += -static-libstdc++ -static-libgcc
|
||||||
|
endif
|
||||||
|
|
||||||
|
### 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)
|
ifeq ($(os),osx)
|
||||||
LDFLAGS += -arch $(arch)
|
LDFLAGS += -arch $(arch) -mmacosx-version-min=10.0
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.4 Debugging
|
### 3.4 Debugging
|
||||||
@@ -268,6 +291,10 @@ ifeq ($(optimize),yes)
|
|||||||
CXXFLAGS += -mdynamic-no-pic
|
CXXFLAGS += -mdynamic-no-pic
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
|
ifeq ($(arch),armv7)
|
||||||
|
CXXFLAGS += -fno-gcse
|
||||||
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
ifeq ($(comp),mingw)
|
ifeq ($(comp),mingw)
|
||||||
@@ -281,6 +308,20 @@ ifeq ($(optimize),yes)
|
|||||||
CXXFLAGS += -O3
|
CXXFLAGS += -O3
|
||||||
endif
|
endif
|
||||||
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
|
endif
|
||||||
|
|
||||||
### 3.6. Bits
|
### 3.6. Bits
|
||||||
@@ -288,40 +329,39 @@ ifeq ($(bits),64)
|
|||||||
CXXFLAGS += -DIS_64BIT
|
CXXFLAGS += -DIS_64BIT
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.7 Endianess
|
### 3.7 prefetch
|
||||||
ifeq ($(bigendian),yes)
|
|
||||||
CXXFLAGS += -DBIGENDIAN
|
|
||||||
endif
|
|
||||||
|
|
||||||
### 3.8 prefetch
|
|
||||||
ifeq ($(prefetch),yes)
|
ifeq ($(prefetch),yes)
|
||||||
|
ifeq ($(sse),yes)
|
||||||
CXXFLAGS += -msse
|
CXXFLAGS += -msse
|
||||||
DEPENDFLAGS += -msse
|
DEPENDFLAGS += -msse
|
||||||
|
endif
|
||||||
else
|
else
|
||||||
CXXFLAGS += -DNO_PREFETCH
|
CXXFLAGS += -DNO_PREFETCH
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.9 bsfq
|
### 3.8 bsfq
|
||||||
ifeq ($(bsfq),yes)
|
ifeq ($(bsfq),yes)
|
||||||
CXXFLAGS += -DUSE_BSFQ
|
CXXFLAGS += -DUSE_BSFQ
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.10 popcnt
|
### 3.9 popcnt
|
||||||
ifeq ($(popcnt),yes)
|
ifeq ($(popcnt),yes)
|
||||||
CXXFLAGS += -msse3 -DUSE_POPCNT
|
CXXFLAGS += -msse3 -DUSE_POPCNT
|
||||||
endif
|
endif
|
||||||
|
|
||||||
### 3.11 Link Time Optimization, it works since gcc 4.5 but not on mingw.
|
### 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
|
### This is a mix of compile and link time options because the lto link phase
|
||||||
### needs access to the optimization flags.
|
### needs access to the optimization flags.
|
||||||
ifeq ($(comp),gcc)
|
ifeq ($(comp),gcc)
|
||||||
GCC_MAJOR := `gcc -dumpversion | cut -f1 -d.`
|
ifeq ($(optimize),yes)
|
||||||
GCC_MINOR := `gcc -dumpversion | cut -f2 -d.`
|
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 \)))
|
ifeq (1,$(shell expr \( $(GCC_MAJOR) \> 4 \) \| \( $(GCC_MAJOR) \= 4 \& $(GCC_MINOR) \>= 5 \)))
|
||||||
CXXFLAGS += -flto
|
CXXFLAGS += -flto
|
||||||
LDFLAGS += $(CXXFLAGS)
|
LDFLAGS += $(CXXFLAGS)
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
|
endif
|
||||||
|
|
||||||
### ==========================================================================
|
### ==========================================================================
|
||||||
### Section 4. Public targets
|
### Section 4. Public targets
|
||||||
@@ -337,7 +377,6 @@ help:
|
|||||||
@echo ""
|
@echo ""
|
||||||
@echo "build > Build unoptimized version"
|
@echo "build > Build unoptimized version"
|
||||||
@echo "profile-build > Build PGO-optimized version"
|
@echo "profile-build > Build PGO-optimized version"
|
||||||
@echo "double-profile-build > Build PGO-optimized version with and without popcnt support"
|
|
||||||
@echo "strip > Strip executable"
|
@echo "strip > Strip executable"
|
||||||
@echo "install > Install executable"
|
@echo "install > Install executable"
|
||||||
@echo "clean > Clean up"
|
@echo "clean > Clean up"
|
||||||
@@ -347,22 +386,22 @@ help:
|
|||||||
@echo ""
|
@echo ""
|
||||||
@echo "x86-64 > x86 64-bit"
|
@echo "x86-64 > x86 64-bit"
|
||||||
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt instruction"
|
@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-32 > x86 32-bit excluding old hardware without SSE-support"
|
||||||
@echo "x86-32-old > x86 32-bit including also very old hardware"
|
@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-64 > PPC-Mac OS X 64 bit"
|
||||||
@echo "osx-ppc-32 > PPC-Mac OS X 32 bit"
|
@echo "osx-ppc-32 > PPC-Mac OS X 32 bit"
|
||||||
@echo "osx-x86-64 > x86-Mac OS X 64 bit"
|
@echo "osx-x86-64 > x86-Mac OS X 64 bit"
|
||||||
@echo "osx-x86-32 > x86-Mac OS X 32 bit"
|
@echo "osx-x86-32 > x86-Mac OS X 32 bit"
|
||||||
|
@echo "armv7 > ARMv7 32 bit"
|
||||||
@echo "general-64 > unspecified 64-bit"
|
@echo "general-64 > unspecified 64-bit"
|
||||||
@echo "general-32 > unspecified 32-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 ""
|
||||||
@echo "Supported comps:"
|
@echo "Supported comps:"
|
||||||
@echo ""
|
@echo ""
|
||||||
@echo "gcc > Gnu compiler (default)"
|
@echo "gcc > Gnu compiler (default)"
|
||||||
@echo "icc > Intel compiler"
|
@echo "icc > Intel compiler"
|
||||||
@echo "mingw > Gnu compiler with MinGW under Windows"
|
@echo "mingw > Gnu compiler with MinGW under Windows"
|
||||||
|
@echo "clang > LLVM Clang compiler"
|
||||||
@echo ""
|
@echo ""
|
||||||
@echo "Non-standard targets:"
|
@echo "Non-standard targets:"
|
||||||
@echo ""
|
@echo ""
|
||||||
@@ -398,34 +437,6 @@ profile-build:
|
|||||||
@echo "Step 4/4. Deleting profile data ..."
|
@echo "Step 4/4. Deleting profile data ..."
|
||||||
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
|
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
|
||||||
|
|
||||||
double-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:
|
||||||
strip $(EXE)
|
strip $(EXE)
|
||||||
|
|
||||||
@@ -457,10 +468,10 @@ config-sanity:
|
|||||||
@echo "arch: '$(arch)'"
|
@echo "arch: '$(arch)'"
|
||||||
@echo "os: '$(os)'"
|
@echo "os: '$(os)'"
|
||||||
@echo "bits: '$(bits)'"
|
@echo "bits: '$(bits)'"
|
||||||
@echo "bigendian: '$(bigendian)'"
|
|
||||||
@echo "prefetch: '$(prefetch)'"
|
@echo "prefetch: '$(prefetch)'"
|
||||||
@echo "bsfq: '$(bsfq)'"
|
@echo "bsfq: '$(bsfq)'"
|
||||||
@echo "popcnt: '$(popcnt)'"
|
@echo "popcnt: '$(popcnt)'"
|
||||||
|
@echo "sse: '$(sse)'"
|
||||||
@echo ""
|
@echo ""
|
||||||
@echo "Flags:"
|
@echo "Flags:"
|
||||||
@echo "CXX: $(CXX)"
|
@echo "CXX: $(CXX)"
|
||||||
@@ -472,14 +483,14 @@ config-sanity:
|
|||||||
@test "$(debug)" = "yes" || test "$(debug)" = "no"
|
@test "$(debug)" = "yes" || test "$(debug)" = "no"
|
||||||
@test "$(optimize)" = "yes" || test "$(optimize)" = "no"
|
@test "$(optimize)" = "yes" || test "$(optimize)" = "no"
|
||||||
@test "$(arch)" = "any" || test "$(arch)" = "x86_64" || test "$(arch)" = "i386" || \
|
@test "$(arch)" = "any" || test "$(arch)" = "x86_64" || test "$(arch)" = "i386" || \
|
||||||
test "$(arch)" = "ppc64" || test "$(arch)" = "ppc"
|
test "$(arch)" = "ppc64" || test "$(arch)" = "ppc" || test "$(arch)" = "armv7"
|
||||||
@test "$(os)" = "any" || test "$(os)" = "osx"
|
@test "$(os)" = "any" || test "$(os)" = "osx"
|
||||||
@test "$(bits)" = "32" || test "$(bits)" = "64"
|
@test "$(bits)" = "32" || test "$(bits)" = "64"
|
||||||
@test "$(bigendian)" = "yes" || test "$(bigendian)" = "no"
|
|
||||||
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
|
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
|
||||||
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
|
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
|
||||||
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
|
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
|
||||||
@test "$(comp)" = "gcc" || test "$(comp)" = "icc" || test "$(comp)" = "mingw"
|
@test "$(sse)" = "yes" || test "$(sse)" = "no"
|
||||||
|
@test "$(comp)" = "gcc" || test "$(comp)" = "icc" || test "$(comp)" = "mingw" || test "$(comp)" = "clang"
|
||||||
|
|
||||||
$(EXE): $(OBJS)
|
$(EXE): $(OBJS)
|
||||||
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
|
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
|
||||||
@@ -531,7 +542,7 @@ icc-profile-clean:
|
|||||||
|
|
||||||
hpux:
|
hpux:
|
||||||
$(MAKE) \
|
$(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="" \
|
CXXFLAGS="" \
|
||||||
LDFLAGS="" \
|
LDFLAGS="" \
|
||||||
all
|
all
|
||||||
|
|||||||
+41
-31
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -19,16 +19,17 @@
|
|||||||
|
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <istream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "misc.h"
|
#include "misc.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
|
#include "tt.h"
|
||||||
#include "ucioption.h"
|
#include "ucioption.h"
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
using namespace Search;
|
|
||||||
|
|
||||||
static const char* Defaults[] = {
|
static const char* Defaults[] = {
|
||||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||||
@@ -58,34 +59,42 @@ static const char* Defaults[] = {
|
|||||||
/// format (defaults are the positions defined above) and the type of the
|
/// format (defaults are the positions defined above) and the type of the
|
||||||
/// limit value: depth (default), time in secs or number of nodes.
|
/// limit value: depth (default), time in secs or number of nodes.
|
||||||
|
|
||||||
void benchmark(int argc, char* argv[]) {
|
void benchmark(const Position& current, istream& is) {
|
||||||
|
|
||||||
|
string token;
|
||||||
|
Search::LimitsType limits;
|
||||||
vector<string> fens;
|
vector<string> fens;
|
||||||
LimitsType limits;
|
|
||||||
int time;
|
|
||||||
int64_t nodes = 0;
|
|
||||||
|
|
||||||
// Assign default values to missing arguments
|
// Assign default values to missing arguments
|
||||||
string ttSize = argc > 2 ? argv[2] : "128";
|
string ttSize = (is >> token) ? token : "32";
|
||||||
string threads = argc > 3 ? argv[3] : "1";
|
string threads = (is >> token) ? token : "1";
|
||||||
string valStr = argc > 4 ? argv[4] : "12";
|
string limit = (is >> token) ? token : "12";
|
||||||
string fenFile = argc > 5 ? argv[5] : "default";
|
string fenFile = (is >> token) ? token : "default";
|
||||||
string valType = argc > 6 ? argv[6] : "depth";
|
string limitType = (is >> token) ? token : "depth";
|
||||||
|
|
||||||
Options["Hash"] = ttSize;
|
Options["Hash"] = ttSize;
|
||||||
Options["Threads"] = threads;
|
Options["Threads"] = threads;
|
||||||
Options["OwnBook"] = false;
|
TT.clear();
|
||||||
|
|
||||||
if (valType == "time")
|
if (limitType == "time")
|
||||||
limits.maxTime = 1000 * atoi(valStr.c_str()); // maxTime is in ms
|
limits.movetime = 1000 * atoi(limit.c_str()); // movetime is in ms
|
||||||
|
|
||||||
else if (valType == "nodes")
|
else if (limitType == "nodes")
|
||||||
limits.maxNodes = atoi(valStr.c_str());
|
limits.nodes = atoi(limit.c_str());
|
||||||
|
|
||||||
|
else if (limitType == "mate")
|
||||||
|
limits.mate = atoi(limit.c_str());
|
||||||
|
|
||||||
else
|
else
|
||||||
limits.maxDepth = atoi(valStr.c_str());
|
limits.depth = atoi(limit.c_str());
|
||||||
|
|
||||||
if (fenFile != "default")
|
if (fenFile == "default")
|
||||||
|
fens.assign(Defaults, Defaults + 16);
|
||||||
|
|
||||||
|
else if (fenFile == "current")
|
||||||
|
fens.push_back(current.fen());
|
||||||
|
|
||||||
|
else
|
||||||
{
|
{
|
||||||
string fen;
|
string fen;
|
||||||
ifstream file(fenFile.c_str());
|
ifstream file(fenFile.c_str());
|
||||||
@@ -93,7 +102,7 @@ void benchmark(int argc, char* argv[]) {
|
|||||||
if (!file.is_open())
|
if (!file.is_open())
|
||||||
{
|
{
|
||||||
cerr << "Unable to open file " << fenFile << endl;
|
cerr << "Unable to open file " << fenFile << endl;
|
||||||
exit(EXIT_FAILURE);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
while (getline(file, fen))
|
while (getline(file, fen))
|
||||||
@@ -102,34 +111,35 @@ void benchmark(int argc, char* argv[]) {
|
|||||||
|
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
else
|
|
||||||
fens.assign(Defaults, Defaults + 16);
|
|
||||||
|
|
||||||
time = system_time();
|
int64_t nodes = 0;
|
||||||
|
Search::StateStackPtr st;
|
||||||
|
Time::point elapsed = Time::now();
|
||||||
|
|
||||||
for (size_t i = 0; i < fens.size(); i++)
|
for (size_t i = 0; i < fens.size(); i++)
|
||||||
{
|
{
|
||||||
Position pos(fens[i], false, 0);
|
Position pos(fens[i], Options["UCI_Chess960"], Threads.main_thread());
|
||||||
|
|
||||||
cerr << "\nPosition: " << i + 1 << '/' << fens.size() << endl;
|
cerr << "\nPosition: " << i + 1 << '/' << fens.size() << endl;
|
||||||
|
|
||||||
if (valType == "perft")
|
if (limitType == "perft")
|
||||||
{
|
{
|
||||||
int64_t cnt = perft(pos, limits.maxDepth * ONE_PLY);
|
size_t cnt = Search::perft(pos, limits.depth * ONE_PLY);
|
||||||
cerr << "\nPerft " << limits.maxDepth << " leaf nodes: " << cnt << endl;
|
cerr << "\nPerft " << limits.depth << " leaf nodes: " << cnt << endl;
|
||||||
nodes += cnt;
|
nodes += cnt;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Threads.start_thinking(pos, limits, vector<Move>(), false);
|
Threads.start_thinking(pos, limits, vector<Move>(), st);
|
||||||
nodes += RootPosition.nodes_searched();
|
Threads.wait_for_think_finished();
|
||||||
|
nodes += Search::RootPos.nodes_searched();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
time = system_time() - time;
|
elapsed = Time::now() - elapsed + 1; // Assure positive to avoid a 'divide by zero'
|
||||||
|
|
||||||
cerr << "\n==========================="
|
cerr << "\n==========================="
|
||||||
<< "\nTotal time (ms) : " << time
|
<< "\nTotal time (ms) : " << elapsed
|
||||||
<< "\nNodes searched : " << nodes
|
<< "\nNodes searched : " << nodes
|
||||||
<< "\nNodes/second : " << int(nodes / (time / 1000.0)) << endl;
|
<< "\nNodes/second : " << 1000 * nodes / elapsed << endl;
|
||||||
}
|
}
|
||||||
|
|||||||
+119
-217
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -18,254 +18,156 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
enum Result {
|
|
||||||
RESULT_UNKNOWN,
|
|
||||||
RESULT_INVALID,
|
|
||||||
RESULT_WIN,
|
|
||||||
RESULT_DRAW
|
|
||||||
};
|
|
||||||
|
|
||||||
struct KPKPosition {
|
|
||||||
Result classify_knowns(int index);
|
|
||||||
Result classify(int index, Result db[]);
|
|
||||||
|
|
||||||
private:
|
|
||||||
void from_index(int index);
|
|
||||||
Result classify_white(const Result db[]);
|
|
||||||
Result classify_black(const Result db[]);
|
|
||||||
Bitboard wk_attacks() const { return StepAttacksBB[W_KING][whiteKingSquare]; }
|
|
||||||
Bitboard bk_attacks() const { return StepAttacksBB[B_KING][blackKingSquare]; }
|
|
||||||
Bitboard pawn_attacks() const { return StepAttacksBB[W_PAWN][pawnSquare]; }
|
|
||||||
|
|
||||||
Square whiteKingSquare, blackKingSquare, pawnSquare;
|
|
||||||
Color sideToMove;
|
|
||||||
};
|
|
||||||
|
|
||||||
// The possible pawns squares are 24, the first 4 files and ranks from 2 to 7
|
// 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 = 196608
|
const unsigned IndexMax = 2*24*64*64; // stm * psq * wksq * bksq = 196608
|
||||||
|
|
||||||
// Each uint32_t stores results of 32 positions, one per bit
|
// Each uint32_t stores results of 32 positions, one per bit
|
||||||
uint32_t KPKBitbase[IndexMax / 32];
|
uint32_t KPKBitbase[IndexMax / 32];
|
||||||
|
|
||||||
int compute_index(Square wksq, Square bksq, Square wpsq, Color stm);
|
// A KPK bitbase index is an integer in [0, IndexMax] range
|
||||||
|
//
|
||||||
|
// Information is mapped in a way that minimizes number of iterations:
|
||||||
|
//
|
||||||
|
// bit 0- 5: white king square (from SQ_A1 to SQ_H8)
|
||||||
|
// bit 6-11: black king square (from SQ_A1 to SQ_H8)
|
||||||
|
// bit 12: side to move (WHITE or BLACK)
|
||||||
|
// bit 13-14: white pawn file (from FILE_A to FILE_D)
|
||||||
|
// bit 15-17: white pawn 6 - rank (from 6 - RANK_7 to 6 - RANK_2)
|
||||||
|
unsigned index(Color us, Square bksq, Square wksq, Square psq) {
|
||||||
|
return wksq + (bksq << 6) + (us << 12) + (file_of(psq) << 13) + ((6 - rank_of(psq)) << 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Result {
|
||||||
|
INVALID = 0,
|
||||||
|
UNKNOWN = 1,
|
||||||
|
DRAW = 2,
|
||||||
|
WIN = 4
|
||||||
|
};
|
||||||
|
|
||||||
|
inline Result& operator|=(Result& r, Result v) { return r = Result(r | v); }
|
||||||
|
|
||||||
|
struct KPKPosition {
|
||||||
|
|
||||||
|
operator Result() const { return res; }
|
||||||
|
Result classify_leaf(unsigned idx);
|
||||||
|
Result classify(const std::vector<KPKPosition>& db)
|
||||||
|
{ return us == WHITE ? classify<WHITE>(db) : classify<BLACK>(db); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
template<Color Us> Result classify(const std::vector<KPKPosition>& db);
|
||||||
|
|
||||||
|
Color us;
|
||||||
|
Square bksq, wksq, psq;
|
||||||
|
Result res;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
|
||||||
|
bool Bitbases::probe_kpk(Square wksq, Square wpsq, Square bksq, Color us) {
|
||||||
|
|
||||||
|
assert(file_of(wpsq) <= FILE_D);
|
||||||
|
|
||||||
|
unsigned idx = index(us, bksq, wksq, wpsq);
|
||||||
|
return KPKBitbase[idx / 32] & (1 << (idx & 0x1F));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm) {
|
void Bitbases::init_kpk() {
|
||||||
|
|
||||||
int index = compute_index(wksq, bksq, wpsq, stm);
|
unsigned idx, repeat = 1;
|
||||||
|
std::vector<KPKPosition> db(IndexMax);
|
||||||
|
|
||||||
return KPKBitbase[index / 32] & (1 << (index & 31));
|
// Initialize db with known win / draw positions
|
||||||
}
|
for (idx = 0; idx < IndexMax; idx++)
|
||||||
|
db[idx].classify_leaf(idx);
|
||||||
|
|
||||||
|
// Iterate through the positions until no more of the unknown positions can be
|
||||||
void kpk_bitbase_init() {
|
// changed to either wins or draws (15 cycles needed).
|
||||||
|
|
||||||
Result db[IndexMax];
|
|
||||||
KPKPosition pos;
|
|
||||||
int index, bit, repeat = 1;
|
|
||||||
|
|
||||||
// Initialize table
|
|
||||||
for (index = 0; index < IndexMax; index++)
|
|
||||||
db[index] = pos.classify_knowns(index);
|
|
||||||
|
|
||||||
// Iterate until all positions are classified (30 cycles needed)
|
|
||||||
while (repeat)
|
while (repeat)
|
||||||
for (repeat = index = 0; index < IndexMax; index++)
|
for (repeat = idx = 0; idx < IndexMax; idx++)
|
||||||
if ( db[index] == RESULT_UNKNOWN
|
if (db[idx] == UNKNOWN && db[idx].classify(db) != UNKNOWN)
|
||||||
&& pos.classify(index, db) != RESULT_UNKNOWN)
|
|
||||||
repeat = 1;
|
repeat = 1;
|
||||||
|
|
||||||
// Map 32 position results into one KPKBitbase[] entry
|
// Map 32 results into one KPKBitbase[] entry
|
||||||
for (index = 0; index < IndexMax / 32; index++)
|
for (idx = 0; idx < IndexMax; idx++)
|
||||||
for (bit = 0; bit < 32; bit++)
|
if (db[idx] == WIN)
|
||||||
if (db[32 * index + bit] == RESULT_WIN)
|
KPKBitbase[idx / 32] |= 1 << (idx & 0x1F);
|
||||||
KPKBitbase[index] |= (1 << bit);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
// A KPK bitbase index is an integer in [0, IndexMax] range
|
Result KPKPosition::classify_leaf(unsigned idx) {
|
||||||
|
|
||||||
|
wksq = Square((idx >> 0) & 0x3F);
|
||||||
|
bksq = Square((idx >> 6) & 0x3F);
|
||||||
|
us = Color((idx >> 12) & 0x01);
|
||||||
|
psq = File((idx >> 13) & 3) | Rank(6 - (idx >> 15));
|
||||||
|
|
||||||
|
// Check if two pieces are on the same square or if a king can be captured
|
||||||
|
if ( wksq == psq || wksq == bksq || bksq == psq
|
||||||
|
|| (StepAttacksBB[KING][wksq] & bksq)
|
||||||
|
|| (us == WHITE && (StepAttacksBB[PAWN][psq] & bksq)))
|
||||||
|
return res = INVALID;
|
||||||
|
|
||||||
|
if (us == WHITE)
|
||||||
|
{
|
||||||
|
// Immediate win if pawn can be promoted without getting captured
|
||||||
|
if ( rank_of(psq) == RANK_7
|
||||||
|
&& wksq != psq + DELTA_N
|
||||||
|
&& ( square_distance(bksq, psq + DELTA_N) > 1
|
||||||
|
||(StepAttacksBB[KING][wksq] & (psq + DELTA_N))))
|
||||||
|
return res = WIN;
|
||||||
|
}
|
||||||
|
// Immediate draw if is stalemate or king captures undefended pawn
|
||||||
|
else if ( !(StepAttacksBB[KING][bksq] & ~(StepAttacksBB[KING][wksq] | StepAttacksBB[PAWN][psq]))
|
||||||
|
|| (StepAttacksBB[KING][bksq] & psq & ~StepAttacksBB[KING][wksq]))
|
||||||
|
return res = DRAW;
|
||||||
|
|
||||||
|
return res = UNKNOWN;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<Color Us>
|
||||||
|
Result KPKPosition::classify(const std::vector<KPKPosition>& db) {
|
||||||
|
|
||||||
|
// White to Move: If one move leads to a position classified as WIN, the result
|
||||||
|
// of the current position is WIN. If all moves lead to positions classified
|
||||||
|
// as DRAW, the current position is classified DRAW otherwise the current
|
||||||
|
// position is classified as UNKNOWN.
|
||||||
//
|
//
|
||||||
// Information is mapped in this way
|
// Black to Move: If one move leads to a position classified as DRAW, the result
|
||||||
//
|
// of the current position is DRAW. If all moves lead to positions classified
|
||||||
// bit 0: side to move (WHITE or BLACK)
|
// as WIN, the position is classified WIN otherwise the current position is
|
||||||
// bit 1- 6: black king square (from SQ_A1 to SQ_H8)
|
// classified UNKNOWN.
|
||||||
// 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) {
|
Result r = INVALID;
|
||||||
|
Bitboard b = StepAttacksBB[KING][Us == WHITE ? wksq : bksq];
|
||||||
|
|
||||||
assert(file_of(wpsq) <= FILE_D);
|
|
||||||
|
|
||||||
int p = file_of(wpsq) + 4 * (rank_of(wpsq) - 1);
|
|
||||||
int r = stm + 2 * bksq + 128 * wksq + 8192 * p;
|
|
||||||
|
|
||||||
assert(r >= 0 && r < IndexMax);
|
|
||||||
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
void KPKPosition::from_index(int index) {
|
|
||||||
|
|
||||||
int s = index >> 13;
|
|
||||||
sideToMove = Color(index & 1);
|
|
||||||
blackKingSquare = Square((index >> 1) & 63);
|
|
||||||
whiteKingSquare = Square((index >> 7) & 63);
|
|
||||||
pawnSquare = make_square(File(s & 3), Rank((s >> 2) + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
Result KPKPosition::classify_knowns(int index) {
|
|
||||||
|
|
||||||
from_index(index);
|
|
||||||
|
|
||||||
// Check if two pieces are on the same square
|
|
||||||
if ( whiteKingSquare == pawnSquare
|
|
||||||
|| whiteKingSquare == blackKingSquare
|
|
||||||
|| blackKingSquare == pawnSquare)
|
|
||||||
return RESULT_INVALID;
|
|
||||||
|
|
||||||
// Check if a king can be captured
|
|
||||||
if ( bit_is_set(wk_attacks(), blackKingSquare)
|
|
||||||
|| (bit_is_set(pawn_attacks(), blackKingSquare) && sideToMove == WHITE))
|
|
||||||
return RESULT_INVALID;
|
|
||||||
|
|
||||||
// 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(pawnSquare) == RANK_7
|
|
||||||
&& sideToMove == WHITE
|
|
||||||
&& whiteKingSquare != pawnSquare + DELTA_N
|
|
||||||
&& ( square_distance(blackKingSquare, pawnSquare + DELTA_N) > 1
|
|
||||||
|| bit_is_set(wk_attacks(), pawnSquare + DELTA_N)))
|
|
||||||
return RESULT_WIN;
|
|
||||||
|
|
||||||
// Check for known draw positions
|
|
||||||
//
|
|
||||||
// Case 1: Stalemate
|
|
||||||
if ( sideToMove == BLACK
|
|
||||||
&& !(bk_attacks() & ~(wk_attacks() | pawn_attacks())))
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
// Case 2: King can capture pawn
|
|
||||||
if ( sideToMove == BLACK
|
|
||||||
&& bit_is_set(bk_attacks(), pawnSquare) && !bit_is_set(wk_attacks(), pawnSquare))
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
// Case 3: Black king in front of white pawn
|
|
||||||
if ( blackKingSquare == pawnSquare + DELTA_N
|
|
||||||
&& rank_of(pawnSquare) < RANK_7)
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
// Case 4: White king in front of pawn and black has opposition
|
|
||||||
if ( whiteKingSquare == pawnSquare + DELTA_N
|
|
||||||
&& blackKingSquare == pawnSquare + DELTA_N + DELTA_N + DELTA_N
|
|
||||||
&& rank_of(pawnSquare) < RANK_5
|
|
||||||
&& sideToMove == WHITE)
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
// Case 5: Stalemate with rook pawn
|
|
||||||
if ( blackKingSquare == SQ_A8
|
|
||||||
&& file_of(pawnSquare) == FILE_A)
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
return RESULT_UNKNOWN;
|
|
||||||
}
|
|
||||||
|
|
||||||
Result KPKPosition::classify(int index, Result db[]) {
|
|
||||||
|
|
||||||
from_index(index);
|
|
||||||
db[index] = (sideToMove == WHITE ? classify_white(db) : classify_black(db));
|
|
||||||
return db[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
Result KPKPosition::classify_white(const Result db[]) {
|
|
||||||
|
|
||||||
// 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.
|
|
||||||
|
|
||||||
bool unknownFound = false;
|
|
||||||
Bitboard b;
|
|
||||||
Square s;
|
|
||||||
Result r;
|
|
||||||
|
|
||||||
// King moves
|
|
||||||
b = wk_attacks();
|
|
||||||
while (b)
|
while (b)
|
||||||
|
r |= Us == WHITE ? db[index(~Us, bksq, pop_lsb(&b), psq)]
|
||||||
|
: db[index(~Us, pop_lsb(&b), wksq, psq)];
|
||||||
|
|
||||||
|
if (Us == WHITE && rank_of(psq) < RANK_7)
|
||||||
{
|
{
|
||||||
s = pop_1st_bit(&b);
|
Square s = psq + DELTA_N;
|
||||||
r = db[compute_index(s, blackKingSquare, pawnSquare, BLACK)];
|
r |= db[index(BLACK, bksq, wksq, s)]; // Single push
|
||||||
|
|
||||||
if (r == RESULT_WIN)
|
if (rank_of(s) == RANK_3 && s != wksq && s != bksq)
|
||||||
return RESULT_WIN;
|
r |= db[index(BLACK, bksq, wksq, s + DELTA_N)]; // Double push
|
||||||
|
|
||||||
if (r == RESULT_UNKNOWN)
|
|
||||||
unknownFound = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pawn moves
|
if (Us == WHITE)
|
||||||
if (rank_of(pawnSquare) < RANK_7)
|
return res = r & WIN ? WIN : r & UNKNOWN ? UNKNOWN : DRAW;
|
||||||
{
|
else
|
||||||
s = pawnSquare + DELTA_N;
|
return res = r & DRAW ? DRAW : r & UNKNOWN ? UNKNOWN : WIN;
|
||||||
r = db[compute_index(whiteKingSquare, blackKingSquare, s, BLACK)];
|
|
||||||
|
|
||||||
if (r == RESULT_WIN)
|
|
||||||
return RESULT_WIN;
|
|
||||||
|
|
||||||
if (r == RESULT_UNKNOWN)
|
|
||||||
unknownFound = true;
|
|
||||||
|
|
||||||
// Double pawn push
|
|
||||||
if (rank_of(s) == RANK_3 && r != RESULT_INVALID)
|
|
||||||
{
|
|
||||||
s += DELTA_N;
|
|
||||||
r = db[compute_index(whiteKingSquare, blackKingSquare, s, BLACK)];
|
|
||||||
|
|
||||||
if (r == RESULT_WIN)
|
|
||||||
return RESULT_WIN;
|
|
||||||
|
|
||||||
if (r == RESULT_UNKNOWN)
|
|
||||||
unknownFound = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return unknownFound ? RESULT_UNKNOWN : RESULT_DRAW;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Result KPKPosition::classify_black(const Result db[]) {
|
} // namespace
|
||||||
|
|
||||||
// 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 as RESULT_WIN.
|
|
||||||
// Otherwise, the current position is classified as RESULT_UNKNOWN.
|
|
||||||
|
|
||||||
bool unknownFound = false;
|
|
||||||
Bitboard b;
|
|
||||||
Square s;
|
|
||||||
Result r;
|
|
||||||
|
|
||||||
// King moves
|
|
||||||
b = bk_attacks();
|
|
||||||
while (b)
|
|
||||||
{
|
|
||||||
s = pop_1st_bit(&b);
|
|
||||||
r = db[compute_index(whiteKingSquare, s, pawnSquare, WHITE)];
|
|
||||||
|
|
||||||
if (r == RESULT_DRAW)
|
|
||||||
return RESULT_DRAW;
|
|
||||||
|
|
||||||
if (r == RESULT_UNKNOWN)
|
|
||||||
unknownFound = true;
|
|
||||||
}
|
|
||||||
return unknownFound ? RESULT_UNKNOWN : RESULT_WIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|||||||
+163
-184
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -23,190 +23,179 @@
|
|||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
#include "bitcount.h"
|
#include "bitcount.h"
|
||||||
|
#include "misc.h"
|
||||||
#include "rkiss.h"
|
#include "rkiss.h"
|
||||||
|
|
||||||
Bitboard RMasks[64];
|
|
||||||
Bitboard RMagics[64];
|
|
||||||
Bitboard* RAttacks[64];
|
|
||||||
int RShifts[64];
|
|
||||||
|
|
||||||
Bitboard BMasks[64];
|
|
||||||
Bitboard BMagics[64];
|
|
||||||
Bitboard* BAttacks[64];
|
|
||||||
int BShifts[64];
|
|
||||||
|
|
||||||
Bitboard SetMaskBB[65];
|
|
||||||
Bitboard ClearMaskBB[65];
|
|
||||||
|
|
||||||
Bitboard FileBB[8];
|
|
||||||
Bitboard RankBB[8];
|
|
||||||
Bitboard NeighboringFilesBB[8];
|
|
||||||
Bitboard ThisAndNeighboringFilesBB[8];
|
|
||||||
Bitboard InFrontBB[2][8];
|
|
||||||
Bitboard StepAttacksBB[16][64];
|
|
||||||
Bitboard BetweenBB[64][64];
|
|
||||||
Bitboard SquaresInFrontMask[2][64];
|
|
||||||
Bitboard PassedPawnMask[2][64];
|
|
||||||
Bitboard AttackSpanMask[2][64];
|
|
||||||
|
|
||||||
Bitboard BishopPseudoAttacks[64];
|
|
||||||
Bitboard RookPseudoAttacks[64];
|
|
||||||
Bitboard QueenPseudoAttacks[64];
|
|
||||||
|
|
||||||
uint8_t BitCount8Bit[256];
|
|
||||||
int SquareDistance[64][64];
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
|
|
||||||
CACHE_LINE_ALIGNMENT
|
CACHE_LINE_ALIGNMENT
|
||||||
|
|
||||||
int BSFTable[64];
|
Bitboard RMasks[SQUARE_NB];
|
||||||
Bitboard RookTable[0x19000]; // Storage space for rook attacks
|
Bitboard RMagics[SQUARE_NB];
|
||||||
Bitboard BishopTable[0x1480]; // Storage space for bishop attacks
|
Bitboard* RAttacks[SQUARE_NB];
|
||||||
|
unsigned RShifts[SQUARE_NB];
|
||||||
|
|
||||||
void init_magic_bitboards(PieceType pt, Bitboard* attacks[], Bitboard magics[],
|
Bitboard BMasks[SQUARE_NB];
|
||||||
Bitboard masks[], int shifts[]);
|
Bitboard BMagics[SQUARE_NB];
|
||||||
}
|
Bitboard* BAttacks[SQUARE_NB];
|
||||||
|
unsigned BShifts[SQUARE_NB];
|
||||||
|
|
||||||
|
Bitboard SquareBB[SQUARE_NB];
|
||||||
|
Bitboard FileBB[FILE_NB];
|
||||||
|
Bitboard RankBB[RANK_NB];
|
||||||
|
Bitboard AdjacentFilesBB[FILE_NB];
|
||||||
|
Bitboard ThisAndAdjacentFilesBB[FILE_NB];
|
||||||
|
Bitboard InFrontBB[COLOR_NB][RANK_NB];
|
||||||
|
Bitboard StepAttacksBB[PIECE_NB][SQUARE_NB];
|
||||||
|
Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
|
||||||
|
Bitboard DistanceRingsBB[SQUARE_NB][8];
|
||||||
|
Bitboard ForwardBB[COLOR_NB][SQUARE_NB];
|
||||||
|
Bitboard PassedPawnMask[COLOR_NB][SQUARE_NB];
|
||||||
|
Bitboard AttackSpanMask[COLOR_NB][SQUARE_NB];
|
||||||
|
Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
|
||||||
|
|
||||||
/// print_bitboard() prints a bitboard in an easily readable format to the
|
int SquareDistance[SQUARE_NB][SQUARE_NB];
|
||||||
/// standard output. This is sometimes useful for debugging.
|
|
||||||
|
|
||||||
void print_bitboard(Bitboard b) {
|
namespace {
|
||||||
|
|
||||||
for (Rank r = RANK_8; r >= RANK_1; r--)
|
// De Bruijn sequences. See chessprogramming.wikispaces.com/BitScan
|
||||||
{
|
const uint64_t DeBruijn_64 = 0x3F79D71B4CB0A89ULL;
|
||||||
std::cout << "+---+---+---+---+---+---+---+---+" << '\n';
|
const uint32_t DeBruijn_32 = 0x783A9B23;
|
||||||
for (File f = FILE_A; f <= FILE_H; f++)
|
|
||||||
std::cout << "| " << (bit_is_set(b, make_square(f, r)) ? "X " : " ");
|
|
||||||
|
|
||||||
std::cout << "|\n";
|
CACHE_LINE_ALIGNMENT
|
||||||
}
|
|
||||||
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
int MS1BTable[256];
|
||||||
|
Square BSFTable[SQUARE_NB];
|
||||||
|
Bitboard RTable[0x19000]; // Storage space for rook attacks
|
||||||
|
Bitboard BTable[0x1480]; // Storage space for bishop attacks
|
||||||
|
|
||||||
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
typedef unsigned (Fn)(Square, Bitboard);
|
||||||
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
|
||||||
/// nonzero bitboard.
|
|
||||||
|
|
||||||
#if defined(IS_64BIT) && !defined(USE_BSFQ)
|
void init_magics(Bitboard table[], Bitboard* attacks[], Bitboard magics[],
|
||||||
|
Bitboard masks[], unsigned shifts[], Square deltas[], Fn index);
|
||||||
|
|
||||||
Square first_1(Bitboard b) {
|
FORCE_INLINE unsigned bsf_index(Bitboard b) {
|
||||||
return Square(BSFTable[((b & -b) * 0x218A392CD3D5DBFULL) >> 58]);
|
|
||||||
}
|
|
||||||
|
|
||||||
Square pop_1st_bit(Bitboard* b) {
|
// Matt Taylor's folding for 32 bit systems, extended to 64 bits by Kim Walisch
|
||||||
Bitboard bb = *b;
|
|
||||||
*b &= (*b - 1);
|
|
||||||
return Square(BSFTable[((bb & -bb) * 0x218A392CD3D5DBFULL) >> 58]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#elif !defined(USE_BSFQ)
|
|
||||||
|
|
||||||
Square first_1(Bitboard b) {
|
|
||||||
b ^= (b - 1);
|
b ^= (b - 1);
|
||||||
uint32_t fold = unsigned(b) ^ unsigned(b >> 32);
|
return Is64Bit ? (b * DeBruijn_64) >> 58
|
||||||
return Square(BSFTable[(fold * 0x783A9B23) >> 26]);
|
: ((unsigned(b) ^ unsigned(b >> 32)) * DeBruijn_32) >> 26;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use type-punning
|
/// lsb()/msb() finds the least/most significant bit in a nonzero bitboard.
|
||||||
union b_union {
|
/// pop_lsb() finds and clears the least significant bit in a nonzero bitboard.
|
||||||
|
|
||||||
Bitboard b;
|
#if !defined(USE_BSFQ)
|
||||||
struct {
|
|
||||||
#if defined (BIGENDIAN)
|
|
||||||
uint32_t h;
|
|
||||||
uint32_t l;
|
|
||||||
#else
|
|
||||||
uint32_t l;
|
|
||||||
uint32_t h;
|
|
||||||
#endif
|
|
||||||
} dw;
|
|
||||||
};
|
|
||||||
|
|
||||||
Square pop_1st_bit(Bitboard* bb) {
|
Square lsb(Bitboard b) { return BSFTable[bsf_index(b)]; }
|
||||||
|
|
||||||
b_union u;
|
Square pop_lsb(Bitboard* b) {
|
||||||
Square ret;
|
|
||||||
|
|
||||||
u.b = *bb;
|
Bitboard bb = *b;
|
||||||
|
*b = bb & (bb - 1);
|
||||||
|
return BSFTable[bsf_index(bb)];
|
||||||
|
}
|
||||||
|
|
||||||
if (u.dw.l)
|
Square msb(Bitboard b) {
|
||||||
|
|
||||||
|
unsigned b32;
|
||||||
|
int result = 0;
|
||||||
|
|
||||||
|
if (b > 0xFFFFFFFF)
|
||||||
{
|
{
|
||||||
ret = Square(BSFTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783A9B23) >> 26]);
|
b >>= 32;
|
||||||
u.dw.l &= (u.dw.l - 1);
|
result = 32;
|
||||||
*bb = u.b;
|
|
||||||
return ret;
|
|
||||||
}
|
}
|
||||||
ret = Square(BSFTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783A9B23) >> 26]);
|
|
||||||
u.dw.h &= (u.dw.h - 1);
|
b32 = unsigned(b);
|
||||||
*bb = u.b;
|
|
||||||
return ret;
|
if (b32 > 0xFFFF)
|
||||||
|
{
|
||||||
|
b32 >>= 16;
|
||||||
|
result += 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (b32 > 0xFF)
|
||||||
|
{
|
||||||
|
b32 >>= 8;
|
||||||
|
result += 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (Square)(result + MS1BTable[b32]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // !defined(USE_BSFQ)
|
#endif // !defined(USE_BSFQ)
|
||||||
|
|
||||||
|
|
||||||
/// bitboards_init() initializes various bitboard arrays. It is called during
|
/// Bitboards::print() prints a bitboard in an easily readable format to the
|
||||||
/// program initialization.
|
/// standard output. This is sometimes useful for debugging.
|
||||||
|
|
||||||
void bitboards_init() {
|
void Bitboards::print(Bitboard b) {
|
||||||
|
|
||||||
for (Bitboard b = 0; b < 256; b++)
|
sync_cout;
|
||||||
BitCount8Bit[b] = (uint8_t)popcount<Max15>(b);
|
|
||||||
|
|
||||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
for (Rank rank = RANK_8; rank >= RANK_1; rank--)
|
||||||
{
|
{
|
||||||
SetMaskBB[s] = 1ULL << s;
|
std::cout << "+---+---+---+---+---+---+---+---+" << '\n';
|
||||||
ClearMaskBB[s] = ~SetMaskBB[s];
|
|
||||||
|
for (File file = FILE_A; file <= FILE_H; file++)
|
||||||
|
std::cout << "| " << (b & (file | rank) ? "X " : " ");
|
||||||
|
|
||||||
|
std::cout << "|\n";
|
||||||
|
}
|
||||||
|
std::cout << "+---+---+---+---+---+---+---+---+" << sync_endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
ClearMaskBB[SQ_NONE] = ~0ULL;
|
|
||||||
|
/// Bitboards::init() initializes various bitboard arrays. It is called during
|
||||||
|
/// program initialization.
|
||||||
|
|
||||||
|
void Bitboards::init() {
|
||||||
|
|
||||||
|
for (int k = 0, i = 0; i < 8; i++)
|
||||||
|
while (k < (2 << i))
|
||||||
|
MS1BTable[k++] = i;
|
||||||
|
|
||||||
|
for (int i = 0; i < 64; i++)
|
||||||
|
BSFTable[bsf_index(1ULL << i)] = Square(i);
|
||||||
|
|
||||||
|
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||||
|
SquareBB[s] = 1ULL << s;
|
||||||
|
|
||||||
FileBB[FILE_A] = FileABB;
|
FileBB[FILE_A] = FileABB;
|
||||||
RankBB[RANK_1] = Rank1BB;
|
RankBB[RANK_1] = Rank1BB;
|
||||||
|
|
||||||
for (int f = FILE_B; f <= FILE_H; f++)
|
for (int i = 1; i < 8; i++)
|
||||||
{
|
{
|
||||||
FileBB[f] = FileBB[f - 1] << 1;
|
FileBB[i] = FileBB[i - 1] << 1;
|
||||||
RankBB[f] = RankBB[f - 1] << 8;
|
RankBB[i] = RankBB[i - 1] << 8;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int f = FILE_A; f <= FILE_H; f++)
|
for (File f = FILE_A; f <= FILE_H; f++)
|
||||||
{
|
{
|
||||||
NeighboringFilesBB[f] = (f > FILE_A ? FileBB[f - 1] : 0) | (f < FILE_H ? FileBB[f + 1] : 0);
|
AdjacentFilesBB[f] = (f > FILE_A ? FileBB[f - 1] : 0) | (f < FILE_H ? FileBB[f + 1] : 0);
|
||||||
ThisAndNeighboringFilesBB[f] = FileBB[f] | NeighboringFilesBB[f];
|
ThisAndAdjacentFilesBB[f] = FileBB[f] | AdjacentFilesBB[f];
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int rw = RANK_7, rb = RANK_2; rw >= RANK_1; rw--, rb++)
|
for (Rank r = RANK_1; r < RANK_8; r++)
|
||||||
{
|
InFrontBB[WHITE][r] = ~(InFrontBB[BLACK][r + 1] = InFrontBB[BLACK][r] | RankBB[r]);
|
||||||
InFrontBB[WHITE][rw] = InFrontBB[WHITE][rw + 1] | RankBB[rw + 1];
|
|
||||||
InFrontBB[BLACK][rb] = InFrontBB[BLACK][rb - 1] | RankBB[rb - 1];
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Color c = WHITE; c <= BLACK; c++)
|
for (Color c = WHITE; c <= BLACK; c++)
|
||||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||||
{
|
{
|
||||||
SquaresInFrontMask[c][s] = in_front_bb(c, s) & file_bb(s);
|
ForwardBB[c][s] = InFrontBB[c][rank_of(s)] & FileBB[file_of(s)];
|
||||||
PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(file_of(s));
|
PassedPawnMask[c][s] = InFrontBB[c][rank_of(s)] & ThisAndAdjacentFilesBB[file_of(s)];
|
||||||
AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(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 s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||||
SquareDistance[s1][s2] = std::max(file_distance(s1, s2), rank_distance(s1, s2));
|
SquareDistance[s1][s2] = std::max(file_distance(s1, s2), rank_distance(s1, s2));
|
||||||
|
|
||||||
for (int i = 0; i < 64; i++)
|
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||||
if (!Is64Bit) // Matt Taylor's folding trick for 32 bit systems
|
for (int d = 1; d < 8; d++)
|
||||||
{
|
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||||
Bitboard b = 1ULL << i;
|
if (SquareDistance[s1][s2] == d)
|
||||||
b ^= b - 1;
|
DistanceRingsBB[s1][d - 1] |= s2;
|
||||||
b ^= b >> 32;
|
|
||||||
BSFTable[uint32_t(b * 0x783A9B23) >> 26] = i;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
BSFTable[((1ULL << i) * 0x218A392CD3D5DBFULL) >> 58] = i;
|
|
||||||
|
|
||||||
int steps[][9] = { {}, { 7, 9 }, { 17, 15, 10, 6, -6, -10, -15, -17 },
|
int steps[][9] = { {}, { 7, 9 }, { 17, 15, 10, 6, -6, -10, -15, -17 },
|
||||||
{}, {}, {}, { 9, 7, -7, -9, 8, 1, -1, -8 } };
|
{}, {}, {}, { 9, 7, -7, -9, 8, 1, -1, -8 } };
|
||||||
@@ -218,97 +207,85 @@ void bitboards_init() {
|
|||||||
{
|
{
|
||||||
Square to = s + Square(c == WHITE ? steps[pt][k] : -steps[pt][k]);
|
Square to = s + Square(c == WHITE ? steps[pt][k] : -steps[pt][k]);
|
||||||
|
|
||||||
if (square_is_ok(to) && square_distance(s, to) < 3)
|
if (is_ok(to) && square_distance(s, to) < 3)
|
||||||
set_bit(&StepAttacksBB[make_piece(c, pt)][s], to);
|
StepAttacksBB[make_piece(c, pt)][s] |= to;
|
||||||
}
|
}
|
||||||
|
|
||||||
init_magic_bitboards(ROOK, RAttacks, RMagics, RMasks, RShifts);
|
Square RDeltas[] = { DELTA_N, DELTA_E, DELTA_S, DELTA_W };
|
||||||
init_magic_bitboards(BISHOP, BAttacks, BMagics, BMasks, BShifts);
|
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++)
|
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||||
{
|
{
|
||||||
BishopPseudoAttacks[s] = bishop_attacks_bb(s, 0);
|
PseudoAttacks[QUEEN][s] = PseudoAttacks[BISHOP][s] = attacks_bb<BISHOP>(s, 0);
|
||||||
RookPseudoAttacks[s] = rook_attacks_bb(s, 0);
|
PseudoAttacks[QUEEN][s] |= PseudoAttacks[ ROOK][s] = attacks_bb< ROOK>(s, 0);
|
||||||
QueenPseudoAttacks[s] = queen_attacks_bb(s, 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||||
if (bit_is_set(QueenPseudoAttacks[s1], s2))
|
if (PseudoAttacks[QUEEN][s1] & s2)
|
||||||
{
|
{
|
||||||
Square delta = (s2 - s1) / square_distance(s1, s2);
|
Square delta = (s2 - s1) / square_distance(s1, s2);
|
||||||
|
|
||||||
for (Square s = s1 + delta; s != s2; s += delta)
|
for (Square s = s1 + delta; s != s2; s += delta)
|
||||||
set_bit(&BetweenBB[s1][s2], s);
|
BetweenBB[s1][s2] |= s;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
Bitboard sliding_attacks(PieceType pt, Square sq, Bitboard occupied) {
|
Bitboard sliding_attack(Square deltas[], Square sq, Bitboard occupied) {
|
||||||
|
|
||||||
Square deltas[][4] = { { DELTA_N, DELTA_E, DELTA_S, DELTA_W },
|
Bitboard attack = 0;
|
||||||
{ DELTA_NE, DELTA_SE, DELTA_SW, DELTA_NW } };
|
|
||||||
Bitboard attacks = 0;
|
|
||||||
Square* delta = (pt == ROOK ? deltas[0] : deltas[1]);
|
|
||||||
|
|
||||||
for (int i = 0; i < 4; i++)
|
for (int i = 0; i < 4; i++)
|
||||||
|
for (Square s = sq + deltas[i];
|
||||||
|
is_ok(s) && square_distance(s, s - deltas[i]) == 1;
|
||||||
|
s += deltas[i])
|
||||||
{
|
{
|
||||||
Square s = sq + delta[i];
|
attack |= s;
|
||||||
|
|
||||||
while (square_is_ok(s) && square_distance(s, s - delta[i]) == 1)
|
if (occupied & s)
|
||||||
{
|
|
||||||
set_bit(&attacks, s);
|
|
||||||
|
|
||||||
if (bit_is_set(occupied, s))
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
s += delta[i];
|
return attack;
|
||||||
}
|
|
||||||
}
|
|
||||||
return attacks;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Bitboard pick_random(Bitboard mask, RKISS& rk, int booster) {
|
Bitboard pick_random(RKISS& rk, int booster) {
|
||||||
|
|
||||||
Bitboard magic;
|
|
||||||
|
|
||||||
// Values s1 and s2 are used to rotate the candidate magic of a
|
// Values s1 and s2 are used to rotate the candidate magic of a
|
||||||
// quantity known to be the optimal to quickly find the magics.
|
// quantity known to be the optimal to quickly find the magics.
|
||||||
int s1 = booster & 63, s2 = (booster >> 6) & 63;
|
int s1 = booster & 63, s2 = (booster >> 6) & 63;
|
||||||
|
|
||||||
while (true)
|
Bitboard m = rk.rand<Bitboard>();
|
||||||
{
|
m = (m >> s1) | (m << (64 - s1));
|
||||||
magic = rk.rand<Bitboard>();
|
m &= rk.rand<Bitboard>();
|
||||||
magic = (magic >> s1) | (magic << (64 - s1));
|
m = (m >> s2) | (m << (64 - s2));
|
||||||
magic &= rk.rand<Bitboard>();
|
return m & rk.rand<Bitboard>();
|
||||||
magic = (magic >> s2) | (magic << (64 - s2));
|
|
||||||
magic &= rk.rand<Bitboard>();
|
|
||||||
|
|
||||||
if (BitCount8Bit[(mask * magic) >> 56] >= 6)
|
|
||||||
return magic;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// init_magic_bitboards() computes all rook and bishop magics at startup.
|
// init_magics() computes all rook and bishop attacks at startup. Magic
|
||||||
// Magic bitboards are used to look up attacks of sliding pieces. As reference
|
// bitboards are used to look up attacks of sliding pieces. As a reference see
|
||||||
// see chessprogramming.wikispaces.com/Magic+Bitboards. In particular, here we
|
// chessprogramming.wikispaces.com/Magic+Bitboards. In particular, here we
|
||||||
// use the so called "fancy" approach.
|
// use the so called "fancy" approach.
|
||||||
|
|
||||||
void init_magic_bitboards(PieceType pt, Bitboard* attacks[], Bitboard magics[],
|
void init_magics(Bitboard table[], Bitboard* attacks[], Bitboard magics[],
|
||||||
Bitboard masks[], int shifts[]) {
|
Bitboard masks[], unsigned shifts[], Square deltas[], Fn index) {
|
||||||
|
|
||||||
int MagicBoosters[][8] = { { 3191, 2184, 1310, 3618, 2091, 1308, 2452, 3996 },
|
int MagicBoosters[][8] = { { 3191, 2184, 1310, 3618, 2091, 1308, 2452, 3996 },
|
||||||
{ 1059, 3608, 605, 3234, 3326, 38, 2029, 3043 } };
|
{ 1059, 3608, 605, 3234, 3326, 38, 2029, 3043 } };
|
||||||
RKISS rk;
|
RKISS rk;
|
||||||
Bitboard occupancy[4096], reference[4096], edges, b;
|
Bitboard occupancy[4096], reference[4096], edges, b;
|
||||||
int i, size, index, booster;
|
int i, size, booster;
|
||||||
|
|
||||||
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
|
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
|
||||||
attacks[SQ_A1] = (pt == ROOK ? RookTable : BishopTable);
|
attacks[SQ_A1] = table;
|
||||||
|
|
||||||
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
for (Square s = SQ_A1; s <= SQ_H8; s++)
|
||||||
{
|
{
|
||||||
@@ -320,15 +297,15 @@ namespace {
|
|||||||
// all the attacks for each possible subset of the mask and so is 2 power
|
// 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
|
// 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.
|
// apply to the 64 or 32 bits word to get the index.
|
||||||
masks[s] = sliding_attacks(pt, s, 0) & ~edges;
|
masks[s] = sliding_attack(deltas, s, 0) & ~edges;
|
||||||
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
|
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
|
||||||
|
|
||||||
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
|
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
|
||||||
// store the corresponding sliding attacks bitboard in reference[].
|
// store the corresponding sliding attack bitboard in reference[].
|
||||||
b = size = 0;
|
b = size = 0;
|
||||||
do {
|
do {
|
||||||
occupancy[size] = b;
|
occupancy[size] = b;
|
||||||
reference[size++] = sliding_attacks(pt, s, b);
|
reference[size++] = sliding_attack(deltas, s, b);
|
||||||
b = (b - masks[s]) & masks[s];
|
b = (b - masks[s]) & masks[s];
|
||||||
} while (b);
|
} while (b);
|
||||||
|
|
||||||
@@ -342,7 +319,9 @@ namespace {
|
|||||||
// Find a magic for square 's' picking up an (almost) random number
|
// Find a magic for square 's' picking up an (almost) random number
|
||||||
// until we find the one that passes the verification test.
|
// until we find the one that passes the verification test.
|
||||||
do {
|
do {
|
||||||
magics[s] = pick_random(masks[s], rk, booster);
|
do magics[s] = pick_random(rk, booster);
|
||||||
|
while (popcount<Max15>((magics[s] * masks[s]) >> 56) < 6);
|
||||||
|
|
||||||
memset(attacks[s], 0, size * sizeof(Bitboard));
|
memset(attacks[s], 0, size * sizeof(Bitboard));
|
||||||
|
|
||||||
// A good magic must map every possible occupancy to an index that
|
// A good magic must map every possible occupancy to an index that
|
||||||
@@ -351,14 +330,14 @@ namespace {
|
|||||||
// effect of verifying the magic.
|
// effect of verifying the magic.
|
||||||
for (i = 0; i < size; i++)
|
for (i = 0; i < size; i++)
|
||||||
{
|
{
|
||||||
index = (pt == ROOK ? rook_index(s, occupancy[i])
|
Bitboard& attack = attacks[s][index(s, occupancy[i])];
|
||||||
: bishop_index(s, occupancy[i]));
|
|
||||||
|
|
||||||
if (!attacks[s][index])
|
if (attack && attack != reference[i])
|
||||||
attacks[s][index] = reference[i];
|
|
||||||
|
|
||||||
else if (attacks[s][index] != reference[i])
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
assert(reference[i] != 0);
|
||||||
|
|
||||||
|
attack = reference[i];
|
||||||
}
|
}
|
||||||
} while (i != size);
|
} while (i != size);
|
||||||
}
|
}
|
||||||
|
|||||||
+150
-131
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -23,64 +23,76 @@
|
|||||||
|
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
extern Bitboard FileBB[8];
|
namespace Bitboards {
|
||||||
extern Bitboard NeighboringFilesBB[8];
|
|
||||||
extern Bitboard ThisAndNeighboringFilesBB[8];
|
|
||||||
extern Bitboard RankBB[8];
|
|
||||||
extern Bitboard InFrontBB[2][8];
|
|
||||||
|
|
||||||
extern Bitboard SetMaskBB[65];
|
void init();
|
||||||
extern Bitboard ClearMaskBB[65];
|
void print(Bitboard b);
|
||||||
|
|
||||||
extern Bitboard StepAttacksBB[16][64];
|
|
||||||
extern Bitboard BetweenBB[64][64];
|
|
||||||
|
|
||||||
extern Bitboard SquaresInFrontMask[2][64];
|
|
||||||
extern Bitboard PassedPawnMask[2][64];
|
|
||||||
extern Bitboard AttackSpanMask[2][64];
|
|
||||||
|
|
||||||
extern uint64_t RMagics[64];
|
|
||||||
extern int RShifts[64];
|
|
||||||
extern Bitboard RMasks[64];
|
|
||||||
extern Bitboard* RAttacks[64];
|
|
||||||
|
|
||||||
extern uint64_t BMagics[64];
|
|
||||||
extern int BShifts[64];
|
|
||||||
extern Bitboard BMasks[64];
|
|
||||||
extern Bitboard* BAttacks[64];
|
|
||||||
|
|
||||||
extern Bitboard BishopPseudoAttacks[64];
|
|
||||||
extern Bitboard RookPseudoAttacks[64];
|
|
||||||
extern Bitboard QueenPseudoAttacks[64];
|
|
||||||
|
|
||||||
extern uint8_t BitCount8Bit[256];
|
|
||||||
|
|
||||||
|
|
||||||
/// Functions 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 void set_bit(Bitboard* b, Square s) {
|
namespace Bitbases {
|
||||||
*b |= SetMaskBB[s];
|
|
||||||
|
void init_kpk();
|
||||||
|
bool probe_kpk(Square wksq, Square wpsq, Square bksq, Color us);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void clear_bit(Bitboard* b, Square s) {
|
CACHE_LINE_ALIGNMENT
|
||||||
*b &= ClearMaskBB[s];
|
|
||||||
|
extern Bitboard RMasks[SQUARE_NB];
|
||||||
|
extern Bitboard RMagics[SQUARE_NB];
|
||||||
|
extern Bitboard* RAttacks[SQUARE_NB];
|
||||||
|
extern unsigned RShifts[SQUARE_NB];
|
||||||
|
|
||||||
|
extern Bitboard BMasks[SQUARE_NB];
|
||||||
|
extern Bitboard BMagics[SQUARE_NB];
|
||||||
|
extern Bitboard* BAttacks[SQUARE_NB];
|
||||||
|
extern unsigned BShifts[SQUARE_NB];
|
||||||
|
|
||||||
|
extern Bitboard SquareBB[SQUARE_NB];
|
||||||
|
extern Bitboard FileBB[FILE_NB];
|
||||||
|
extern Bitboard RankBB[RANK_NB];
|
||||||
|
extern Bitboard AdjacentFilesBB[FILE_NB];
|
||||||
|
extern Bitboard ThisAndAdjacentFilesBB[FILE_NB];
|
||||||
|
extern Bitboard InFrontBB[COLOR_NB][RANK_NB];
|
||||||
|
extern Bitboard StepAttacksBB[PIECE_NB][SQUARE_NB];
|
||||||
|
extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
|
||||||
|
extern Bitboard DistanceRingsBB[SQUARE_NB][8];
|
||||||
|
extern Bitboard ForwardBB[COLOR_NB][SQUARE_NB];
|
||||||
|
extern Bitboard PassedPawnMask[COLOR_NB][SQUARE_NB];
|
||||||
|
extern Bitboard AttackSpanMask[COLOR_NB][SQUARE_NB];
|
||||||
|
extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
|
||||||
|
|
||||||
|
const Bitboard BlackSquares = 0xAA55AA55AA55AA55ULL;
|
||||||
|
|
||||||
|
/// 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 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];
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
/// more_than_one() returns true if in 'b' there is more than one bit set
|
||||||
/// then calling a sequence of clear_bit() + set_bit()
|
|
||||||
|
|
||||||
inline Bitboard make_move_bb(Square from, Square to) {
|
inline bool more_than_one(Bitboard b) {
|
||||||
return SetMaskBB[from] | SetMaskBB[to];
|
return b & (b - 1);
|
||||||
}
|
|
||||||
|
|
||||||
inline void do_move_bb(Bitboard* b, Bitboard move_bb) {
|
|
||||||
*b ^= move_bb;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -104,19 +116,19 @@ inline Bitboard file_bb(Square s) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// neighboring_files_bb takes a file as input and returns a bitboard representing
|
/// adjacent_files_bb takes a file as input and returns a bitboard representing
|
||||||
/// all squares on the neighboring files.
|
/// all squares on the adjacent files.
|
||||||
|
|
||||||
inline Bitboard neighboring_files_bb(File f) {
|
inline Bitboard adjacent_files_bb(File f) {
|
||||||
return NeighboringFilesBB[f];
|
return AdjacentFilesBB[f];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// this_and_neighboring_files_bb takes a file as input and returns a bitboard
|
/// this_and_adjacent_files_bb takes a file as input and returns a bitboard
|
||||||
/// representing all squares on the given and neighboring files.
|
/// representing all squares on the given and adjacent files.
|
||||||
|
|
||||||
inline Bitboard this_and_neighboring_files_bb(File f) {
|
inline Bitboard this_and_adjacent_files_bb(File f) {
|
||||||
return ThisAndNeighboringFilesBB[f];
|
return ThisAndAdjacentFilesBB[f];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -135,71 +147,30 @@ inline Bitboard in_front_bb(Color c, Square s) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Functions for computing sliding attack bitboards. rook_attacks_bb(),
|
/// between_bb returns a bitboard representing all squares between two squares.
|
||||||
/// bishop_attacks_bb() and queen_attacks_bb() all take a square and a
|
/// For instance, between_bb(SQ_C4, SQ_F7) returns a bitboard with the bits for
|
||||||
/// bitboard of occupied squares as input, and return a bitboard representing
|
/// square d5 and e6 set. If s1 and s2 are not on the same line, file or diagonal,
|
||||||
/// all squares attacked by a rook, bishop or queen on the given square.
|
/// 0 is returned.
|
||||||
|
|
||||||
#if defined(IS_64BIT)
|
inline Bitboard between_bb(Square s1, Square s2) {
|
||||||
|
|
||||||
FORCE_INLINE unsigned rook_index(Square s, Bitboard occ) {
|
|
||||||
return unsigned(((occ & RMasks[s]) * RMagics[s]) >> RShifts[s]);
|
|
||||||
}
|
|
||||||
|
|
||||||
FORCE_INLINE unsigned bishop_index(Square s, Bitboard occ) {
|
|
||||||
return unsigned(((occ & BMasks[s]) * BMagics[s]) >> BShifts[s]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#else // if !defined(IS_64BIT)
|
|
||||||
|
|
||||||
FORCE_INLINE unsigned rook_index(Square s, Bitboard occ) {
|
|
||||||
Bitboard b = occ & RMasks[s];
|
|
||||||
return unsigned(int(b) * int(RMagics[s]) ^ int(b >> 32) * int(RMagics[s] >> 32)) >> RShifts[s];
|
|
||||||
}
|
|
||||||
|
|
||||||
FORCE_INLINE unsigned bishop_index(Square s, Bitboard occ) {
|
|
||||||
Bitboard b = occ & BMasks[s];
|
|
||||||
return unsigned(int(b) * int(BMagics[s]) ^ int(b >> 32) * int(BMagics[s] >> 32)) >> BShifts[s];
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
inline Bitboard rook_attacks_bb(Square s, Bitboard occ) {
|
|
||||||
return RAttacks[s][rook_index(s, occ)];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard bishop_attacks_bb(Square s, Bitboard occ) {
|
|
||||||
return BAttacks[s][bishop_index(s, occ)];
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
|
||||||
return BetweenBB[s1][s2];
|
return BetweenBB[s1][s2];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// squares_in_front_of takes a color and a square as input, and returns a
|
/// forward_bb takes a color and a square as input, and returns a bitboard
|
||||||
/// bitboard representing all squares along the line in front of the square,
|
/// representing all squares along the line in front of the square, from the
|
||||||
/// from the point of view of the given color. Definition of the table is:
|
/// point of view of the given color. Definition of the table is:
|
||||||
/// SquaresInFrontOf[c][s] = in_front_bb(c, s) & file_bb(s)
|
/// ForwardBB[c][s] = in_front_bb(c, s) & file_bb(s)
|
||||||
|
|
||||||
inline Bitboard squares_in_front_of(Color c, Square s) {
|
inline Bitboard forward_bb(Color c, Square s) {
|
||||||
return SquaresInFrontMask[c][s];
|
return ForwardBB[c][s];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// passed_pawn_mask takes a color and a square as input, and returns a
|
/// 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
|
/// 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:
|
/// 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) {
|
inline Bitboard passed_pawn_mask(Color c, Square s) {
|
||||||
return PassedPawnMask[c][s];
|
return PassedPawnMask[c][s];
|
||||||
@@ -209,7 +180,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
|
/// 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
|
/// 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:
|
/// 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) {
|
inline Bitboard attack_span_mask(Color c, Square s) {
|
||||||
return AttackSpanMask[c][s];
|
return AttackSpanMask[c][s];
|
||||||
@@ -221,7 +192,7 @@ inline Bitboard attack_span_mask(Color c, Square s) {
|
|||||||
|
|
||||||
inline bool squares_aligned(Square s1, Square s2, Square s3) {
|
inline bool squares_aligned(Square s1, Square s2, Square s3) {
|
||||||
return (BetweenBB[s1][s2] | BetweenBB[s1][s3] | BetweenBB[s2][s3])
|
return (BetweenBB[s1][s2] | BetweenBB[s1][s3] | BetweenBB[s2][s3])
|
||||||
& ( SetMaskBB[s1] | SetMaskBB[s2] | SetMaskBB[s3]);
|
& ( SquareBB[s1] | SquareBB[s2] | SquareBB[s3]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -229,48 +200,96 @@ inline bool squares_aligned(Square s1, Square s2, Square s3) {
|
|||||||
/// the same color of the given square.
|
/// the same color of the given square.
|
||||||
|
|
||||||
inline Bitboard same_color_squares(Square s) {
|
inline Bitboard same_color_squares(Square s) {
|
||||||
return bit_is_set(0xAA55AA55AA55AA55ULL, s) ? 0xAA55AA55AA55AA55ULL
|
return BlackSquares & s ? BlackSquares : ~BlackSquares;
|
||||||
: ~0xAA55AA55AA55AA55ULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
/// Functions for computing sliding attack bitboards. Function attacks_bb() takes
|
||||||
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
/// a square and a bitboard of occupied squares as input, and returns a bitboard
|
||||||
/// nonzero 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(USE_BSFQ)
|
||||||
|
|
||||||
# if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
|
# if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
|
||||||
|
|
||||||
FORCE_INLINE Square first_1(Bitboard b) {
|
FORCE_INLINE Square lsb(Bitboard b) {
|
||||||
unsigned long index;
|
unsigned long index;
|
||||||
_BitScanForward64(&index, b);
|
_BitScanForward64(&index, b);
|
||||||
return (Square) index;
|
return (Square) index;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FORCE_INLINE Square msb(Bitboard b) {
|
||||||
|
unsigned long index;
|
||||||
|
_BitScanReverse64(&index, b);
|
||||||
|
return (Square) index;
|
||||||
|
}
|
||||||
|
|
||||||
|
# elif defined(__arm__)
|
||||||
|
|
||||||
|
FORCE_INLINE int lsb32(uint32_t v) {
|
||||||
|
__asm__("rbit %0, %1" : "=r"(v) : "r"(v));
|
||||||
|
return __builtin_clz(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
FORCE_INLINE Square msb(Bitboard b) {
|
||||||
|
return (Square) (63 - __builtin_clzll(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
FORCE_INLINE Square lsb(Bitboard b) {
|
||||||
|
return (Square) (uint32_t(b) ? lsb32(uint32_t(b)) : 32 + lsb32(uint32_t(b >> 32)));
|
||||||
|
}
|
||||||
|
|
||||||
# else
|
# else
|
||||||
|
|
||||||
FORCE_INLINE Square first_1(Bitboard b) { // Assembly code by Heinz van Saanen
|
FORCE_INLINE Square lsb(Bitboard b) { // Assembly code by Heinz van Saanen
|
||||||
Bitboard dummy;
|
Bitboard index;
|
||||||
__asm__("bsfq %1, %0": "=r"(dummy): "rm"(b) );
|
__asm__("bsfq %1, %0": "=r"(index): "rm"(b) );
|
||||||
return (Square) dummy;
|
return (Square) index;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FORCE_INLINE Square msb(Bitboard b) {
|
||||||
|
Bitboard index;
|
||||||
|
__asm__("bsrq %1, %0": "=r"(index): "rm"(b) );
|
||||||
|
return (Square) index;
|
||||||
|
}
|
||||||
|
|
||||||
# endif
|
# endif
|
||||||
|
|
||||||
FORCE_INLINE Square pop_1st_bit(Bitboard* b) {
|
FORCE_INLINE Square pop_lsb(Bitboard* b) {
|
||||||
const Square s = first_1(*b);
|
const Square s = lsb(*b);
|
||||||
*b &= ~(1ULL<<s);
|
*b &= *b - 1;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
#else // if !defined(USE_BSFQ)
|
#else // if !defined(USE_BSFQ)
|
||||||
|
|
||||||
extern Square first_1(Bitboard b);
|
extern Square msb(Bitboard b);
|
||||||
extern Square pop_1st_bit(Bitboard* b);
|
extern Square lsb(Bitboard b);
|
||||||
|
extern Square pop_lsb(Bitboard* b);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
extern void print_bitboard(Bitboard b);
|
|
||||||
extern void bitboards_init();
|
|
||||||
|
|
||||||
#endif // !defined(BITBOARD_H_INCLUDED)
|
#endif // !defined(BITBOARD_H_INCLUDED)
|
||||||
|
|||||||
+12
-19
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -33,8 +33,8 @@ enum BitCountType {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// Determine at compile time the best popcount<> specialization according if
|
/// 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
|
/// platform is 32 or 64 bits, to the maximum number of nonzero bits to count
|
||||||
/// use hardware popcnt instruction when available.
|
/// and if hardware popcnt instruction is available.
|
||||||
const BitCountType Full = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64 : CNT_32;
|
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;
|
const BitCountType Max15 = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64_MAX15 : CNT_32_MAX15;
|
||||||
|
|
||||||
@@ -44,19 +44,17 @@ template<BitCountType> inline int popcount(Bitboard);
|
|||||||
|
|
||||||
template<>
|
template<>
|
||||||
inline int popcount<CNT_64>(Bitboard b) {
|
inline int popcount<CNT_64>(Bitboard b) {
|
||||||
b -= ((b>>1) & 0x5555555555555555ULL);
|
b -= (b >> 1) & 0x5555555555555555ULL;
|
||||||
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||||
b = ((b >> 4) + b) & 0x0F0F0F0F0F0F0F0FULL;
|
b = ((b >> 4) + b) & 0x0F0F0F0F0F0F0F0FULL;
|
||||||
b *= 0x0101010101010101ULL;
|
return (b * 0x0101010101010101ULL) >> 56;
|
||||||
return int(b >> 56);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template<>
|
||||||
inline int popcount<CNT_64_MAX15>(Bitboard b) {
|
inline int popcount<CNT_64_MAX15>(Bitboard b) {
|
||||||
b -= (b >> 1) & 0x5555555555555555ULL;
|
b -= (b >> 1) & 0x5555555555555555ULL;
|
||||||
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
b = ((b >> 2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||||
b *= 0x1111111111111111ULL;
|
return (b * 0x1111111111111111ULL) >> 60;
|
||||||
return int(b >> 60);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template<>
|
||||||
@@ -66,10 +64,8 @@ inline int popcount<CNT_32>(Bitboard b) {
|
|||||||
w -= (w >> 1) & 0x55555555;
|
w -= (w >> 1) & 0x55555555;
|
||||||
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||||
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||||
v = ((v >> 4) + v) & 0x0F0F0F0F; // 0-8 in 8 bits
|
v = ((v >> 4) + v + (w >> 4) + w) & 0x0F0F0F0F;
|
||||||
v += (((w >> 4) + w) & 0x0F0F0F0F); // 0-16 in 8 bits
|
return (v * 0x01010101) >> 24;
|
||||||
v *= 0x01010101; // mul is fast on amd procs
|
|
||||||
return int(v >> 24);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template<>
|
||||||
@@ -79,9 +75,7 @@ inline int popcount<CNT_32_MAX15>(Bitboard b) {
|
|||||||
w -= (w >> 1) & 0x55555555;
|
w -= (w >> 1) & 0x55555555;
|
||||||
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||||
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||||
v += w; // 0-8 in 4 bits
|
return ((v + w) * 0x11111111) >> 28;
|
||||||
v *= 0x11111111;
|
|
||||||
return int(v >> 28);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<>
|
template<>
|
||||||
@@ -90,7 +84,7 @@ inline int popcount<CNT_HW_POPCNT>(Bitboard b) {
|
|||||||
#if !defined(USE_POPCNT)
|
#if !defined(USE_POPCNT)
|
||||||
|
|
||||||
assert(false);
|
assert(false);
|
||||||
return int(b != 0); // Avoid 'b not used' warning
|
return b != 0; // Avoid 'b not used' warning
|
||||||
|
|
||||||
#elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
|
#elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
|
||||||
|
|
||||||
@@ -102,9 +96,8 @@ inline int popcount<CNT_HW_POPCNT>(Bitboard b) {
|
|||||||
|
|
||||||
#else
|
#else
|
||||||
|
|
||||||
unsigned long ret;
|
__asm__("popcnt %1, %0" : "=r" (b) : "r" (b));
|
||||||
__asm__("popcnt %1, %0" : "=r" (ret) : "r" (b));
|
return b;
|
||||||
return ret;
|
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|||||||
+117
-169
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -17,13 +17,13 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
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
|
The code in this file is based on the opening book code in PolyGlot
|
||||||
by Fabien Letouzey. PolyGlot is available under the GNU General
|
by Fabien Letouzey. PolyGlot is available under the GNU General
|
||||||
Public License, and can be downloaded from http://wbec-ridderkerk.nl
|
Public License, and can be downloaded from http://wbec-ridderkerk.nl
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
@@ -35,8 +35,26 @@ using namespace std;
|
|||||||
|
|
||||||
namespace {
|
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 Entry {
|
||||||
|
uint64_t key;
|
||||||
|
uint16_t move;
|
||||||
|
uint16_t count;
|
||||||
|
uint32_t learn;
|
||||||
|
};
|
||||||
|
|
||||||
// Random numbers from PolyGlot, used to compute book hash keys
|
// Random numbers from PolyGlot, used to compute book hash keys
|
||||||
const Key PolyGlotRandoms[781] = {
|
const union {
|
||||||
|
Key PolyGlotRandoms[781];
|
||||||
|
struct {
|
||||||
|
Key psq[12][64]; // [piece][square]
|
||||||
|
Key castle[4]; // [castle right]
|
||||||
|
Key enpassant[8]; // [file]
|
||||||
|
Key turn;
|
||||||
|
} Zobrist;
|
||||||
|
} PG = {{
|
||||||
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
|
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
|
||||||
0x9C15F73E62A76AE2ULL, 0x75834465489C0C89ULL, 0x3290AC3A203001BFULL,
|
0x9C15F73E62A76AE2ULL, 0x75834465489C0C89ULL, 0x3290AC3A203001BFULL,
|
||||||
0x0FBBAD1F61042279ULL, 0xE83A908FF2FB60CAULL, 0x0D7E765D58755C10ULL,
|
0x0FBBAD1F61042279ULL, 0xE83A908FF2FB60CAULL, 0x0D7E765D58755C10ULL,
|
||||||
@@ -298,233 +316,163 @@ namespace {
|
|||||||
0x003A93D8B2806962ULL, 0x1C99DED33CB890A1ULL, 0xCF3145DE0ADD4289ULL,
|
0x003A93D8B2806962ULL, 0x1C99DED33CB890A1ULL, 0xCF3145DE0ADD4289ULL,
|
||||||
0xD0E4427A5514FB72ULL, 0x77C621CC9FB3A483ULL, 0x67A34DAC4356550BULL,
|
0xD0E4427A5514FB72ULL, 0x77C621CC9FB3A483ULL, 0x67A34DAC4356550BULL,
|
||||||
0xF8D626AAAF278509ULL
|
0xF8D626AAAF278509ULL
|
||||||
};
|
}};
|
||||||
|
|
||||||
// Offsets to the PolyGlotRandoms[] array of zobrist keys
|
// polyglot_key() returns the PolyGlot hash key of the given position
|
||||||
const Key* ZobPiece = PolyGlotRandoms + 0;
|
Key polyglot_key(const Position& pos) {
|
||||||
const Key* ZobCastle = PolyGlotRandoms + 768;
|
|
||||||
const Key* ZobEnPassant = PolyGlotRandoms + 772;
|
|
||||||
const Key* ZobTurn = PolyGlotRandoms + 780;
|
|
||||||
|
|
||||||
// Piece offset is calculated as 64 * (PolyPiece ^ 1) where
|
Key key = 0;
|
||||||
// PolyPiece is: BP = 0, WP = 1, BN = 2, WN = 3 ... BK = 10, WK = 11
|
Bitboard b = pos.pieces();
|
||||||
const int PieceOfs[] = { 0, 64, 192, 320, 448, 576, 704, 0,
|
|
||||||
0, 0, 128, 256, 384, 512, 640 };
|
|
||||||
|
|
||||||
// book_key() builds up a PolyGlot hash key out of a position
|
|
||||||
uint64_t book_key(const Position& pos) {
|
|
||||||
|
|
||||||
uint64_t result = 0;
|
|
||||||
Bitboard b = pos.occupied_squares();
|
|
||||||
|
|
||||||
while (b)
|
while (b)
|
||||||
{
|
{
|
||||||
Square s = pop_1st_bit(&b);
|
Square s = pop_lsb(&b);
|
||||||
result ^= ZobPiece[PieceOfs[pos.piece_on(s)] + s];
|
Piece p = pos.piece_on(s);
|
||||||
|
|
||||||
|
// PolyGlot pieces are: BP = 0, WP = 1, BN = 2, ... BK = 10, WK = 11
|
||||||
|
key ^= PG.Zobrist.psq[2 * (type_of(p) - 1) + (color_of(p) == WHITE)][s];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pos.can_castle(WHITE_OO))
|
b = pos.can_castle(ALL_CASTLES);
|
||||||
result ^= ZobCastle[0];
|
|
||||||
|
|
||||||
if (pos.can_castle(WHITE_OOO))
|
while (b)
|
||||||
result ^= ZobCastle[1];
|
key ^= PG.Zobrist.castle[pop_lsb(&b)];
|
||||||
|
|
||||||
if (pos.can_castle(BLACK_OO))
|
|
||||||
result ^= ZobCastle[2];
|
|
||||||
|
|
||||||
if (pos.can_castle(BLACK_OOO))
|
|
||||||
result ^= ZobCastle[3];
|
|
||||||
|
|
||||||
if (pos.ep_square() != SQ_NONE)
|
if (pos.ep_square() != SQ_NONE)
|
||||||
result ^= ZobEnPassant[file_of(pos.ep_square())];
|
key ^= PG.Zobrist.enpassant[file_of(pos.ep_square())];
|
||||||
|
|
||||||
if (pos.side_to_move() == WHITE)
|
if (pos.side_to_move() == WHITE)
|
||||||
result ^= ZobTurn[0];
|
key ^= PG.Zobrist.turn;
|
||||||
|
|
||||||
return result;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
PolyglotBook::PolyglotBook() : rkiss(Time::now() % 10000) {}
|
||||||
|
|
||||||
|
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>>(Entry& e) {
|
||||||
|
return *this >> e.key >> e.move >> e.count >> e.learn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Book c'tor. Make random number generation less deterministic, for book moves
|
/// open() tries to open a book file with the given name after closing any
|
||||||
Book::Book() : bookSize(0) {
|
/// exsisting one.
|
||||||
|
|
||||||
for (int i = abs(system_time() % 10000); i > 0; i--)
|
bool PolyglotBook::open(const char* fName) {
|
||||||
RKiss.rand<unsigned>();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (is_open()) // Cannot close an already closed file
|
||||||
/// Book destructor. Be sure file is closed before we leave.
|
|
||||||
|
|
||||||
Book::~Book() {
|
|
||||||
|
|
||||||
close();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Book::close() closes the file only if it is open, otherwise the call fails
|
|
||||||
/// and the failbit internal state flag is set.
|
|
||||||
|
|
||||||
void Book::close() {
|
|
||||||
|
|
||||||
if (bookFile.is_open())
|
|
||||||
bookFile.close();
|
|
||||||
|
|
||||||
bookName = "";
|
|
||||||
bookSize = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Book::open() opens a book file with a given name
|
|
||||||
|
|
||||||
void Book::open(const string& fileName) {
|
|
||||||
|
|
||||||
// Close old file before opening the new
|
|
||||||
close();
|
close();
|
||||||
|
|
||||||
bookFile.open(fileName.c_str(), ifstream::in | ifstream::binary |ios::ate);
|
ifstream::open(fName, ifstream::in | ifstream::binary);
|
||||||
|
|
||||||
// Silently return when asked to open a non-exsistent file
|
fileName = is_open() ? fName : "";
|
||||||
if (!bookFile.is_open())
|
ifstream::clear(); // Reset any error flag to allow retry ifstream::open()
|
||||||
return;
|
return !fileName.empty();
|
||||||
|
|
||||||
// Get the book size in number of entries, we are already at the file 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::probe() gets a book move for a given position. Returns MOVE_NONE
|
/// probe() tries to find a book move for the given position. If no move is
|
||||||
/// if no book move is found. If findBest is true then returns always the
|
/// found returns MOVE_NONE. If pickBest is true returns always the highest
|
||||||
/// highest rated move otherwise chooses randomly based on the move score.
|
/// rated move, otherwise randomly chooses one, based on the move score.
|
||||||
|
|
||||||
Move Book::probe(const Position& pos, bool findBest) {
|
Move PolyglotBook::probe(const Position& pos, const string& fName, bool pickBest) {
|
||||||
|
|
||||||
if (!bookSize || !bookFile.is_open())
|
if (fileName != fName && !open(fName.c_str()))
|
||||||
return MOVE_NONE;
|
return MOVE_NONE;
|
||||||
|
|
||||||
BookEntry entry;
|
Entry e;
|
||||||
unsigned scoresSum = 0, bestScore = 0, bookMove = 0;
|
uint16_t best = 0;
|
||||||
uint64_t key = book_key(pos);
|
unsigned sum = 0;
|
||||||
int idx = first_entry(key) - 1;
|
Move move = MOVE_NONE;
|
||||||
|
Key key = polyglot_key(pos);
|
||||||
|
|
||||||
// Choose a book move among the possible moves for the given position
|
seekg(find_first(key) * sizeof(Entry), ios_base::beg);
|
||||||
while (++idx < bookSize && (entry = read_entry(idx), entry.key == key))
|
|
||||||
|
while (*this >> e, e.key == key && good())
|
||||||
{
|
{
|
||||||
scoresSum += entry.count;
|
best = max(best, e.count);
|
||||||
|
sum += e.count;
|
||||||
|
|
||||||
// Choose book move according to its score. If a move has a very
|
// 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
|
// high score it has higher probability to be choosen than a move
|
||||||
// with lower score. Note that first entry is always chosen.
|
// with lower score. Note that first entry is always chosen.
|
||||||
if ( RKiss.rand<unsigned>() % scoresSum < entry.count
|
if ( (sum && rkiss.rand<unsigned>() % sum < e.count)
|
||||||
|| (findBest && entry.count > bestScore))
|
|| (pickBest && e.count == best))
|
||||||
bookMove = entry.move;
|
move = Move(e.move);
|
||||||
|
|
||||||
if (entry.count > bestScore)
|
|
||||||
bestScore = entry.count;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!bookMove)
|
if (!move)
|
||||||
return MOVE_NONE;
|
return MOVE_NONE;
|
||||||
|
|
||||||
// A PolyGlot book move is encoded as follows:
|
// A PolyGlot book move is encoded as follows:
|
||||||
//
|
//
|
||||||
// bit 0- 5: destination square (from 0 to 63)
|
// bit 0- 5: destination square (from 0 to 63)
|
||||||
// bit 6-11: origin 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
|
// Castling moves follow "king captures rook" representation. So in case book
|
||||||
// book move is a promotion we have to convert to our representation, in
|
// move is a promotion we have to convert to our representation, in all the
|
||||||
// all other cases we can directly compare with a Move after having
|
// other cases we can directly compare with a Move after having masked out
|
||||||
// masked out special Move's flags that are not supported by PolyGlot.
|
// the special Move's flags (bit 14-15) that are not supported by PolyGlot.
|
||||||
int promotion = (bookMove >> 12) & 7;
|
int pt = (move >> 12) & 7;
|
||||||
|
if (pt)
|
||||||
|
move = make<PROMOTION>(from_sq(move), to_sq(move), PieceType(pt + 1));
|
||||||
|
|
||||||
if (promotion)
|
// Add 'special move' flags and verify it is legal
|
||||||
bookMove = make_promotion_move(move_from(Move(bookMove)),
|
for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
|
||||||
move_to(Move(bookMove)),
|
if (move == (ml.move() ^ type_of(ml.move())))
|
||||||
PieceType(promotion + 1));
|
|
||||||
// Verify the book move is legal
|
|
||||||
for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
|
|
||||||
if (unsigned(ml.move() & ~(3 << 14)) == bookMove) // Mask out special flags
|
|
||||||
return ml.move();
|
return ml.move();
|
||||||
|
|
||||||
return MOVE_NONE;
|
return MOVE_NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Book::first_entry() takes a book key as input, and does a binary search
|
/// find_first() takes a book key as input, and does a binary search through
|
||||||
/// through the book file for the given key. The index to the first (leftmost)
|
/// the book file for the given key. Returns the index of the leftmost book
|
||||||
/// book entry with the same key as the input is returned. When the key is not
|
/// entry with the same key as the input.
|
||||||
/// found in the book file, bookSize is returned.
|
|
||||||
|
|
||||||
int Book::first_entry(uint64_t key) {
|
size_t PolyglotBook::find_first(Key key) {
|
||||||
|
|
||||||
int left, right, mid;
|
seekg(0, ios::end); // Move pointer to end, so tellg() gets file's size
|
||||||
|
|
||||||
// Binary search (finds the leftmost entry with given key)
|
size_t low = 0, mid, high = (size_t)tellg() / sizeof(Entry) - 1;
|
||||||
left = 0;
|
Entry e;
|
||||||
right = bookSize - 1;
|
|
||||||
|
|
||||||
assert(left <= right);
|
assert(low <= high);
|
||||||
|
|
||||||
while (left < right)
|
while (low < high && good())
|
||||||
{
|
{
|
||||||
mid = (left + right) / 2;
|
mid = (low + high) / 2;
|
||||||
|
|
||||||
assert(mid >= left && mid < right);
|
assert(mid >= low && mid < high);
|
||||||
|
|
||||||
if (key <= read_entry(mid).key)
|
seekg(mid * sizeof(Entry), ios_base::beg);
|
||||||
right = mid;
|
*this >> e;
|
||||||
|
|
||||||
|
if (key <= e.key)
|
||||||
|
high = mid;
|
||||||
else
|
else
|
||||||
left = mid + 1;
|
low = mid + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
assert(left == right);
|
assert(low == high);
|
||||||
|
|
||||||
return read_entry(left).key == key ? left : bookSize;
|
return low;
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Book::operator>>() reads sizeof(T) chars from the file's binary byte
|
|
||||||
/// stream and converts them in a number of type T.
|
|
||||||
template<typename T>
|
|
||||||
Book& Book::operator>>(T& n) {
|
|
||||||
|
|
||||||
n = 0;
|
|
||||||
|
|
||||||
for (size_t i = 0; i < sizeof(T); i++)
|
|
||||||
n = T((n << 8) + bookFile.get());
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// 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());
|
|
||||||
|
|
||||||
BookEntry e;
|
|
||||||
|
|
||||||
bookFile.seekg(idx * sizeof(BookEntry), ios_base::beg);
|
|
||||||
|
|
||||||
*this >> e.key >> e.move >> e.count >> e.learn;
|
|
||||||
|
|
||||||
if (!bookFile.good())
|
|
||||||
{
|
|
||||||
cerr << "Failed to read book entry at index " << idx << endl;
|
|
||||||
exit(EXIT_FAILURE);
|
|
||||||
}
|
|
||||||
return e;
|
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-26
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -26,36 +26,20 @@
|
|||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "rkiss.h"
|
#include "rkiss.h"
|
||||||
|
|
||||||
|
class PolyglotBook : private std::ifstream {
|
||||||
/// 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 {
|
|
||||||
public:
|
public:
|
||||||
Book();
|
PolyglotBook();
|
||||||
~Book();
|
~PolyglotBook();
|
||||||
void open(const std::string& fileName);
|
Move probe(const Position& pos, const std::string& fName, bool pickBest);
|
||||||
void close();
|
|
||||||
Move probe(const Position& pos, bool findBestMove);
|
|
||||||
const std::string name() const { return bookName; }
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
template<typename T> Book& operator>>(T& n);
|
template<typename T> PolyglotBook& operator>>(T& n);
|
||||||
|
|
||||||
BookEntry read_entry(int idx);
|
bool open(const char* fName);
|
||||||
int first_entry(uint64_t key);
|
size_t find_first(Key key);
|
||||||
|
|
||||||
RKISS RKiss;
|
RKISS rkiss;
|
||||||
std::ifstream bookFile;
|
std::string fileName;
|
||||||
std::string bookName;
|
|
||||||
int bookSize;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // !defined(BOOK_H_INCLUDED)
|
#endif // !defined(BOOK_H_INCLUDED)
|
||||||
|
|||||||
+165
-89
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,19 +20,18 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
|
||||||
|
#include "bitboard.h"
|
||||||
#include "bitcount.h"
|
#include "bitcount.h"
|
||||||
#include "endgame.h"
|
#include "endgame.h"
|
||||||
#include "pawns.h"
|
#include "movegen.h"
|
||||||
|
|
||||||
using std::string;
|
using std::string;
|
||||||
|
|
||||||
extern uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm);
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
// Table used to drive the defending king towards the edge of the board
|
// Table used to drive the defending king towards the edge of the board
|
||||||
// in KX vs K and KQ vs KR endgames.
|
// in KX vs K and KQ vs KR endgames.
|
||||||
const int MateTable[64] = {
|
const int MateTable[SQUARE_NB] = {
|
||||||
100, 90, 80, 70, 70, 80, 90, 100,
|
100, 90, 80, 70, 70, 80, 90, 100,
|
||||||
90, 70, 60, 50, 50, 60, 70, 90,
|
90, 70, 60, 50, 50, 60, 70, 90,
|
||||||
80, 60, 40, 30, 30, 40, 60, 80,
|
80, 60, 40, 30, 30, 40, 60, 80,
|
||||||
@@ -45,7 +44,7 @@ namespace {
|
|||||||
|
|
||||||
// Table used to drive the defending king towards a corner square of the
|
// Table used to drive the defending king towards a corner square of the
|
||||||
// right color in KBN vs K endgames.
|
// right color in KBN vs K endgames.
|
||||||
const int KBNKMateTable[64] = {
|
const int KBNKMateTable[SQUARE_NB] = {
|
||||||
200, 190, 180, 170, 160, 150, 140, 130,
|
200, 190, 180, 170, 160, 150, 140, 130,
|
||||||
190, 180, 170, 160, 150, 140, 130, 140,
|
190, 180, 170, 160, 150, 140, 130, 140,
|
||||||
180, 170, 155, 140, 140, 125, 140, 150,
|
180, 170, 155, 140, 140, 125, 140, 150,
|
||||||
@@ -72,12 +71,12 @@ namespace {
|
|||||||
string sides[] = { code.substr(code.find('K', 1)), // Weaker
|
string sides[] = { code.substr(code.find('K', 1)), // Weaker
|
||||||
code.substr(0, code.find('K', 1)) }; // Stronger
|
code.substr(0, code.find('K', 1)) }; // Stronger
|
||||||
|
|
||||||
transform(sides[c].begin(), sides[c].end(), sides[c].begin(), tolower);
|
std::transform(sides[c].begin(), sides[c].end(), sides[c].begin(), tolower);
|
||||||
|
|
||||||
string fen = sides[0] + char('0' + int(8 - code.length()))
|
string fen = sides[0] + char('0' + int(8 - code.length()))
|
||||||
+ sides[1] + "/8/8/8/8/8/8/8 w - - 0 10";
|
+ sides[1] + "/8/8/8/8/8/8/8 w - - 0 10";
|
||||||
|
|
||||||
return Position(fen, false, 0).material_key();
|
return Position(fen, false, NULL).material_key();
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename M>
|
template<typename M>
|
||||||
@@ -96,10 +95,12 @@ Endgames::Endgames() {
|
|||||||
add<KRKP>("KRKP");
|
add<KRKP>("KRKP");
|
||||||
add<KRKB>("KRKB");
|
add<KRKB>("KRKB");
|
||||||
add<KRKN>("KRKN");
|
add<KRKN>("KRKN");
|
||||||
|
add<KQKP>("KQKP");
|
||||||
add<KQKR>("KQKR");
|
add<KQKR>("KQKR");
|
||||||
add<KBBKN>("KBBKN");
|
add<KBBKN>("KBBKN");
|
||||||
|
|
||||||
add<KNPK>("KNPK");
|
add<KNPK>("KNPK");
|
||||||
|
add<KNPKB>("KNPKB");
|
||||||
add<KRPKR>("KRPKR");
|
add<KRPKR>("KRPKR");
|
||||||
add<KBPKB>("KBPKB");
|
add<KBPKB>("KBPKB");
|
||||||
add<KBPKN>("KBPKN");
|
add<KBPKN>("KBPKN");
|
||||||
@@ -116,10 +117,8 @@ Endgames::~Endgames() {
|
|||||||
template<EndgameType E>
|
template<EndgameType E>
|
||||||
void Endgames::add(const string& code) {
|
void Endgames::add(const string& code) {
|
||||||
|
|
||||||
typedef typename eg_family<E>::type T;
|
map((Endgame<E>*)0)[key(code, WHITE)] = new Endgame<E>(WHITE);
|
||||||
|
map((Endgame<E>*)0)[key(code, BLACK)] = new Endgame<E>(BLACK);
|
||||||
map((T*)0)[key(code, WHITE)] = new Endgame<E>(WHITE);
|
|
||||||
map((T*)0)[key(code, BLACK)] = new Endgame<E>(BLACK);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -133,19 +132,26 @@ Value Endgame<KXK>::operator()(const Position& pos) const {
|
|||||||
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
|
assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
|
||||||
|
|
||||||
|
// Stalemate detection with lone king
|
||||||
|
if ( pos.side_to_move() == weakerSide
|
||||||
|
&& !pos.checkers()
|
||||||
|
&& !MoveList<LEGAL>(pos).size()) {
|
||||||
|
return VALUE_DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
Square winnerKSq = pos.king_square(strongerSide);
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
Square loserKSq = pos.king_square(weakerSide);
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
Value result = pos.non_pawn_material(strongerSide)
|
Value result = pos.non_pawn_material(strongerSide)
|
||||||
+ pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
|
+ pos.piece_count(strongerSide, PAWN) * PawnValueEg
|
||||||
+ MateTable[loserKSq]
|
+ MateTable[loserKSq]
|
||||||
+ DistanceBonus[square_distance(winnerKSq, loserKSq)];
|
+ DistanceBonus[square_distance(winnerKSq, loserKSq)];
|
||||||
|
|
||||||
if ( pos.piece_count(strongerSide, QUEEN)
|
if ( pos.piece_count(strongerSide, QUEEN)
|
||||||
|| pos.piece_count(strongerSide, ROOK)
|
|| pos.piece_count(strongerSide, ROOK)
|
||||||
|| pos.piece_count(strongerSide, BISHOP) > 1)
|
|| pos.bishop_pair(strongerSide)) {
|
||||||
// TODO: check for two equal-colored bishops!
|
|
||||||
result += VALUE_KNOWN_WIN;
|
result += VALUE_KNOWN_WIN;
|
||||||
|
}
|
||||||
|
|
||||||
return strongerSide == pos.side_to_move() ? result : -result;
|
return strongerSide == pos.side_to_move() ? result : -result;
|
||||||
}
|
}
|
||||||
@@ -158,19 +164,19 @@ Value Endgame<KBNK>::operator()(const Position& pos) const {
|
|||||||
|
|
||||||
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
|
assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
|
||||||
assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == KnightValueMg + BishopValueMg);
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
|
||||||
Square winnerKSq = pos.king_square(strongerSide);
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
Square loserKSq = pos.king_square(weakerSide);
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
Square bishopSquare = pos.piece_list(strongerSide, BISHOP)[0];
|
Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
|
||||||
|
|
||||||
// kbnk_mate_table() tries to drive toward corners A1 or H8,
|
// kbnk_mate_table() tries to drive toward corners A1 or H8,
|
||||||
// if we have a bishop that cannot reach the above squares we
|
// if we have a bishop that cannot reach the above squares we
|
||||||
// mirror the kings so to drive enemy toward corners A8 or H1.
|
// mirror the kings so to drive enemy toward corners A8 or H1.
|
||||||
if (opposite_colors(bishopSquare, SQ_A1))
|
if (opposite_colors(bishopSq, SQ_A1))
|
||||||
{
|
{
|
||||||
winnerKSq = mirror(winnerKSq);
|
winnerKSq = mirror(winnerKSq);
|
||||||
loserKSq = mirror(loserKSq);
|
loserKSq = mirror(loserKSq);
|
||||||
@@ -194,21 +200,21 @@ Value Endgame<KPK>::operator()(const Position& pos) const {
|
|||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
Square wksq, bksq, wpsq;
|
Square wksq, bksq, wpsq;
|
||||||
Color stm;
|
Color us;
|
||||||
|
|
||||||
if (strongerSide == WHITE)
|
if (strongerSide == WHITE)
|
||||||
{
|
{
|
||||||
wksq = pos.king_square(WHITE);
|
wksq = pos.king_square(WHITE);
|
||||||
bksq = pos.king_square(BLACK);
|
bksq = pos.king_square(BLACK);
|
||||||
wpsq = pos.piece_list(WHITE, PAWN)[0];
|
wpsq = pos.piece_list(WHITE, PAWN)[0];
|
||||||
stm = pos.side_to_move();
|
us = pos.side_to_move();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
wksq = flip(pos.king_square(BLACK));
|
wksq = ~pos.king_square(BLACK);
|
||||||
bksq = flip(pos.king_square(WHITE));
|
bksq = ~pos.king_square(WHITE);
|
||||||
wpsq = flip(pos.piece_list(BLACK, PAWN)[0]);
|
wpsq = ~pos.piece_list(BLACK, PAWN)[0];
|
||||||
stm = flip(pos.side_to_move());
|
us = ~pos.side_to_move();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (file_of(wpsq) >= FILE_E)
|
if (file_of(wpsq) >= FILE_E)
|
||||||
@@ -218,12 +224,10 @@ Value Endgame<KPK>::operator()(const Position& pos) const {
|
|||||||
wpsq = mirror(wpsq);
|
wpsq = mirror(wpsq);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!probe_kpk_bitbase(wksq, wpsq, bksq, stm))
|
if (!Bitbases::probe_kpk(wksq, wpsq, bksq, us))
|
||||||
return VALUE_DRAW;
|
return VALUE_DRAW;
|
||||||
|
|
||||||
Value result = VALUE_KNOWN_WIN
|
Value result = VALUE_KNOWN_WIN + PawnValueEg + Value(rank_of(wpsq));
|
||||||
+ PawnValueEndgame
|
|
||||||
+ Value(rank_of(wpsq));
|
|
||||||
|
|
||||||
return strongerSide == pos.side_to_move() ? result : -result;
|
return strongerSide == pos.side_to_move() ? result : -result;
|
||||||
}
|
}
|
||||||
@@ -236,7 +240,7 @@ Value Endgame<KPK>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
Value Endgame<KRKP>::operator()(const Position& pos) const {
|
Value Endgame<KRKP>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
assert(pos.non_pawn_material(weakerSide) == 0);
|
assert(pos.non_pawn_material(weakerSide) == 0);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
||||||
@@ -251,24 +255,24 @@ Value Endgame<KRKP>::operator()(const Position& pos) const {
|
|||||||
|
|
||||||
if (strongerSide == BLACK)
|
if (strongerSide == BLACK)
|
||||||
{
|
{
|
||||||
wksq = flip(wksq);
|
wksq = ~wksq;
|
||||||
wrsq = flip(wrsq);
|
wrsq = ~wrsq;
|
||||||
bksq = flip(bksq);
|
bksq = ~bksq;
|
||||||
bpsq = flip(bpsq);
|
bpsq = ~bpsq;
|
||||||
}
|
}
|
||||||
|
|
||||||
Square queeningSq = make_square(file_of(bpsq), RANK_1);
|
Square queeningSq = file_of(bpsq) | RANK_1;
|
||||||
Value result;
|
Value result;
|
||||||
|
|
||||||
// If the stronger side's king is in front of the pawn, it's a win
|
// If the stronger side's king is in front of the pawn, it's a win
|
||||||
if (wksq < bpsq && file_of(wksq) == file_of(bpsq))
|
if (wksq < bpsq && file_of(wksq) == file_of(bpsq))
|
||||||
result = RookValueEndgame - Value(square_distance(wksq, bpsq));
|
result = RookValueEg - Value(square_distance(wksq, bpsq));
|
||||||
|
|
||||||
// If the weaker side's king is too far from the pawn and the rook,
|
// If the weaker side's king is too far from the pawn and the rook,
|
||||||
// it's a win
|
// it's a win
|
||||||
else if ( square_distance(bksq, bpsq) - (tempo ^ 1) >= 3
|
else if ( square_distance(bksq, bpsq) - (tempo ^ 1) >= 3
|
||||||
&& square_distance(bksq, wrsq) >= 3)
|
&& square_distance(bksq, wrsq) >= 3)
|
||||||
result = RookValueEndgame - Value(square_distance(wksq, bpsq));
|
result = RookValueEg - Value(square_distance(wksq, bpsq));
|
||||||
|
|
||||||
// If the pawn is far advanced and supported by the defending king,
|
// If the pawn is far advanced and supported by the defending king,
|
||||||
// the position is drawish
|
// the position is drawish
|
||||||
@@ -293,9 +297,9 @@ Value Endgame<KRKP>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
Value Endgame<KRKB>::operator()(const Position& pos) const {
|
Value Endgame<KRKB>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
|
|
||||||
@@ -309,9 +313,9 @@ Value Endgame<KRKB>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
Value Endgame<KRKN>::operator()(const Position& pos) const {
|
Value Endgame<KRKN>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMg);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
|
|
||||||
@@ -324,6 +328,37 @@ Value Endgame<KRKN>::operator()(const Position& pos) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KQ vs KP. In general, a win for the stronger side, however, there are a few
|
||||||
|
/// important exceptions. Pawn on 7th rank, A,C,F or H file, with king next can
|
||||||
|
/// be a draw, so we scale down to distance between kings only.
|
||||||
|
template<>
|
||||||
|
Value Endgame<KQKP>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == QueenValueMg);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == 0);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
||||||
|
|
||||||
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
Square pawnSq = pos.piece_list(weakerSide, PAWN)[0];
|
||||||
|
|
||||||
|
Value result = QueenValueEg
|
||||||
|
- PawnValueEg
|
||||||
|
+ DistanceBonus[square_distance(winnerKSq, loserKSq)];
|
||||||
|
|
||||||
|
if ( square_distance(loserKSq, pawnSq) == 1
|
||||||
|
&& relative_rank(weakerSide, pawnSq) == RANK_7)
|
||||||
|
{
|
||||||
|
File f = file_of(pawnSq);
|
||||||
|
|
||||||
|
if (f == FILE_A || f == FILE_C || f == FILE_F || f == FILE_H)
|
||||||
|
result = Value(DistanceBonus[square_distance(winnerKSq, loserKSq)]);
|
||||||
|
}
|
||||||
|
return strongerSide == pos.side_to_move() ? result : -result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// KQ vs KR. This is almost identical to KX vs K: We give the attacking
|
/// KQ vs KR. This is almost identical to KX vs K: We give the attacking
|
||||||
/// king a bonus for having the kings close together, and for forcing the
|
/// king a bonus for having the kings close together, and for forcing the
|
||||||
/// defending king towards the edge. If we also take care to avoid null move
|
/// defending king towards the edge. If we also take care to avoid null move
|
||||||
@@ -332,16 +367,16 @@ Value Endgame<KRKN>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
Value Endgame<KQKR>::operator()(const Position& pos) const {
|
Value Endgame<KQKR>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == QueenValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
Square winnerKSq = pos.king_square(strongerSide);
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
Square loserKSq = pos.king_square(weakerSide);
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
Value result = QueenValueEndgame
|
Value result = QueenValueEg
|
||||||
- RookValueEndgame
|
- RookValueEg
|
||||||
+ MateTable[loserKSq]
|
+ MateTable[loserKSq]
|
||||||
+ DistanceBonus[square_distance(winnerKSq, loserKSq)];
|
+ DistanceBonus[square_distance(winnerKSq, loserKSq)];
|
||||||
|
|
||||||
@@ -352,12 +387,12 @@ template<>
|
|||||||
Value Endgame<KBBKN>::operator()(const Position& pos) const {
|
Value Endgame<KBBKN>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 2);
|
assert(pos.piece_count(strongerSide, BISHOP) == 2);
|
||||||
assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMg);
|
||||||
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMg);
|
||||||
assert(!pos.pieces(PAWN));
|
assert(!pos.pieces(PAWN));
|
||||||
|
|
||||||
Value result = BishopValueEndgame;
|
Value result = BishopValueEg;
|
||||||
Square wksq = pos.king_square(strongerSide);
|
Square wksq = pos.king_square(strongerSide);
|
||||||
Square bksq = pos.king_square(weakerSide);
|
Square bksq = pos.king_square(weakerSide);
|
||||||
Square nsq = pos.piece_list(weakerSide, KNIGHT)[0];
|
Square nsq = pos.piece_list(weakerSide, KNIGHT)[0];
|
||||||
@@ -394,14 +429,14 @@ Value Endgame<KNNK>::operator()(const Position&) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) >= 1);
|
assert(pos.piece_count(strongerSide, PAWN) >= 1);
|
||||||
|
|
||||||
// No assertions about the material of weakerSide, because we want draws to
|
// No assertions about the material of weakerSide, because we want draws to
|
||||||
// be detected even when the weaker side has some pawns.
|
// be detected even when the weaker side has some pawns.
|
||||||
|
|
||||||
Bitboard pawns = pos.pieces(PAWN, strongerSide);
|
Bitboard pawns = pos.pieces(strongerSide, PAWN);
|
||||||
File pawnFile = file_of(pos.piece_list(strongerSide, PAWN)[0]);
|
File pawnFile = file_of(pos.piece_list(strongerSide, PAWN)[0]);
|
||||||
|
|
||||||
// All pawns are on a single rook file ?
|
// All pawns are on a single rook file ?
|
||||||
@@ -409,14 +444,14 @@ ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
|||||||
&& !(pawns & ~file_bb(pawnFile)))
|
&& !(pawns & ~file_bb(pawnFile)))
|
||||||
{
|
{
|
||||||
Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
|
Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
|
||||||
Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
|
Square queeningSq = relative_square(strongerSide, pawnFile | RANK_8);
|
||||||
Square kingSq = pos.king_square(weakerSide);
|
Square kingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
if ( opposite_colors(queeningSq, bishopSq)
|
if ( opposite_colors(queeningSq, bishopSq)
|
||||||
&& abs(file_of(kingSq) - pawnFile) <= 1)
|
&& abs(file_of(kingSq) - pawnFile) <= 1)
|
||||||
{
|
{
|
||||||
// The bishop has the wrong color, and the defending king is on the
|
// The bishop has the wrong color, and the defending king is on the
|
||||||
// file of the pawn(s) or the neighboring file. Find the rank of the
|
// file of the pawn(s) or the adjacent file. Find the rank of the
|
||||||
// frontmost pawn.
|
// frontmost pawn.
|
||||||
Rank rank;
|
Rank rank;
|
||||||
if (strongerSide == WHITE)
|
if (strongerSide == WHITE)
|
||||||
@@ -437,6 +472,29 @@ ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
|||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// All pawns on same B or G file? Then potential draw
|
||||||
|
if ( (pawnFile == FILE_B || pawnFile == FILE_G)
|
||||||
|
&& !(pos.pieces(PAWN) & ~file_bb(pawnFile))
|
||||||
|
&& pos.non_pawn_material(weakerSide) == 0
|
||||||
|
&& pos.piece_count(weakerSide, PAWN) >= 1)
|
||||||
|
{
|
||||||
|
// Get weaker pawn closest to opponent's queening square
|
||||||
|
Bitboard wkPawns = pos.pieces(weakerSide, PAWN);
|
||||||
|
Square weakerPawnSq = strongerSide == WHITE ? msb(wkPawns) : lsb(wkPawns);
|
||||||
|
|
||||||
|
Square strongerKingSq = pos.king_square(strongerSide);
|
||||||
|
Square weakerKingSq = pos.king_square(weakerSide);
|
||||||
|
Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
|
||||||
|
|
||||||
|
// Draw if weaker pawn is on rank 7, bishop can't attack the pawn, and
|
||||||
|
// weaker king can stop opposing opponent's king from penetrating.
|
||||||
|
if ( relative_rank(strongerSide, weakerPawnSq) == RANK_7
|
||||||
|
&& opposite_colors(bishopSq, weakerPawnSq)
|
||||||
|
&& square_distance(weakerPawnSq, weakerKingSq) <= square_distance(weakerPawnSq, strongerKingSq))
|
||||||
|
return SCALE_FACTOR_DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
return SCALE_FACTOR_NONE;
|
return SCALE_FACTOR_NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -446,7 +504,7 @@ ScaleFactor Endgame<KBPsK>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == QueenValueMg);
|
||||||
assert(pos.piece_count(strongerSide, QUEEN) == 1);
|
assert(pos.piece_count(strongerSide, QUEEN) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
assert(pos.piece_count(weakerSide, ROOK) == 1);
|
assert(pos.piece_count(weakerSide, ROOK) == 1);
|
||||||
@@ -455,12 +513,12 @@ ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
|
|||||||
Square kingSq = pos.king_square(weakerSide);
|
Square kingSq = pos.king_square(weakerSide);
|
||||||
if ( relative_rank(weakerSide, kingSq) <= RANK_2
|
if ( relative_rank(weakerSide, kingSq) <= RANK_2
|
||||||
&& relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
|
&& relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
|
||||||
&& (pos.pieces(ROOK, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_3)))
|
&& (pos.pieces(weakerSide, ROOK) & rank_bb(relative_rank(weakerSide, RANK_3)))
|
||||||
&& (pos.pieces(PAWN, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_2)))
|
&& (pos.pieces(weakerSide, PAWN) & rank_bb(relative_rank(weakerSide, RANK_2)))
|
||||||
&& (pos.attacks_from<KING>(kingSq) & pos.pieces(PAWN, weakerSide)))
|
&& (pos.attacks_from<KING>(kingSq) & pos.pieces(weakerSide, PAWN)))
|
||||||
{
|
{
|
||||||
Square rsq = pos.piece_list(weakerSide, ROOK)[0];
|
Square rsq = pos.piece_list(weakerSide, ROOK)[0];
|
||||||
if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(PAWN, weakerSide))
|
if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(weakerSide, PAWN))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
}
|
}
|
||||||
return SCALE_FACTOR_NONE;
|
return SCALE_FACTOR_NONE;
|
||||||
@@ -476,9 +534,9 @@ ScaleFactor Endgame<KQKRPs>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
Square wksq = pos.king_square(strongerSide);
|
Square wksq = pos.king_square(strongerSide);
|
||||||
@@ -491,11 +549,11 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
|||||||
// pawn is on the left half of the board.
|
// pawn is on the left half of the board.
|
||||||
if (strongerSide == BLACK)
|
if (strongerSide == BLACK)
|
||||||
{
|
{
|
||||||
wksq = flip(wksq);
|
wksq = ~wksq;
|
||||||
wrsq = flip(wrsq);
|
wrsq = ~wrsq;
|
||||||
wpsq = flip(wpsq);
|
wpsq = ~wpsq;
|
||||||
bksq = flip(bksq);
|
bksq = ~bksq;
|
||||||
brsq = flip(brsq);
|
brsq = ~brsq;
|
||||||
}
|
}
|
||||||
if (file_of(wpsq) > FILE_D)
|
if (file_of(wpsq) > FILE_D)
|
||||||
{
|
{
|
||||||
@@ -508,7 +566,7 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
|||||||
|
|
||||||
File f = file_of(wpsq);
|
File f = file_of(wpsq);
|
||||||
Rank r = rank_of(wpsq);
|
Rank r = rank_of(wpsq);
|
||||||
Square queeningSq = make_square(f, RANK_8);
|
Square queeningSq = f | RANK_8;
|
||||||
int tempo = (pos.side_to_move() == strongerSide);
|
int tempo = (pos.side_to_move() == strongerSide);
|
||||||
|
|
||||||
// If the pawn is not too far advanced and the defending king defends the
|
// If the pawn is not too far advanced and the defending king defends the
|
||||||
@@ -594,9 +652,9 @@ ScaleFactor Endgame<KRPKR>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KRPPKRP>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
||||||
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == RookValueMg);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
||||||
|
|
||||||
Square wpsq1 = pos.piece_list(strongerSide, PAWN)[0];
|
Square wpsq1 = pos.piece_list(strongerSide, PAWN)[0];
|
||||||
@@ -638,7 +696,7 @@ ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
|
|||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
Square ksq = pos.king_square(weakerSide);
|
Square ksq = pos.king_square(weakerSide);
|
||||||
Bitboard pawns = pos.pieces(PAWN, strongerSide);
|
Bitboard pawns = pos.pieces(strongerSide, PAWN);
|
||||||
|
|
||||||
// Are all pawns on the 'a' file?
|
// Are all pawns on the 'a' file?
|
||||||
if (!(pawns & ~FileABB))
|
if (!(pawns & ~FileABB))
|
||||||
@@ -646,7 +704,7 @@ ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
|
|||||||
// Does the defending king block the pawns?
|
// Does the defending king block the pawns?
|
||||||
if ( square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1
|
if ( square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1
|
||||||
|| ( file_of(ksq) == FILE_A
|
|| ( file_of(ksq) == FILE_A
|
||||||
&& !in_front_bb(strongerSide, ksq) & pawns))
|
&& !(in_front_bb(strongerSide, ksq) & pawns)))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
}
|
}
|
||||||
// Are all pawns on the 'h' file?
|
// Are all pawns on the 'h' file?
|
||||||
@@ -655,7 +713,7 @@ ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
|
|||||||
// Does the defending king block the pawns?
|
// Does the defending king block the pawns?
|
||||||
if ( square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1
|
if ( square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1
|
||||||
|| ( file_of(ksq) == FILE_H
|
|| ( file_of(ksq) == FILE_H
|
||||||
&& !in_front_bb(strongerSide, ksq) & pawns))
|
&& !(in_front_bb(strongerSide, ksq) & pawns)))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
}
|
}
|
||||||
return SCALE_FACTOR_NONE;
|
return SCALE_FACTOR_NONE;
|
||||||
@@ -669,10 +727,10 @@ ScaleFactor Endgame<KPsK>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
@@ -705,9 +763,9 @@ ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
|
|||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Bitboard path = squares_in_front_of(strongerSide, pawnSq);
|
Bitboard path = forward_bb(strongerSide, pawnSq);
|
||||||
|
|
||||||
if (path & pos.pieces(KING, weakerSide))
|
if (path & pos.pieces(weakerSide, KING))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
|
|
||||||
if ( (pos.attacks_from<BISHOP>(weakerBishopSq) & path)
|
if ( (pos.attacks_from<BISHOP>(weakerBishopSq) & path)
|
||||||
@@ -724,10 +782,10 @@ ScaleFactor Endgame<KBPKB>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
||||||
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
@@ -747,12 +805,12 @@ ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
|||||||
if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
|
if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
|
||||||
{
|
{
|
||||||
blockSq1 = psq1 + pawn_push(strongerSide);
|
blockSq1 = psq1 + pawn_push(strongerSide);
|
||||||
blockSq2 = make_square(file_of(psq2), rank_of(psq1));
|
blockSq2 = file_of(psq2) | rank_of(psq1);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
blockSq1 = psq2 + pawn_push(strongerSide);
|
blockSq1 = psq2 + pawn_push(strongerSide);
|
||||||
blockSq2 = make_square(file_of(psq1), rank_of(psq2));
|
blockSq2 = file_of(psq1) | rank_of(psq2);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (file_distance(psq1, psq2))
|
switch (file_distance(psq1, psq2))
|
||||||
@@ -768,20 +826,20 @@ ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
|||||||
return SCALE_FACTOR_NONE;
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
case 1:
|
case 1:
|
||||||
// Pawns on neighboring files. Draw if defender firmly controls the square
|
// Pawns on adjacent files. Draw if defender firmly controls the square
|
||||||
// in front of the frontmost pawn's path, and the square diagonally behind
|
// in front of the frontmost pawn's path, and the square diagonally behind
|
||||||
// this square on the file of the other pawn.
|
// this square on the file of the other pawn.
|
||||||
if ( ksq == blockSq1
|
if ( ksq == blockSq1
|
||||||
&& opposite_colors(ksq, wbsq)
|
&& opposite_colors(ksq, wbsq)
|
||||||
&& ( bbsq == blockSq2
|
&& ( bbsq == blockSq2
|
||||||
|| (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(BISHOP, weakerSide))
|
|| (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(weakerSide, BISHOP))
|
||||||
|| abs(r1 - r2) >= 2))
|
|| abs(r1 - r2) >= 2))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
|
|
||||||
else if ( ksq == blockSq2
|
else if ( ksq == blockSq2
|
||||||
&& opposite_colors(ksq, wbsq)
|
&& opposite_colors(ksq, wbsq)
|
||||||
&& ( bbsq == blockSq1
|
&& ( bbsq == blockSq1
|
||||||
|| (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(BISHOP, weakerSide))))
|
|| (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(weakerSide, BISHOP))))
|
||||||
return SCALE_FACTOR_DRAW;
|
return SCALE_FACTOR_DRAW;
|
||||||
else
|
else
|
||||||
return SCALE_FACTOR_NONE;
|
return SCALE_FACTOR_NONE;
|
||||||
@@ -799,10 +857,10 @@ ScaleFactor Endgame<KBPPKB>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMg);
|
||||||
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMg);
|
||||||
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
@@ -826,7 +884,7 @@ ScaleFactor Endgame<KBPKN>::operator()(const Position& pos) const {
|
|||||||
template<>
|
template<>
|
||||||
ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const {
|
ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
|
assert(pos.non_pawn_material(strongerSide) == KnightValueMg);
|
||||||
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
||||||
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
|
||||||
@@ -847,6 +905,24 @@ ScaleFactor Endgame<KNPK>::operator()(const Position& pos) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// K, knight and a pawn vs K and bishop. If knight can block bishop from taking
|
||||||
|
/// pawn, it's a win. Otherwise, drawn.
|
||||||
|
template<>
|
||||||
|
ScaleFactor Endgame<KNPKB>::operator()(const Position& pos) const {
|
||||||
|
|
||||||
|
Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
|
||||||
|
Square bishopSq = pos.piece_list(weakerSide, BISHOP)[0];
|
||||||
|
Square weakerKingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
// King needs to get close to promoting pawn to prevent knight from blocking.
|
||||||
|
// Rules for this are very tricky, so just approximate.
|
||||||
|
if (forward_bb(strongerSide, pawnSq) & pos.attacks_from<BISHOP>(bishopSq))
|
||||||
|
return ScaleFactor(square_distance(weakerKingSq, pawnSq));
|
||||||
|
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// K and a pawn vs K and a pawn. This is done by removing the weakest side's
|
/// K and a pawn vs K and a pawn. This is done by removing the weakest side's
|
||||||
/// pawn and probing the KP vs K bitbase: If the weakest side has a draw without
|
/// pawn and probing the KP vs K bitbase: If the weakest side has a draw without
|
||||||
/// the pawn, she probably has at least a draw with the pawn as well. The exception
|
/// the pawn, she probably has at least a draw with the pawn as well. The exception
|
||||||
@@ -863,14 +939,14 @@ ScaleFactor Endgame<KPKP>::operator()(const Position& pos) const {
|
|||||||
Square wksq = pos.king_square(strongerSide);
|
Square wksq = pos.king_square(strongerSide);
|
||||||
Square bksq = pos.king_square(weakerSide);
|
Square bksq = pos.king_square(weakerSide);
|
||||||
Square wpsq = pos.piece_list(strongerSide, PAWN)[0];
|
Square wpsq = pos.piece_list(strongerSide, PAWN)[0];
|
||||||
Color stm = pos.side_to_move();
|
Color us = pos.side_to_move();
|
||||||
|
|
||||||
if (strongerSide == BLACK)
|
if (strongerSide == BLACK)
|
||||||
{
|
{
|
||||||
wksq = flip(wksq);
|
wksq = ~wksq;
|
||||||
bksq = flip(bksq);
|
bksq = ~bksq;
|
||||||
wpsq = flip(wpsq);
|
wpsq = ~wpsq;
|
||||||
stm = flip(stm);
|
us = ~us;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (file_of(wpsq) >= FILE_E)
|
if (file_of(wpsq) >= FILE_E)
|
||||||
@@ -888,5 +964,5 @@ ScaleFactor Endgame<KPKP>::operator()(const Position& pos) const {
|
|||||||
|
|
||||||
// Probe the KPK bitbase with the weakest side's pawn removed. If it's a draw,
|
// Probe the KPK bitbase with the weakest side's pawn removed. If it's a draw,
|
||||||
// it's probably at least a draw even with the pawn.
|
// it's probably at least a draw even with the pawn.
|
||||||
return probe_kpk_bitbase(wksq, wpsq, bksq, stm) ? SCALE_FACTOR_NONE : SCALE_FACTOR_DRAW;
|
return Bitbases::probe_kpk(wksq, wpsq, bksq, us) ? SCALE_FACTOR_NONE : SCALE_FACTOR_DRAW;
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-15
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -39,6 +39,7 @@ enum EndgameType {
|
|||||||
KRKP, // KR vs KP
|
KRKP, // KR vs KP
|
||||||
KRKB, // KR vs KB
|
KRKB, // KR vs KB
|
||||||
KRKN, // KR vs KN
|
KRKN, // KR vs KN
|
||||||
|
KQKP, // KQ vs KP
|
||||||
KQKR, // KQ vs KR
|
KQKR, // KQ vs KR
|
||||||
KBBKN, // KBB vs KN
|
KBBKN, // KBB vs KN
|
||||||
KNNK, // KNN vs K
|
KNNK, // KNN vs K
|
||||||
@@ -57,15 +58,17 @@ enum EndgameType {
|
|||||||
KBPPKB, // KBPP vs KB
|
KBPPKB, // KBPP vs KB
|
||||||
KBPKN, // KBP vs KN
|
KBPKN, // KBP vs KN
|
||||||
KNPK, // KNP vs K
|
KNPK, // KNP vs K
|
||||||
|
KNPKB, // KNP vs KB
|
||||||
KPKP // KP vs KP
|
KPKP // KP vs KP
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
/// Some magic to detect family type of endgame from its enum value
|
/// 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<bool> struct bool_to_type { typedef Value type; };
|
template<int> struct eg_fun { typedef Value type; };
|
||||||
template<> struct bool_to_type<true> { typedef ScaleFactor type; };
|
template<> struct eg_fun<1> { typedef ScaleFactor type; };
|
||||||
template<EndgameType E> struct eg_family : public bool_to_type<(E > SCALE_FUNS)> {};
|
|
||||||
|
|
||||||
|
|
||||||
/// Base and derived templates for endgame evaluation and scaling functions
|
/// Base and derived templates for endgame evaluation and scaling functions
|
||||||
@@ -79,10 +82,10 @@ struct EndgameBase {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
template<EndgameType E, typename T = typename eg_family<E>::type>
|
template<EndgameType E, typename T = typename eg_fun<(E > SCALE_FUNS)>::type>
|
||||||
struct Endgame : public EndgameBase<T> {
|
struct Endgame : public EndgameBase<T> {
|
||||||
|
|
||||||
explicit Endgame(Color c) : strongerSide(c), weakerSide(flip(c)) {}
|
explicit Endgame(Color c) : strongerSide(c), weakerSide(~c) {}
|
||||||
Color color() const { return strongerSide; }
|
Color color() const { return strongerSide; }
|
||||||
T operator()(const Position&) const;
|
T operator()(const Position&) const;
|
||||||
|
|
||||||
@@ -93,18 +96,18 @@ private:
|
|||||||
|
|
||||||
/// Endgames class stores in two std::map the pointers to endgame evaluation
|
/// Endgames class stores in two std::map the pointers to endgame evaluation
|
||||||
/// and scaling base objects. Then we use polymorphism to invoke the actual
|
/// and scaling base objects. Then we use polymorphism to invoke the actual
|
||||||
/// endgame function calling its operator() method that is virtual.
|
/// endgame function calling its operator() that is virtual.
|
||||||
|
|
||||||
class Endgames {
|
class Endgames {
|
||||||
|
|
||||||
typedef std::map<Key, EndgameBase<Value>*> M1;
|
typedef std::map<Key, EndgameBase<eg_fun<0>::type>*> M1;
|
||||||
typedef std::map<Key, EndgameBase<ScaleFactor>*> M2;
|
typedef std::map<Key, EndgameBase<eg_fun<1>::type>*> M2;
|
||||||
|
|
||||||
M1 m1;
|
M1 m1;
|
||||||
M2 m2;
|
M2 m2;
|
||||||
|
|
||||||
M1& map(Value*) { return m1; }
|
M1& map(M1::mapped_type) { return m1; }
|
||||||
M2& map(ScaleFactor*) { return m2; }
|
M2& map(M2::mapped_type) { return m2; }
|
||||||
|
|
||||||
template<EndgameType E> void add(const std::string& code);
|
template<EndgameType E> void add(const std::string& code);
|
||||||
|
|
||||||
@@ -112,9 +115,8 @@ public:
|
|||||||
Endgames();
|
Endgames();
|
||||||
~Endgames();
|
~Endgames();
|
||||||
|
|
||||||
template<typename T> EndgameBase<T>* get(Key key) {
|
template<typename T> T probe(Key key, T& eg)
|
||||||
return map((T*)0).count(key) ? map((T*)0)[key] : NULL;
|
{ return eg = map(eg).count(key) ? map(eg)[key] : NULL; }
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // !defined(ENDGAME_H_INCLUDED)
|
#endif // !defined(ENDGAME_H_INCLUDED)
|
||||||
|
|||||||
+230
-218
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -18,7 +18,6 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <iostream>
|
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
@@ -37,13 +36,13 @@ namespace {
|
|||||||
struct EvalInfo {
|
struct EvalInfo {
|
||||||
|
|
||||||
// Pointers to material and pawn hash table entries
|
// Pointers to material and pawn hash table entries
|
||||||
MaterialInfo* mi;
|
Material::Entry* mi;
|
||||||
PawnInfo* pi;
|
Pawns::Entry* pi;
|
||||||
|
|
||||||
// attackedBy[color][piece type] is a bitboard representing all squares
|
// attackedBy[color][piece type] is a bitboard representing all squares
|
||||||
// attacked by a given color and piece type, attackedBy[color][0] contains
|
// attacked by a given color and piece type, attackedBy[color][ALL_PIECES]
|
||||||
// all squares attacked by the given color.
|
// contains all squares attacked by the given color.
|
||||||
Bitboard attackedBy[2][8];
|
Bitboard attackedBy[COLOR_NB][PIECE_TYPE_NB];
|
||||||
|
|
||||||
// kingRing[color] is the zone around the king which is considered
|
// kingRing[color] is the zone around the king which is considered
|
||||||
// by the king safety evaluation. This consists of the squares directly
|
// by the king safety evaluation. This consists of the squares directly
|
||||||
@@ -51,25 +50,25 @@ namespace {
|
|||||||
// squares two ranks in front of the king. For instance, if black's king
|
// squares two ranks in front of the king. For instance, if black's king
|
||||||
// is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
|
// is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
|
||||||
// f7, g7, h7, f6, g6 and h6.
|
// f7, g7, h7, f6, g6 and h6.
|
||||||
Bitboard kingRing[2];
|
Bitboard kingRing[COLOR_NB];
|
||||||
|
|
||||||
// kingAttackersCount[color] is the number of pieces of the given color
|
// kingAttackersCount[color] is the number of pieces of the given color
|
||||||
// which attack a square in the kingRing of the enemy king.
|
// which attack a square in the kingRing of the enemy king.
|
||||||
int kingAttackersCount[2];
|
int kingAttackersCount[COLOR_NB];
|
||||||
|
|
||||||
// kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
|
// kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
|
||||||
// given color which attack a square in the kingRing of the enemy king. The
|
// given color which attack a square in the kingRing of the enemy king. The
|
||||||
// weights of the individual piece types are given by the variables
|
// weights of the individual piece types are given by the variables
|
||||||
// QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
|
// QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
|
||||||
// KnightAttackWeight in evaluate.cpp
|
// KnightAttackWeight in evaluate.cpp
|
||||||
int kingAttackersWeight[2];
|
int kingAttackersWeight[COLOR_NB];
|
||||||
|
|
||||||
// kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
|
// kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
|
||||||
// directly adjacent to the king of the given color. Pieces which attack
|
// directly adjacent to the king of the given color. Pieces which attack
|
||||||
// more than one square are counted multiple times. For instance, if black's
|
// more than one square are counted multiple times. For instance, if black's
|
||||||
// king is on g8 and there's a white knight on g5, this knight adds
|
// king is on g8 and there's a white knight on g5, this knight adds
|
||||||
// 2 to kingAdjacentZoneAttacksCount[BLACK].
|
// 2 to kingAdjacentZoneAttacksCount[BLACK].
|
||||||
int kingAdjacentZoneAttacksCount[2];
|
int kingAdjacentZoneAttacksCount[COLOR_NB];
|
||||||
};
|
};
|
||||||
|
|
||||||
// Evaluation grain size, must be a power of 2
|
// Evaluation grain size, must be a power of 2
|
||||||
@@ -89,7 +88,7 @@ namespace {
|
|||||||
//
|
//
|
||||||
// Values modified by Joona Kiiski
|
// Values modified by Joona Kiiski
|
||||||
const Score WeightsInternal[] = {
|
const Score WeightsInternal[] = {
|
||||||
S(252, 344), S(216, 266), S(46, 0), S(247, 0), S(259, 0)
|
S(289, 344), S(221, 273), S(46, 0), S(271, 0), S(307, 0)
|
||||||
};
|
};
|
||||||
|
|
||||||
// MobilityBonus[PieceType][attacked] contains mobility bonuses for middle and
|
// MobilityBonus[PieceType][attacked] contains mobility bonuses for middle and
|
||||||
@@ -115,7 +114,7 @@ namespace {
|
|||||||
|
|
||||||
// OutpostBonus[PieceType][Square] contains outpost bonuses of knights and
|
// OutpostBonus[PieceType][Square] contains outpost bonuses of knights and
|
||||||
// bishops, indexed by piece type and square (from white's point of view).
|
// bishops, indexed by piece type and square (from white's point of view).
|
||||||
const Value OutpostBonus[][64] = {
|
const Value OutpostBonus[][SQUARE_NB] = {
|
||||||
{
|
{
|
||||||
// A B C D E F G H
|
// A B C D E F G H
|
||||||
V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
|
V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
|
||||||
@@ -135,11 +134,11 @@ namespace {
|
|||||||
|
|
||||||
// ThreatBonus[attacking][attacked] contains threat bonuses according to
|
// ThreatBonus[attacking][attacked] contains threat bonuses according to
|
||||||
// which piece type attacks which one.
|
// which piece type attacks which one.
|
||||||
const Score ThreatBonus[][8] = {
|
const Score ThreatBonus[][PIECE_TYPE_NB] = {
|
||||||
{}, {},
|
{}, {},
|
||||||
{ S(0, 0), S( 7, 39), S( 0, 0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
|
{ S(0, 0), S( 7, 39), S( 0, 0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
|
||||||
{ S(0, 0), S( 7, 39), S(24, 49), S( 0, 0), S(41,100), S(41,100) }, // BISHOP
|
{ S(0, 0), S( 7, 39), S(24, 49), S( 0, 0), S(41,100), S(41,100) }, // BISHOP
|
||||||
{ S(0, 0), S(-1, 29), S(15, 49), S(15, 49), S( 0, 0), S(24, 49) }, // ROOK
|
{ S(0, 0), S( 0, 22), S(15, 49), S(15, 49), S( 0, 0), S(24, 49) }, // ROOK
|
||||||
{ S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0, 0) } // QUEEN
|
{ S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0, 0) } // QUEEN
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -151,23 +150,38 @@ namespace {
|
|||||||
|
|
||||||
#undef S
|
#undef S
|
||||||
|
|
||||||
// Rooks and queens on the 7th rank (modified by Joona Kiiski)
|
const Score BishopPinBonus = make_score(66, 11);
|
||||||
const Score RookOn7thBonus = make_score(47, 98);
|
|
||||||
const Score QueenOn7thBonus = make_score(27, 54);
|
// Bonus for having the side to move (modified by Joona Kiiski)
|
||||||
|
const Score Tempo = make_score(24, 11);
|
||||||
|
|
||||||
|
// Rooks and queens on the 7th rank
|
||||||
|
const Score RookOn7thBonus = make_score(11, 20);
|
||||||
|
const Score QueenOn7thBonus = make_score( 3, 8);
|
||||||
|
|
||||||
|
// Rooks and queens attacking pawns on the same rank
|
||||||
|
const Score RookOnPawnBonus = make_score(10, 28);
|
||||||
|
const Score QueenOnPawnBonus = make_score( 4, 20);
|
||||||
|
|
||||||
// Rooks on open files (modified by Joona Kiiski)
|
// Rooks on open files (modified by Joona Kiiski)
|
||||||
const Score RookOpenFileBonus = make_score(43, 43);
|
const Score RookOpenFileBonus = make_score(43, 21);
|
||||||
const Score RookHalfOpenFileBonus = make_score(19, 19);
|
const Score RookHalfOpenFileBonus = make_score(19, 10);
|
||||||
|
|
||||||
// Penalty for rooks trapped inside a friendly king which has lost the
|
// Penalty for rooks trapped inside a friendly king which has lost the
|
||||||
// right to castle.
|
// right to castle.
|
||||||
const Value TrappedRookPenalty = Value(180);
|
const Value TrappedRookPenalty = Value(180);
|
||||||
|
|
||||||
|
// Penalty for bishop with pawns on the same coloured squares
|
||||||
|
const Score BishopPawnsPenalty = make_score(8, 12);
|
||||||
|
|
||||||
// Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
|
// Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
|
||||||
// a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
|
// a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
|
||||||
// happen in Chess960 games.
|
// happen in Chess960 games.
|
||||||
const Score TrappedBishopA1H1Penalty = make_score(100, 100);
|
const Score TrappedBishopA1H1Penalty = make_score(100, 100);
|
||||||
|
|
||||||
|
// Penalty for an undefended bishop or knight
|
||||||
|
const Score UndefendedMinorPenalty = make_score(25, 10);
|
||||||
|
|
||||||
// The SpaceMask[Color] contains the area of the board which is considered
|
// The SpaceMask[Color] contains the area of the board which is considered
|
||||||
// by the space evaluation. In the middle game, each side is given a bonus
|
// by the space evaluation. In the middle game, each side is given a bonus
|
||||||
// based on how many squares inside this area are safe and available for
|
// based on how many squares inside this area are safe and available for
|
||||||
@@ -212,11 +226,11 @@ namespace {
|
|||||||
|
|
||||||
// KingDangerTable[Color][attackUnits] contains the actual king danger
|
// KingDangerTable[Color][attackUnits] contains the actual king danger
|
||||||
// weighted scores, indexed by color and by a calculated integer number.
|
// weighted scores, indexed by color and by a calculated integer number.
|
||||||
Score KingDangerTable[2][128];
|
Score KingDangerTable[COLOR_NB][128];
|
||||||
|
|
||||||
// TracedTerms[Color][PieceType || TracedType] contains a breakdown of the
|
// TracedTerms[Color][PieceType || TracedType] contains a breakdown of the
|
||||||
// evaluation terms, used when tracing.
|
// evaluation terms, used when tracing.
|
||||||
Score TracedScores[2][16];
|
Score TracedScores[COLOR_NB][16];
|
||||||
std::stringstream TraceStream;
|
std::stringstream TraceStream;
|
||||||
|
|
||||||
enum TracedType {
|
enum TracedType {
|
||||||
@@ -248,42 +262,120 @@ namespace {
|
|||||||
|
|
||||||
Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
|
Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
|
||||||
|
|
||||||
inline Score apply_weight(Score v, Score weight);
|
Value interpolate(const Score& v, Phase ph, ScaleFactor sf);
|
||||||
Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf);
|
|
||||||
Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
|
Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
|
||||||
void init_safety();
|
|
||||||
double to_cp(Value v);
|
double to_cp(Value v);
|
||||||
void trace_add(int idx, Score term_w, Score term_b = SCORE_ZERO);
|
void trace_add(int idx, Score term_w, Score term_b = SCORE_ZERO);
|
||||||
|
void trace_row(const char* name, int idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace Eval {
|
||||||
|
|
||||||
/// evaluate() is the main evaluation function. It always computes two
|
/// evaluate() is the main evaluation function. It always computes two
|
||||||
/// values, an endgame score and a middle game score, and interpolates
|
/// values, an endgame score and a middle game score, and interpolates
|
||||||
/// between them based on the remaining material.
|
/// between them based on the remaining material.
|
||||||
Value evaluate(const Position& pos, Value& margin) { return do_evaluate<false>(pos, margin); }
|
|
||||||
|
Value evaluate(const Position& pos, Value& margin) {
|
||||||
|
return do_evaluate<false>(pos, margin);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// init() computes evaluation weights from the corresponding UCI parameters
|
||||||
|
/// and setup king tables.
|
||||||
|
|
||||||
|
void init() {
|
||||||
|
|
||||||
|
Weights[Mobility] = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
|
||||||
|
Weights[PassedPawns] = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
|
||||||
|
Weights[Space] = weight_option("Space", "Space", WeightsInternal[Space]);
|
||||||
|
Weights[KingDangerUs] = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
|
||||||
|
Weights[KingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
|
||||||
|
|
||||||
|
const int MaxSlope = 30;
|
||||||
|
const int Peak = 1280;
|
||||||
|
|
||||||
|
for (int t = 0, i = 1; i < 100; i++)
|
||||||
|
{
|
||||||
|
t = std::min(Peak, std::min(int(0.4 * i * i), t + MaxSlope));
|
||||||
|
|
||||||
|
KingDangerTable[1][i] = apply_weight(make_score(t, 0), Weights[KingDangerUs]);
|
||||||
|
KingDangerTable[0][i] = apply_weight(make_score(t, 0), Weights[KingDangerThem]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// trace() is like evaluate() but instead of a value returns a string suitable
|
||||||
|
/// to be print on stdout with the detailed descriptions and values of each
|
||||||
|
/// evaluation term. Used mainly for debugging.
|
||||||
|
|
||||||
|
std::string trace(const Position& pos) {
|
||||||
|
|
||||||
|
Value margin;
|
||||||
|
std::string totals;
|
||||||
|
|
||||||
|
Search::RootColor = pos.side_to_move();
|
||||||
|
|
||||||
|
TraceStream.str("");
|
||||||
|
TraceStream << std::showpoint << std::showpos << std::fixed << std::setprecision(2);
|
||||||
|
memset(TracedScores, 0, 2 * 16 * sizeof(Score));
|
||||||
|
|
||||||
|
do_evaluate<true>(pos, margin);
|
||||||
|
|
||||||
|
totals = TraceStream.str();
|
||||||
|
TraceStream.str("");
|
||||||
|
|
||||||
|
TraceStream << std::setw(21) << "Eval term " << "| White | Black | Total \n"
|
||||||
|
<< " | MG EG | MG EG | MG EG \n"
|
||||||
|
<< "---------------------+-------------+-------------+---------------\n";
|
||||||
|
|
||||||
|
trace_row("Material, PST, Tempo", PST);
|
||||||
|
trace_row("Material imbalance", IMBALANCE);
|
||||||
|
trace_row("Pawns", PAWN);
|
||||||
|
trace_row("Knights", KNIGHT);
|
||||||
|
trace_row("Bishops", BISHOP);
|
||||||
|
trace_row("Rooks", ROOK);
|
||||||
|
trace_row("Queens", QUEEN);
|
||||||
|
trace_row("Mobility", MOBILITY);
|
||||||
|
trace_row("King safety", KING);
|
||||||
|
trace_row("Threats", THREAT);
|
||||||
|
trace_row("Passed pawns", PASSED);
|
||||||
|
trace_row("Unstoppable pawns", UNSTOPPABLE);
|
||||||
|
trace_row("Space", SPACE);
|
||||||
|
|
||||||
|
TraceStream << "---------------------+-------------+-------------+---------------\n";
|
||||||
|
trace_row("Total", TOTAL);
|
||||||
|
TraceStream << totals;
|
||||||
|
|
||||||
|
return TraceStream.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Eval
|
||||||
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
template<bool Trace>
|
template<bool Trace>
|
||||||
Value do_evaluate(const Position& pos, Value& margin) {
|
Value do_evaluate(const Position& pos, Value& margin) {
|
||||||
|
|
||||||
|
assert(!pos.checkers());
|
||||||
|
|
||||||
EvalInfo ei;
|
EvalInfo ei;
|
||||||
Value margins[2];
|
Value margins[COLOR_NB];
|
||||||
Score score, mobilityWhite, mobilityBlack;
|
Score score, mobilityWhite, mobilityBlack;
|
||||||
|
Thread* th = pos.this_thread();
|
||||||
assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
|
|
||||||
assert(!pos.in_check());
|
|
||||||
|
|
||||||
// Initialize score by reading the incrementally updated scores included
|
|
||||||
// in the position object (material + piece square tables).
|
|
||||||
score = pos.value();
|
|
||||||
|
|
||||||
// margins[] store the uncertainty estimation of position's evaluation
|
// margins[] store the uncertainty estimation of position's evaluation
|
||||||
// that typically is used by the search for pruning decisions.
|
// that typically is used by the search for pruning decisions.
|
||||||
margins[WHITE] = margins[BLACK] = VALUE_ZERO;
|
margins[WHITE] = margins[BLACK] = VALUE_ZERO;
|
||||||
|
|
||||||
|
// Initialize score by reading the incrementally updated scores included
|
||||||
|
// in the position object (material + piece square tables) and adding
|
||||||
|
// Tempo bonus. Score is computed from the point of view of white.
|
||||||
|
score = pos.psq_score() + (pos.side_to_move() == WHITE ? Tempo : -Tempo);
|
||||||
|
|
||||||
// Probe the material hash table
|
// Probe the material hash table
|
||||||
ei.mi = Threads[pos.thread()].materialTable.material_info(pos);
|
ei.mi = Material::probe(pos, th->materialTable, th->endgames);
|
||||||
score += ei.mi->material_value();
|
score += ei.mi->material_value();
|
||||||
|
|
||||||
// If we have a specialized evaluation function for the current material
|
// If we have a specialized evaluation function for the current material
|
||||||
@@ -295,7 +387,7 @@ Value do_evaluate(const Position& pos, Value& margin) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Probe the pawn hash table
|
// Probe the pawn hash table
|
||||||
ei.pi = Threads[pos.thread()].pawnTable.pawn_info(pos);
|
ei.pi = Pawns::probe(pos, th->pawnsTable);
|
||||||
score += ei.pi->pawns_value();
|
score += ei.pi->pawns_value();
|
||||||
|
|
||||||
// Initialize attack and king safety bitboards
|
// Initialize attack and king safety bitboards
|
||||||
@@ -339,12 +431,12 @@ Value do_evaluate(const Position& pos, Value& margin) {
|
|||||||
// If we don't already have an unusual scale factor, check for opposite
|
// If we don't already have an unusual scale factor, check for opposite
|
||||||
// colored bishop endgames, and use a lower scale for those.
|
// colored bishop endgames, and use a lower scale for those.
|
||||||
if ( ei.mi->game_phase() < PHASE_MIDGAME
|
if ( ei.mi->game_phase() < PHASE_MIDGAME
|
||||||
&& pos.opposite_colored_bishops()
|
&& pos.opposite_bishops()
|
||||||
&& sf == SCALE_FACTOR_NORMAL)
|
&& sf == SCALE_FACTOR_NORMAL)
|
||||||
{
|
{
|
||||||
// Only the two bishops ?
|
// Only the two bishops ?
|
||||||
if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
|
if ( pos.non_pawn_material(WHITE) == BishopValueMg
|
||||||
&& pos.non_pawn_material(BLACK) == BishopValueMidgame)
|
&& pos.non_pawn_material(BLACK) == BishopValueMg)
|
||||||
{
|
{
|
||||||
// Check for KBP vs KB with only a single pawn that is almost
|
// Check for KBP vs KB with only a single pawn that is almost
|
||||||
// certainly a draw or at least two pawns.
|
// certainly a draw or at least two pawns.
|
||||||
@@ -357,14 +449,13 @@ Value do_evaluate(const Position& pos, Value& margin) {
|
|||||||
sf = ScaleFactor(50);
|
sf = ScaleFactor(50);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Interpolate between the middle game and the endgame score
|
|
||||||
margin = margins[pos.side_to_move()];
|
margin = margins[pos.side_to_move()];
|
||||||
Value v = scale_by_game_phase(score, ei.mi->game_phase(), sf);
|
Value v = interpolate(score, ei.mi->game_phase(), sf);
|
||||||
|
|
||||||
// In case of tracing add all single evaluation contributions for both white and black
|
// In case of tracing add all single evaluation contributions for both white and black
|
||||||
if (Trace)
|
if (Trace)
|
||||||
{
|
{
|
||||||
trace_add(PST, pos.value());
|
trace_add(PST, pos.psq_score());
|
||||||
trace_add(IMBALANCE, ei.mi->material_value());
|
trace_add(IMBALANCE, ei.mi->material_value());
|
||||||
trace_add(PAWN, ei.pi->pawns_value());
|
trace_add(PAWN, ei.pi->pawns_value());
|
||||||
trace_add(MOBILITY, apply_weight(mobilityWhite, Weights[Mobility]), apply_weight(mobilityBlack, Weights[Mobility]));
|
trace_add(MOBILITY, apply_weight(mobilityWhite, Weights[Mobility]), apply_weight(mobilityBlack, Weights[Mobility]));
|
||||||
@@ -387,34 +478,6 @@ Value do_evaluate(const Position& pos, Value& margin) {
|
|||||||
return pos.side_to_move() == WHITE ? v : -v;
|
return pos.side_to_move() == WHITE ? v : -v;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
|
|
||||||
/// read_weights() reads evaluation weights from the corresponding UCI parameters
|
|
||||||
|
|
||||||
void read_evaluation_uci_options(Color us) {
|
|
||||||
|
|
||||||
// King safety is asymmetrical. Our king danger level is weighted by
|
|
||||||
// "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
|
|
||||||
const int kingDangerUs = (us == WHITE ? KingDangerUs : KingDangerThem);
|
|
||||||
const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
|
|
||||||
|
|
||||||
Weights[Mobility] = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
|
|
||||||
Weights[PassedPawns] = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
|
|
||||||
Weights[Space] = weight_option("Space", "Space", WeightsInternal[Space]);
|
|
||||||
Weights[kingDangerUs] = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
|
|
||||||
Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
|
|
||||||
|
|
||||||
// If running in analysis mode, make sure we use symmetrical king safety. We do this
|
|
||||||
// by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
|
|
||||||
if (Options["UCI_AnalyseMode"])
|
|
||||||
Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
|
|
||||||
|
|
||||||
init_safety();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
|
|
||||||
// init_eval_info() initializes king bitboards for given color adding
|
// init_eval_info() initializes king bitboards for given color adding
|
||||||
// pawn attacks. To be done at the beginning of the evaluation.
|
// pawn attacks. To be done at the beginning of the evaluation.
|
||||||
@@ -429,7 +492,7 @@ namespace {
|
|||||||
|
|
||||||
// Init king safety tables only if we are going to use them
|
// Init king safety tables only if we are going to use them
|
||||||
if ( pos.piece_count(Us, QUEEN)
|
if ( pos.piece_count(Us, QUEEN)
|
||||||
&& pos.non_pawn_material(Us) >= QueenValueMidgame + RookValueMidgame)
|
&& pos.non_pawn_material(Us) > QueenValueMg + PawnValueMg)
|
||||||
{
|
{
|
||||||
ei.kingRing[Them] = (b | (Us == WHITE ? b >> 8 : b << 8));
|
ei.kingRing[Them] = (b | (Us == WHITE ? b >> 8 : b << 8));
|
||||||
b &= ei.attackedBy[Us][PAWN];
|
b &= ei.attackedBy[Us][PAWN];
|
||||||
@@ -454,10 +517,10 @@ namespace {
|
|||||||
|
|
||||||
// Increase bonus if supported by pawn, especially if the opponent has
|
// Increase bonus if supported by pawn, especially if the opponent has
|
||||||
// no minor piece which can exchange the outpost piece.
|
// no minor piece which can exchange the outpost piece.
|
||||||
if (bonus && bit_is_set(ei.attackedBy[Us][PAWN], s))
|
if (bonus && (ei.attackedBy[Us][PAWN] & s))
|
||||||
{
|
{
|
||||||
if ( !pos.pieces(KNIGHT, Them)
|
if ( !pos.pieces(Them, KNIGHT)
|
||||||
&& !(same_color_squares(s) & pos.pieces(BISHOP, Them)))
|
&& !(same_color_squares(s) & pos.pieces(Them, BISHOP)))
|
||||||
bonus += bonus + bonus / 2;
|
bonus += bonus + bonus / 2;
|
||||||
else
|
else
|
||||||
bonus += bonus / 2;
|
bonus += bonus / 2;
|
||||||
@@ -488,16 +551,14 @@ namespace {
|
|||||||
if (Piece == KNIGHT || Piece == QUEEN)
|
if (Piece == KNIGHT || Piece == QUEEN)
|
||||||
b = pos.attacks_from<Piece>(s);
|
b = pos.attacks_from<Piece>(s);
|
||||||
else if (Piece == BISHOP)
|
else if (Piece == BISHOP)
|
||||||
b = bishop_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
|
b = attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN));
|
||||||
else if (Piece == ROOK)
|
else if (Piece == ROOK)
|
||||||
b = rook_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
|
b = attacks_bb<ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN));
|
||||||
else
|
else
|
||||||
assert(false);
|
assert(false);
|
||||||
|
|
||||||
// Update attack info
|
|
||||||
ei.attackedBy[Us][Piece] |= b;
|
ei.attackedBy[Us][Piece] |= b;
|
||||||
|
|
||||||
// King attacks
|
|
||||||
if (b & ei.kingRing[Them])
|
if (b & ei.kingRing[Them])
|
||||||
{
|
{
|
||||||
ei.kingAttackersCount[Us]++;
|
ei.kingAttackersCount[Us]++;
|
||||||
@@ -507,7 +568,6 @@ namespace {
|
|||||||
ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
|
ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mobility
|
|
||||||
mob = (Piece != QUEEN ? popcount<Max15>(b & mobilityArea)
|
mob = (Piece != QUEEN ? popcount<Max15>(b & mobilityArea)
|
||||||
: popcount<Full >(b & mobilityArea));
|
: popcount<Full >(b & mobilityArea));
|
||||||
|
|
||||||
@@ -515,20 +575,37 @@ namespace {
|
|||||||
|
|
||||||
// Decrease score if we are attacked by an enemy pawn. Remaining part
|
// Decrease score if we are attacked by an enemy pawn. Remaining part
|
||||||
// of threat evaluation must be done later when we have full attack info.
|
// of threat evaluation must be done later when we have full attack info.
|
||||||
if (bit_is_set(ei.attackedBy[Them][PAWN], s))
|
if (ei.attackedBy[Them][PAWN] & s)
|
||||||
score -= ThreatenedByPawnPenalty[Piece];
|
score -= ThreatenedByPawnPenalty[Piece];
|
||||||
|
|
||||||
|
// Otherwise give a bonus if we are a bishop and can pin a piece or
|
||||||
|
// can give a discovered check through an x-ray attack.
|
||||||
|
else if ( Piece == BISHOP
|
||||||
|
&& (PseudoAttacks[Piece][pos.king_square(Them)] & s)
|
||||||
|
&& !more_than_one(BetweenBB[s][pos.king_square(Them)] & pos.pieces()))
|
||||||
|
score += BishopPinBonus;
|
||||||
|
|
||||||
|
// Penalty for bishop with same coloured pawns
|
||||||
|
if (Piece == BISHOP)
|
||||||
|
score -= BishopPawnsPenalty * ei.pi->pawns_on_same_color_squares(Us, s);
|
||||||
|
|
||||||
// Bishop and knight outposts squares
|
// Bishop and knight outposts squares
|
||||||
if ( (Piece == BISHOP || Piece == KNIGHT)
|
if ( (Piece == BISHOP || Piece == KNIGHT)
|
||||||
&& !(pos.pieces(PAWN, Them) & attack_span_mask(Us, s)))
|
&& !(pos.pieces(Them, PAWN) & attack_span_mask(Us, s)))
|
||||||
score += evaluate_outposts<Piece, Us>(pos, ei, s);
|
score += evaluate_outposts<Piece, Us>(pos, ei, s);
|
||||||
|
|
||||||
// Queen or rook on 7th rank
|
if ((Piece == ROOK || Piece == QUEEN) && relative_rank(Us, s) >= RANK_5)
|
||||||
if ( (Piece == ROOK || Piece == QUEEN)
|
|
||||||
&& relative_rank(Us, s) == RANK_7
|
|
||||||
&& relative_rank(Us, pos.king_square(Them)) == RANK_8)
|
|
||||||
{
|
{
|
||||||
|
// Major piece on 7th rank
|
||||||
|
if ( relative_rank(Us, s) == RANK_7
|
||||||
|
&& relative_rank(Us, pos.king_square(Them)) == RANK_8)
|
||||||
score += (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
|
score += (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
|
||||||
|
|
||||||
|
// Major piece attacking pawns on the same rank
|
||||||
|
Bitboard pawns = pos.pieces(Them, PAWN) & rank_bb(s);
|
||||||
|
if (pawns)
|
||||||
|
score += (Piece == ROOK ? RookOnPawnBonus
|
||||||
|
: QueenOnPawnBonus) * popcount<Max15>(pawns);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Special extra evaluation for bishops
|
// Special extra evaluation for bishops
|
||||||
@@ -542,7 +619,7 @@ namespace {
|
|||||||
Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
|
Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
|
||||||
if (pos.piece_on(s + d) == make_piece(Us, PAWN))
|
if (pos.piece_on(s + d) == make_piece(Us, PAWN))
|
||||||
{
|
{
|
||||||
if (!pos.square_is_empty(s + d + pawn_push(Us)))
|
if (!pos.is_empty(s + d + pawn_push(Us)))
|
||||||
score -= 2*TrappedBishopA1H1Penalty;
|
score -= 2*TrappedBishopA1H1Penalty;
|
||||||
else if (pos.piece_on(s + 2*d) == make_piece(Us, PAWN))
|
else if (pos.piece_on(s + 2*d) == make_piece(Us, PAWN))
|
||||||
score -= TrappedBishopA1H1Penalty;
|
score -= TrappedBishopA1H1Penalty;
|
||||||
@@ -608,15 +685,24 @@ namespace {
|
|||||||
|
|
||||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
|
|
||||||
Bitboard b;
|
Bitboard b, undefendedMinors, weakEnemies;
|
||||||
Score score = SCORE_ZERO;
|
Score score = SCORE_ZERO;
|
||||||
|
|
||||||
|
// Undefended minors get penalized even if not under attack
|
||||||
|
undefendedMinors = pos.pieces(Them)
|
||||||
|
& (pos.pieces(BISHOP) | pos.pieces(KNIGHT))
|
||||||
|
& ~ei.attackedBy[Them][ALL_PIECES];
|
||||||
|
|
||||||
|
if (undefendedMinors)
|
||||||
|
score += UndefendedMinorPenalty;
|
||||||
|
|
||||||
// Enemy pieces not defended by a pawn and under our attack
|
// Enemy pieces not defended by a pawn and under our attack
|
||||||
Bitboard weakEnemies = pos.pieces(Them)
|
weakEnemies = pos.pieces(Them)
|
||||||
& ~ei.attackedBy[Them][PAWN]
|
& ~ei.attackedBy[Them][PAWN]
|
||||||
& ei.attackedBy[Us][0];
|
& ei.attackedBy[Us][ALL_PIECES];
|
||||||
|
|
||||||
if (!weakEnemies)
|
if (!weakEnemies)
|
||||||
return SCORE_ZERO;
|
return score;
|
||||||
|
|
||||||
// Add bonus according to type of attacked enemy piece and to the
|
// Add bonus according to type of attacked enemy piece and to the
|
||||||
// type of attacking piece, from knights to queens. Kings are not
|
// type of attacking piece, from knights to queens. Kings are not
|
||||||
@@ -652,7 +738,7 @@ namespace {
|
|||||||
score += evaluate_pieces<QUEEN, Us, Trace>(pos, ei, mobility, mobilityArea);
|
score += evaluate_pieces<QUEEN, Us, Trace>(pos, ei, mobility, mobilityArea);
|
||||||
|
|
||||||
// Sum up all attacked squares
|
// Sum up all attacked squares
|
||||||
ei.attackedBy[Us][0] = ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
|
ei.attackedBy[Us][ALL_PIECES] = ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
|
||||||
| ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
|
| ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
|
||||||
| ei.attackedBy[Us][QUEEN] | ei.attackedBy[Us][KING];
|
| ei.attackedBy[Us][QUEEN] | ei.attackedBy[Us][KING];
|
||||||
return score;
|
return score;
|
||||||
@@ -670,8 +756,8 @@ namespace {
|
|||||||
int attackUnits;
|
int attackUnits;
|
||||||
const Square ksq = pos.king_square(Us);
|
const Square ksq = pos.king_square(Us);
|
||||||
|
|
||||||
// King shelter
|
// King shelter and enemy pawns storm
|
||||||
Score score = ei.pi->king_shelter<Us>(pos, ksq);
|
Score score = ei.pi->king_safety<Us>(pos, ksq);
|
||||||
|
|
||||||
// King safety. This is quite complicated, and is almost certainly far
|
// King safety. This is quite complicated, and is almost certainly far
|
||||||
// from optimally tuned.
|
// from optimally tuned.
|
||||||
@@ -680,7 +766,7 @@ namespace {
|
|||||||
{
|
{
|
||||||
// Find the attacked squares around the king which has no defenders
|
// Find the attacked squares around the king which has no defenders
|
||||||
// apart from the king itself
|
// apart from the king itself
|
||||||
undefended = ei.attackedBy[Them][0] & ei.attackedBy[Us][KING];
|
undefended = ei.attackedBy[Them][ALL_PIECES] & ei.attackedBy[Us][KING];
|
||||||
undefended &= ~( ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
|
undefended &= ~( ei.attackedBy[Us][PAWN] | ei.attackedBy[Us][KNIGHT]
|
||||||
| ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
|
| ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
|
||||||
| ei.attackedBy[Us][QUEEN]);
|
| ei.attackedBy[Us][QUEEN]);
|
||||||
@@ -693,7 +779,7 @@ namespace {
|
|||||||
attackUnits = std::min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
|
attackUnits = std::min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
|
||||||
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + popcount<Max15>(undefended))
|
+ 3 * (ei.kingAdjacentZoneAttacksCount[Them] + popcount<Max15>(undefended))
|
||||||
+ InitKingDanger[relative_square(Us, ksq)]
|
+ InitKingDanger[relative_square(Us, ksq)]
|
||||||
- mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32;
|
- mg_value(score) / 32;
|
||||||
|
|
||||||
// Analyse enemy's safe queen contact checks. First find undefended
|
// Analyse enemy's safe queen contact checks. First find undefended
|
||||||
// squares around the king attacked by enemy queen...
|
// squares around the king attacked by enemy queen...
|
||||||
@@ -714,7 +800,7 @@ namespace {
|
|||||||
b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces(Them);
|
b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces(Them);
|
||||||
|
|
||||||
// Consider only squares where the enemy rook gives check
|
// Consider only squares where the enemy rook gives check
|
||||||
b &= RookPseudoAttacks[ksq];
|
b &= PseudoAttacks[ROOK][ksq];
|
||||||
|
|
||||||
if (b)
|
if (b)
|
||||||
{
|
{
|
||||||
@@ -728,7 +814,7 @@ namespace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Analyse enemy's safe distance checks for sliders and knights
|
// Analyse enemy's safe distance checks for sliders and knights
|
||||||
safe = ~(pos.pieces(Them) | ei.attackedBy[Us][0]);
|
safe = ~(pos.pieces(Them) | ei.attackedBy[Us][ALL_PIECES]);
|
||||||
|
|
||||||
b1 = pos.attacks_from<ROOK>(ksq) & safe;
|
b1 = pos.attacks_from<ROOK>(ksq) & safe;
|
||||||
b2 = pos.attacks_from<BISHOP>(ksq) & safe;
|
b2 = pos.attacks_from<BISHOP>(ksq) & safe;
|
||||||
@@ -761,8 +847,8 @@ namespace {
|
|||||||
// value that will be used for pruning because this value can sometimes
|
// value that will be used for pruning because this value can sometimes
|
||||||
// be very big, and so capturing a single attacking piece can therefore
|
// be very big, and so capturing a single attacking piece can therefore
|
||||||
// result in a score change far bigger than the value of the captured piece.
|
// result in a score change far bigger than the value of the captured piece.
|
||||||
score -= KingDangerTable[Us][attackUnits];
|
score -= KingDangerTable[Us == Search::RootColor][attackUnits];
|
||||||
margins[Us] += mg_value(KingDangerTable[Us][attackUnits]);
|
margins[Us] += mg_value(KingDangerTable[Us == Search::RootColor][attackUnits]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Trace)
|
if (Trace)
|
||||||
@@ -788,7 +874,7 @@ namespace {
|
|||||||
return SCORE_ZERO;
|
return SCORE_ZERO;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
Square s = pop_1st_bit(&b);
|
Square s = pop_lsb(&b);
|
||||||
|
|
||||||
assert(pos.pawn_is_passed(Us, s));
|
assert(pos.pawn_is_passed(Us, s));
|
||||||
|
|
||||||
@@ -812,19 +898,19 @@ namespace {
|
|||||||
ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * rr);
|
ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * rr);
|
||||||
|
|
||||||
// If the pawn is free to advance, increase bonus
|
// If the pawn is free to advance, increase bonus
|
||||||
if (pos.square_is_empty(blockSq))
|
if (pos.is_empty(blockSq))
|
||||||
{
|
{
|
||||||
squaresToQueen = squares_in_front_of(Us, s);
|
squaresToQueen = forward_bb(Us, s);
|
||||||
defendedSquares = squaresToQueen & ei.attackedBy[Us][0];
|
defendedSquares = squaresToQueen & ei.attackedBy[Us][ALL_PIECES];
|
||||||
|
|
||||||
// If there is an enemy rook or queen attacking the pawn from behind,
|
// If there is an enemy rook or queen attacking the pawn from behind,
|
||||||
// add all X-ray attacks by the rook or queen. Otherwise consider only
|
// add all X-ray attacks by the rook or queen. Otherwise consider only
|
||||||
// the squares in the pawn's path attacked or occupied by the enemy.
|
// the squares in the pawn's path attacked or occupied by the enemy.
|
||||||
if ( (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them))
|
if ( (forward_bb(Them, s) & pos.pieces(Them, ROOK, QUEEN))
|
||||||
&& (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
|
&& (forward_bb(Them, s) & pos.pieces(Them, ROOK, QUEEN) & pos.attacks_from<ROOK>(s)))
|
||||||
unsafeSquares = squaresToQueen;
|
unsafeSquares = squaresToQueen;
|
||||||
else
|
else
|
||||||
unsafeSquares = squaresToQueen & (ei.attackedBy[Them][0] | pos.pieces(Them));
|
unsafeSquares = squaresToQueen & (ei.attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
|
||||||
|
|
||||||
// If there aren't enemy attacks or pieces along the path to queen give
|
// If there aren't enemy attacks or pieces along the path to queen give
|
||||||
// huge bonus. Even bigger if we protect the pawn's path.
|
// huge bonus. Even bigger if we protect the pawn's path.
|
||||||
@@ -841,7 +927,7 @@ namespace {
|
|||||||
|
|
||||||
// Increase the bonus if the passed pawn is supported by a friendly pawn
|
// Increase the bonus if the passed pawn is supported by a friendly pawn
|
||||||
// on the same rank and a bit smaller if it's on the previous rank.
|
// on the same rank and a bit smaller if it's on the previous rank.
|
||||||
supportingPawns = pos.pieces(PAWN, Us) & neighboring_files_bb(file_of(s));
|
supportingPawns = pos.pieces(Us, PAWN) & adjacent_files_bb(file_of(s));
|
||||||
if (supportingPawns & rank_bb(s))
|
if (supportingPawns & rank_bb(s))
|
||||||
ebonus += Value(r * 20);
|
ebonus += Value(r * 20);
|
||||||
|
|
||||||
@@ -856,9 +942,9 @@ namespace {
|
|||||||
// value if the other side has a rook or queen.
|
// value if the other side has a rook or queen.
|
||||||
if (file_of(s) == FILE_A || file_of(s) == FILE_H)
|
if (file_of(s) == FILE_A || file_of(s) == FILE_H)
|
||||||
{
|
{
|
||||||
if (pos.non_pawn_material(Them) <= KnightValueMidgame)
|
if (pos.non_pawn_material(Them) <= KnightValueMg)
|
||||||
ebonus += ebonus / 4;
|
ebonus += ebonus / 4;
|
||||||
else if (pos.pieces(ROOK, QUEEN, Them))
|
else if (pos.pieces(Them, ROOK, QUEEN))
|
||||||
ebonus -= ebonus / 4;
|
ebonus -= ebonus / 4;
|
||||||
}
|
}
|
||||||
score += make_score(mbonus, ebonus);
|
score += make_score(mbonus, ebonus);
|
||||||
@@ -887,29 +973,29 @@ namespace {
|
|||||||
for (c = WHITE; c <= BLACK; c++)
|
for (c = WHITE; c <= BLACK; c++)
|
||||||
{
|
{
|
||||||
// Skip if other side has non-pawn pieces
|
// Skip if other side has non-pawn pieces
|
||||||
if (pos.non_pawn_material(flip(c)))
|
if (pos.non_pawn_material(~c))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
b = ei.pi->passed_pawns(c);
|
b = ei.pi->passed_pawns(c);
|
||||||
|
|
||||||
while (b)
|
while (b)
|
||||||
{
|
{
|
||||||
s = pop_1st_bit(&b);
|
s = pop_lsb(&b);
|
||||||
queeningSquare = relative_square(c, make_square(file_of(s), RANK_8));
|
queeningSquare = relative_square(c, file_of(s) | RANK_8);
|
||||||
queeningPath = squares_in_front_of(c, s);
|
queeningPath = forward_bb(c, s);
|
||||||
|
|
||||||
// Compute plies to queening and check direct advancement
|
// Compute plies to queening and check direct advancement
|
||||||
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(c, s) == RANK_2);
|
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(c, s) == RANK_2);
|
||||||
oppMovesToGo = square_distance(pos.king_square(flip(c)), queeningSquare) - int(c != pos.side_to_move());
|
oppMovesToGo = square_distance(pos.king_square(~c), queeningSquare) - int(c != pos.side_to_move());
|
||||||
pathDefended = ((ei.attackedBy[c][0] & queeningPath) == queeningPath);
|
pathDefended = ((ei.attackedBy[c][ALL_PIECES] & queeningPath) == queeningPath);
|
||||||
|
|
||||||
if (movesToGo >= oppMovesToGo && !pathDefended)
|
if (movesToGo >= oppMovesToGo && !pathDefended)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
// Opponent king cannot block because path is defended and position
|
// Opponent king cannot block because path is defended and position
|
||||||
// is not in check. So only friendly pieces can be blockers.
|
// is not in check. So only friendly pieces can be blockers.
|
||||||
assert(!pos.in_check());
|
assert(!pos.checkers());
|
||||||
assert((queeningPath & pos.occupied_squares()) == (queeningPath & pos.pieces(c)));
|
assert((queeningPath & pos.pieces()) == (queeningPath & pos.pieces(c)));
|
||||||
|
|
||||||
// Add moves needed to free the path from friendly pieces and retest condition
|
// Add moves needed to free the path from friendly pieces and retest condition
|
||||||
movesToGo += popcount<Max15>(queeningPath & pos.pieces(c));
|
movesToGo += popcount<Max15>(queeningPath & pos.pieces(c));
|
||||||
@@ -928,24 +1014,24 @@ namespace {
|
|||||||
return SCORE_ZERO;
|
return SCORE_ZERO;
|
||||||
|
|
||||||
winnerSide = (pliesToQueen[WHITE] < pliesToQueen[BLACK] ? WHITE : BLACK);
|
winnerSide = (pliesToQueen[WHITE] < pliesToQueen[BLACK] ? WHITE : BLACK);
|
||||||
loserSide = flip(winnerSide);
|
loserSide = ~winnerSide;
|
||||||
|
|
||||||
// Step 3. Can the losing side possibly create a new passed pawn and thus prevent the loss?
|
// Step 3. Can the losing side possibly create a new passed pawn and thus prevent the loss?
|
||||||
b = candidates = pos.pieces(PAWN, loserSide);
|
b = candidates = pos.pieces(loserSide, PAWN);
|
||||||
|
|
||||||
while (b)
|
while (b)
|
||||||
{
|
{
|
||||||
s = pop_1st_bit(&b);
|
s = pop_lsb(&b);
|
||||||
|
|
||||||
// Compute plies from queening
|
// Compute plies from queening
|
||||||
queeningSquare = relative_square(loserSide, make_square(file_of(s), RANK_8));
|
queeningSquare = relative_square(loserSide, file_of(s) | RANK_8);
|
||||||
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
|
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
|
||||||
pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
|
pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
|
||||||
|
|
||||||
// Check if (without even considering any obstacles) we're too far away or doubled
|
// Check if (without even considering any obstacles) we're too far away or doubled
|
||||||
if ( pliesToQueen[winnerSide] + 3 <= pliesToGo
|
if ( pliesToQueen[winnerSide] + 3 <= pliesToGo
|
||||||
|| (squares_in_front_of(loserSide, s) & pos.pieces(PAWN, loserSide)))
|
|| (forward_bb(loserSide, s) & pos.pieces(loserSide, PAWN)))
|
||||||
clear_bit(&candidates, s);
|
candidates ^= s;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If any candidate is already a passed pawn it _may_ promote in time. We give up.
|
// If any candidate is already a passed pawn it _may_ promote in time. We give up.
|
||||||
@@ -957,26 +1043,26 @@ namespace {
|
|||||||
|
|
||||||
while (b)
|
while (b)
|
||||||
{
|
{
|
||||||
s = pop_1st_bit(&b);
|
s = pop_lsb(&b);
|
||||||
sacptg = blockersCount = 0;
|
sacptg = blockersCount = 0;
|
||||||
minKingDist = kingptg = 256;
|
minKingDist = kingptg = 256;
|
||||||
|
|
||||||
// Compute plies from queening
|
// Compute plies from queening
|
||||||
queeningSquare = relative_square(loserSide, make_square(file_of(s), RANK_8));
|
queeningSquare = relative_square(loserSide, file_of(s) | RANK_8);
|
||||||
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
|
movesToGo = rank_distance(s, queeningSquare) - int(relative_rank(loserSide, s) == RANK_2);
|
||||||
pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
|
pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
|
||||||
|
|
||||||
// Generate list of blocking pawns and supporters
|
// Generate list of blocking pawns and supporters
|
||||||
supporters = neighboring_files_bb(file_of(s)) & candidates;
|
supporters = adjacent_files_bb(file_of(s)) & candidates;
|
||||||
opposed = squares_in_front_of(loserSide, s) & pos.pieces(PAWN, winnerSide);
|
opposed = forward_bb(loserSide, s) & pos.pieces(winnerSide, PAWN);
|
||||||
blockers = passed_pawn_mask(loserSide, s) & pos.pieces(PAWN, winnerSide);
|
blockers = passed_pawn_mask(loserSide, s) & pos.pieces(winnerSide, PAWN);
|
||||||
|
|
||||||
assert(blockers);
|
assert(blockers);
|
||||||
|
|
||||||
// How many plies does it take to remove all the blocking pawns?
|
// How many plies does it take to remove all the blocking pawns?
|
||||||
while (blockers)
|
while (blockers)
|
||||||
{
|
{
|
||||||
blockSq = pop_1st_bit(&blockers);
|
blockSq = pop_lsb(&blockers);
|
||||||
movesToGo = 256;
|
movesToGo = 256;
|
||||||
|
|
||||||
// Check pawns that can give support to overcome obstacle, for instance
|
// Check pawns that can give support to overcome obstacle, for instance
|
||||||
@@ -987,7 +1073,7 @@ namespace {
|
|||||||
|
|
||||||
while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
|
while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
|
||||||
{
|
{
|
||||||
d = square_distance(blockSq, pop_1st_bit(&b2)) - 2;
|
d = square_distance(blockSq, pop_lsb(&b2)) - 2;
|
||||||
movesToGo = std::min(movesToGo, d);
|
movesToGo = std::min(movesToGo, d);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -997,7 +1083,7 @@ namespace {
|
|||||||
|
|
||||||
while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
|
while (b2) // This while-loop could be replaced with LSB/MSB (depending on color)
|
||||||
{
|
{
|
||||||
d = square_distance(blockSq, pop_1st_bit(&b2)) - 2;
|
d = square_distance(blockSq, pop_lsb(&b2)) - 2;
|
||||||
movesToGo = std::min(movesToGo, d);
|
movesToGo = std::min(movesToGo, d);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1026,7 +1112,7 @@ namespace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Winning pawn is unstoppable and will promote as first, return big score
|
// Winning pawn is unstoppable and will promote as first, return big score
|
||||||
Score score = make_score(0, (Value) 0x500 - 0x20 * pliesToQueen[winnerSide]);
|
Score score = make_score(0, (Value) 1280 - 32 * pliesToQueen[winnerSide]);
|
||||||
return winnerSide == WHITE ? score : -score;
|
return winnerSide == WHITE ? score : -score;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1046,31 +1132,27 @@ namespace {
|
|||||||
// SpaceMask[]. A square is unsafe if it is attacked by an enemy
|
// SpaceMask[]. A square is unsafe if it is attacked by an enemy
|
||||||
// pawn, or if it is undefended and attacked by an enemy piece.
|
// pawn, or if it is undefended and attacked by an enemy piece.
|
||||||
Bitboard safe = SpaceMask[Us]
|
Bitboard safe = SpaceMask[Us]
|
||||||
& ~pos.pieces(PAWN, Us)
|
& ~pos.pieces(Us, PAWN)
|
||||||
& ~ei.attackedBy[Them][PAWN]
|
& ~ei.attackedBy[Them][PAWN]
|
||||||
& (ei.attackedBy[Us][0] | ~ei.attackedBy[Them][0]);
|
& (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
|
||||||
|
|
||||||
// Find all squares which are at most three squares behind some friendly pawn
|
// Find all squares which are at most three squares behind some friendly pawn
|
||||||
Bitboard behind = pos.pieces(PAWN, Us);
|
Bitboard behind = pos.pieces(Us, PAWN);
|
||||||
behind |= (Us == WHITE ? behind >> 8 : behind << 8);
|
behind |= (Us == WHITE ? behind >> 8 : behind << 8);
|
||||||
behind |= (Us == WHITE ? behind >> 16 : behind << 16);
|
behind |= (Us == WHITE ? behind >> 16 : behind << 16);
|
||||||
|
|
||||||
return popcount<Max15>(safe) + popcount<Max15>(behind & safe);
|
// Since SpaceMask[Us] is fully on our half of the board
|
||||||
|
assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
|
||||||
|
|
||||||
|
// Count safe + (behind & safe) with a single popcount
|
||||||
|
return popcount<Full>((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// apply_weight() applies an evaluation weight to a value trying to prevent overflow
|
// interpolate() interpolates between a middle game and an endgame score,
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// scale_by_game_phase() interpolates between a middle game and an endgame score,
|
|
||||||
// based on game phase. It also scales the return value by a ScaleFactor array.
|
// based on game phase. It also scales the return value by a ScaleFactor array.
|
||||||
|
|
||||||
Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf) {
|
Value interpolate(const Score& v, Phase ph, ScaleFactor sf) {
|
||||||
|
|
||||||
assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
|
assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
|
||||||
assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
|
assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
|
||||||
@@ -1095,37 +1177,10 @@ namespace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// init_safety() initizes the king safety evaluation, based on UCI
|
|
||||||
// parameters. It is called from read_weights().
|
|
||||||
|
|
||||||
void init_safety() {
|
|
||||||
|
|
||||||
const Value MaxSlope = Value(30);
|
|
||||||
const Value Peak = Value(1280);
|
|
||||||
Value t[100];
|
|
||||||
|
|
||||||
// First setup the base table
|
|
||||||
for (int i = 0; i < 100; i++)
|
|
||||||
{
|
|
||||||
t[i] = Value(int(0.4 * i * i));
|
|
||||||
|
|
||||||
if (i > 0)
|
|
||||||
t[i] = std::min(t[i], t[i - 1] + MaxSlope);
|
|
||||||
|
|
||||||
t[i] = std::min(t[i], Peak);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then apply the weights and get the final KingDangerTable[] array
|
|
||||||
for (Color c = WHITE; c <= BLACK; c++)
|
|
||||||
for (int i = 0; i < 100; i++)
|
|
||||||
KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// A couple of little helpers used by tracing code, to_cp() converts a value to
|
// A couple of little helpers used by tracing code, to_cp() converts a value to
|
||||||
// a double in centipawns scale, trace_add() stores white and black scores.
|
// a double in centipawns scale, trace_add() stores white and black scores.
|
||||||
|
|
||||||
double to_cp(Value v) { return double(v) / double(PawnValueMidgame); }
|
double to_cp(Value v) { return double(v) / double(PawnValueMg); }
|
||||||
|
|
||||||
void trace_add(int idx, Score wScore, Score bScore) {
|
void trace_add(int idx, Score wScore, Score bScore) {
|
||||||
|
|
||||||
@@ -1133,6 +1188,7 @@ namespace {
|
|||||||
TracedScores[BLACK][idx] = bScore;
|
TracedScores[BLACK][idx] = bScore;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// trace_row() is an helper function used by tracing code to register the
|
// trace_row() is an helper function used by tracing code to register the
|
||||||
// values of a single evaluation term.
|
// values of a single evaluation term.
|
||||||
|
|
||||||
@@ -1159,47 +1215,3 @@ namespace {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// trace_evaluate() is like evaluate() but instead of a value returns a string
|
|
||||||
/// suitable to be print on stdout with the detailed descriptions and values of
|
|
||||||
/// each evaluation term. Used mainly for debugging.
|
|
||||||
|
|
||||||
std::string trace_evaluate(const Position& pos) {
|
|
||||||
|
|
||||||
Value margin;
|
|
||||||
std::string totals;
|
|
||||||
|
|
||||||
TraceStream.str("");
|
|
||||||
TraceStream << std::showpoint << std::showpos << std::fixed << std::setprecision(2);
|
|
||||||
memset(TracedScores, 0, 2 * 16 * sizeof(Score));
|
|
||||||
|
|
||||||
do_evaluate<true>(pos, margin);
|
|
||||||
|
|
||||||
totals = TraceStream.str();
|
|
||||||
TraceStream.str("");
|
|
||||||
|
|
||||||
TraceStream << std::setw(21) << "Eval term " << "| White | Black | Total \n"
|
|
||||||
<< " | MG EG | MG EG | MG EG \n"
|
|
||||||
<< "---------------------+-------------+-------------+---------------\n";
|
|
||||||
|
|
||||||
trace_row("Material, PST, Tempo", PST);
|
|
||||||
trace_row("Material imbalance", IMBALANCE);
|
|
||||||
trace_row("Pawns", PAWN);
|
|
||||||
trace_row("Knights", KNIGHT);
|
|
||||||
trace_row("Bishops", BISHOP);
|
|
||||||
trace_row("Rooks", ROOK);
|
|
||||||
trace_row("Queens", QUEEN);
|
|
||||||
trace_row("Mobility", MOBILITY);
|
|
||||||
trace_row("King safety", KING);
|
|
||||||
trace_row("Threats", THREAT);
|
|
||||||
trace_row("Passed pawns", PASSED);
|
|
||||||
trace_row("Unstoppable pawns", UNSTOPPABLE);
|
|
||||||
trace_row("Space", SPACE);
|
|
||||||
|
|
||||||
TraceStream << "---------------------+-------------+-------------+---------------\n";
|
|
||||||
trace_row("Total", TOTAL);
|
|
||||||
TraceStream << totals;
|
|
||||||
|
|
||||||
return TraceStream.str();
|
|
||||||
}
|
|
||||||
|
|||||||
+7
-3
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -24,8 +24,12 @@
|
|||||||
|
|
||||||
class Position;
|
class Position;
|
||||||
|
|
||||||
|
namespace Eval {
|
||||||
|
|
||||||
|
extern void init();
|
||||||
extern Value evaluate(const Position& pos, Value& margin);
|
extern Value evaluate(const Position& pos, Value& margin);
|
||||||
extern std::string trace_evaluate(const Position& pos);
|
extern std::string trace(const Position& pos);
|
||||||
extern void read_evaluation_uci_options(Color sideToMove);
|
|
||||||
|
}
|
||||||
|
|
||||||
#endif // !defined(EVALUATE_H_INCLUDED)
|
#endif // !defined(EVALUATE_H_INCLUDED)
|
||||||
|
|||||||
@@ -1,71 +0,0 @@
|
|||||||
/*
|
|
||||||
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(HISTORY_H_INCLUDED)
|
|
||||||
#define HISTORY_H_INCLUDED
|
|
||||||
|
|
||||||
#include "types.h"
|
|
||||||
#include <cstring>
|
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
/// The History class stores statistics about how often different moves
|
|
||||||
/// have been successful or unsuccessful during the current search. These
|
|
||||||
/// statistics are used for reduction and move ordering decisions. History
|
|
||||||
/// entries are stored according only to moving piece and destination square,
|
|
||||||
/// in particular two moves with different origin but same destination and
|
|
||||||
/// same piece will be considered identical.
|
|
||||||
|
|
||||||
class History {
|
|
||||||
|
|
||||||
public:
|
|
||||||
void clear();
|
|
||||||
Value value(Piece p, Square to) const;
|
|
||||||
void add(Piece p, Square to, Value bonus);
|
|
||||||
Value gain(Piece p, Square to) const;
|
|
||||||
void update_gain(Piece p, Square to, Value g);
|
|
||||||
|
|
||||||
static const Value MaxValue = Value(2000);
|
|
||||||
|
|
||||||
private:
|
|
||||||
Value history[16][64]; // [piece][to_square]
|
|
||||||
Value maxGains[16][64]; // [piece][to_square]
|
|
||||||
};
|
|
||||||
|
|
||||||
inline void History::clear() {
|
|
||||||
memset(history, 0, 16 * 64 * sizeof(Value));
|
|
||||||
memset(maxGains, 0, 16 * 64 * sizeof(Value));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Value History::value(Piece p, Square to) const {
|
|
||||||
return history[p][to];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void History::add(Piece p, Square to, Value bonus) {
|
|
||||||
if (abs(history[p][to] + bonus) < MaxValue) history[p][to] += bonus;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Value History::gain(Piece p, Square to) const {
|
|
||||||
return maxGains[p][to];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void History::update_gain(Piece p, Square to, Value g) {
|
|
||||||
maxGains[p][to] = std::max(g, maxGains[p][to] - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // !defined(HISTORY_H_INCLUDED)
|
|
||||||
-85
@@ -1,85 +0,0 @@
|
|||||||
/*
|
|
||||||
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(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)
|
|
||||||
# define cond_timedwait(x,y,z) pthread_cond_timedwait(x,y,z)
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
#define NOMINMAX // disable macros min() and max()
|
|
||||||
#define WIN32_LEAN_AND_MEAN
|
|
||||||
#include <windows.h>
|
|
||||||
#undef WIN32_LEAN_AND_MEAN
|
|
||||||
#undef NOMINMAX
|
|
||||||
|
|
||||||
// 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)
|
|
||||||
# define cond_timedwait(x,y,z) SleepConditionVariableSRW(x,y,z,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) { ResetEvent(*x); lock_release(y); WaitForSingleObject(*x, INFINITE); lock_grab(y); }
|
|
||||||
# define cond_timedwait(x,y,z) { ResetEvent(*x); lock_release(y); WaitForSingleObject(*x,z); lock_grab(y); }
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif // !defined(LOCK_H_INCLUDED)
|
|
||||||
+16
-21
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -21,37 +21,32 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
#include "misc.h"
|
#include "evaluate.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
|
#include "tt.h"
|
||||||
using namespace std;
|
#include "ucioption.h"
|
||||||
|
|
||||||
extern void uci_loop();
|
|
||||||
extern void benchmark(int argc, char* argv[]);
|
|
||||||
extern void kpk_bitbase_init();
|
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
int main(int argc, char* argv[]) {
|
||||||
|
|
||||||
bitboards_init();
|
std::cout << engine_info() << std::endl;
|
||||||
Position::init();
|
|
||||||
kpk_bitbase_init();
|
UCI::init(Options);
|
||||||
|
Bitboards::init();
|
||||||
|
Zobrist::init();
|
||||||
|
Bitbases::init_kpk();
|
||||||
Search::init();
|
Search::init();
|
||||||
|
Eval::init();
|
||||||
Threads.init();
|
Threads.init();
|
||||||
|
TT.set_size(Options["Hash"]);
|
||||||
|
|
||||||
cout << engine_info() << endl;
|
std::string args;
|
||||||
|
|
||||||
if (argc == 1)
|
for (int i = 1; i < argc; i++)
|
||||||
uci_loop();
|
args += std::string(argv[i]) + " ";
|
||||||
|
|
||||||
else if (string(argv[1]) == "bench")
|
UCI::loop(args);
|
||||||
benchmark(argc, argv);
|
|
||||||
|
|
||||||
else
|
|
||||||
cerr << "\nUsage: stockfish bench [hash size = 128] [threads = 1] "
|
|
||||||
<< "[limit = 12] [fen positions file = default] "
|
|
||||||
<< "[limited by depth, time, nodes or perft = depth]" << endl;
|
|
||||||
|
|
||||||
Threads.exit();
|
Threads.exit();
|
||||||
}
|
}
|
||||||
|
|||||||
+177
-171
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -17,9 +17,9 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <algorithm> // For std::min
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
#include "material.h"
|
#include "material.h"
|
||||||
|
|
||||||
@@ -38,15 +38,29 @@ namespace {
|
|||||||
const Value RedundantQueenPenalty = Value(320);
|
const Value RedundantQueenPenalty = Value(320);
|
||||||
const Value RedundantRookPenalty = Value(554);
|
const Value RedundantRookPenalty = Value(554);
|
||||||
|
|
||||||
|
// pair pawn knight bishop rook queen
|
||||||
const int LinearCoefficients[6] = { 1617, -162, -1172, -190, 105, 26 };
|
const int LinearCoefficients[6] = { 1617, -162, -1172, -190, 105, 26 };
|
||||||
|
|
||||||
const int QuadraticCoefficientsSameColor[][8] = {
|
const int QuadraticCoefficientsSameColor[][PIECE_TYPE_NB] = {
|
||||||
{ 7, 7, 7, 7, 7, 7 }, { 39, 2, 7, 7, 7, 7 }, { 35, 271, -4, 7, 7, 7 },
|
// pair pawn knight bishop rook queen
|
||||||
{ 7, 25, 4, 7, 7, 7 }, { -27, -2, 46, 100, 56, 7 }, { 58, 29, 83, 148, -3, -25 } };
|
{ 7 }, // Bishop pair
|
||||||
|
{ 39, 2 }, // Pawn
|
||||||
|
{ 35, 271, -4 }, // Knight
|
||||||
|
{ 7, 105, 4, 7 }, // Bishop
|
||||||
|
{ -27, -2, 46, 100, 56 }, // Rook
|
||||||
|
{ 58, 29, 83, 148, -3, -25 } // Queen
|
||||||
|
};
|
||||||
|
|
||||||
const int QuadraticCoefficientsOppositeColor[][8] = {
|
const int QuadraticCoefficientsOppositeColor[][PIECE_TYPE_NB] = {
|
||||||
{ 41, 41, 41, 41, 41, 41 }, { 37, 41, 41, 41, 41, 41 }, { 10, 62, 41, 41, 41, 41 },
|
// THEIR PIECES
|
||||||
{ 57, 64, 39, 41, 41, 41 }, { 50, 40, 23, -22, 41, 41 }, { 106, 101, 3, 151, 171, 41 } };
|
// pair pawn knight bishop rook queen
|
||||||
|
{ 41 }, // Bishop pair
|
||||||
|
{ 37, 41 }, // Pawn
|
||||||
|
{ 10, 62, 41 }, // Knight OUR PIECES
|
||||||
|
{ 57, 64, 39, 41 }, // Bishop
|
||||||
|
{ 50, 40, 23, -22, 41 }, // Rook
|
||||||
|
{ 106, 101, 3, 151, 171, 41 } // Queen
|
||||||
|
};
|
||||||
|
|
||||||
// Endgame evaluation and scaling functions accessed direcly and not through
|
// Endgame evaluation and scaling functions accessed direcly and not through
|
||||||
// the function maps because correspond to more then one material hash key.
|
// the function maps because correspond to more then one material hash key.
|
||||||
@@ -63,11 +77,11 @@ namespace {
|
|||||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
return pos.non_pawn_material(Them) == VALUE_ZERO
|
return pos.non_pawn_material(Them) == VALUE_ZERO
|
||||||
&& pos.piece_count(Them, PAWN) == 0
|
&& 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) {
|
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, BISHOP) == 1
|
||||||
&& pos.piece_count(Us, PAWN) >= 1;
|
&& pos.piece_count(Us, PAWN) >= 1;
|
||||||
}
|
}
|
||||||
@@ -75,172 +89,17 @@ namespace {
|
|||||||
template<Color Us> bool is_KQKRPs(const Position& pos) {
|
template<Color Us> bool is_KQKRPs(const Position& pos) {
|
||||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
return pos.piece_count(Us, PAWN) == 0
|
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(Us, QUEEN) == 1
|
||||||
&& pos.piece_count(Them, ROOK) == 1
|
&& pos.piece_count(Them, ROOK) == 1
|
||||||
&& pos.piece_count(Them, PAWN) >= 1;
|
&& pos.piece_count(Them, PAWN) >= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
/// imbalance() calculates imbalance comparing piece count of each
|
||||||
|
|
||||||
|
|
||||||
/// MaterialInfoTable c'tor and d'tor allocate and free the space for Endgames
|
|
||||||
|
|
||||||
void MaterialInfoTable::init() { Base::init(); if (!funcs) funcs = new Endgames(); }
|
|
||||||
MaterialInfoTable::~MaterialInfoTable() { delete funcs; }
|
|
||||||
|
|
||||||
|
|
||||||
/// MaterialInfoTable::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::material_info(const Position& pos) const {
|
|
||||||
|
|
||||||
Key key = pos.material_key();
|
|
||||||
MaterialInfo* mi = probe(key);
|
|
||||||
|
|
||||||
// If mi->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;
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
|
|
||||||
// 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<Value>(key)) != NULL)
|
|
||||||
return mi;
|
|
||||||
|
|
||||||
if (is_KXK<WHITE>(pos))
|
|
||||||
{
|
|
||||||
mi->evaluationFunction = &EvaluateKXK[WHITE];
|
|
||||||
return mi;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_KXK<BLACK>(pos))
|
|
||||||
{
|
|
||||||
mi->evaluationFunction = &EvaluateKXK[BLACK];
|
|
||||||
return mi;
|
|
||||||
}
|
|
||||||
|
|
||||||
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)));
|
|
||||||
|
|
||||||
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[pos.side_to_move()];
|
|
||||||
return mi;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// OK, we didn't find any special evaluation function for the current
|
|
||||||
// material configuration. Is there a suitable scaling function?
|
|
||||||
//
|
|
||||||
// We face problems when there are several conflicting applicable
|
|
||||||
// scaling functions and we need to decide which one to use.
|
|
||||||
EndgameBase<ScaleFactor>* sf;
|
|
||||||
|
|
||||||
if ((sf = funcs->get<ScaleFactor>(key)) != NULL)
|
|
||||||
{
|
|
||||||
mi->scalingFunction[sf->color()] = sf;
|
|
||||||
return mi;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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];
|
|
||||||
|
|
||||||
if (is_KBPsKs<BLACK>(pos))
|
|
||||||
mi->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
|
|
||||||
|
|
||||||
if (is_KQKRPs<WHITE>(pos))
|
|
||||||
mi->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
|
|
||||||
|
|
||||||
else if (is_KQKRPs<BLACK>(pos))
|
|
||||||
mi->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
|
|
||||||
|
|
||||||
Value npm_w = pos.non_pawn_material(WHITE);
|
|
||||||
Value npm_b = pos.non_pawn_material(BLACK);
|
|
||||||
|
|
||||||
if (npm_w + npm_b == VALUE_ZERO)
|
|
||||||
{
|
|
||||||
if (pos.piece_count(BLACK, PAWN) == 0)
|
|
||||||
{
|
|
||||||
assert(pos.piece_count(WHITE, PAWN) >= 2);
|
|
||||||
mi->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
|
|
||||||
}
|
|
||||||
else if (pos.piece_count(WHITE, PAWN) == 0)
|
|
||||||
{
|
|
||||||
assert(pos.piece_count(BLACK, PAWN) >= 2);
|
|
||||||
mi->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];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// No pawns makes it difficult to win, even with a material advantage
|
|
||||||
if (pos.piece_count(WHITE, PAWN) == 0 && npm_w - npm_b <= BishopValueMidgame)
|
|
||||||
{
|
|
||||||
mi->factor[WHITE] = uint8_t
|
|
||||||
(npm_w == npm_b || npm_w < RookValueMidgame ? 0 : NoPawnsSF[std::min(pos.piece_count(WHITE, BISHOP), 2)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pos.piece_count(BLACK, PAWN) == 0 && npm_b - npm_w <= BishopValueMidgame)
|
|
||||||
{
|
|
||||||
mi->factor[BLACK] = uint8_t
|
|
||||||
(npm_w == npm_b || npm_b < RookValueMidgame ? 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)
|
|
||||||
{
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
|
|
||||||
// for the bishop pair "extended piece", this allow us to be more flexible
|
|
||||||
// in defining bishop pair bonuses.
|
|
||||||
const int pieceCount[2][8] = {
|
|
||||||
{ pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
|
|
||||||
pos.piece_count(WHITE, BISHOP) , pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
|
|
||||||
{ 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// MaterialInfoTable::imbalance() calculates imbalance comparing piece count of each
|
|
||||||
/// piece type for both colors.
|
/// piece type for both colors.
|
||||||
|
|
||||||
template<Color Us>
|
template<Color Us>
|
||||||
int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
int imbalance(const int pieceCount[][PIECE_TYPE_NB]) {
|
||||||
|
|
||||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
|
|
||||||
@@ -271,12 +130,157 @@ int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
/// MaterialInfoTable::game_phase() calculates the phase given the current
|
namespace Material {
|
||||||
|
|
||||||
|
/// Material::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.
|
||||||
|
|
||||||
|
Entry* probe(const Position& pos, Table& entries, Endgames& endgames) {
|
||||||
|
|
||||||
|
Key key = pos.material_key();
|
||||||
|
Entry* e = entries[key];
|
||||||
|
|
||||||
|
// 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 (e->key == key)
|
||||||
|
return e;
|
||||||
|
|
||||||
|
memset(e, 0, sizeof(Entry));
|
||||||
|
e->key = key;
|
||||||
|
e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
|
||||||
|
e->gamePhase = 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 (endgames.probe(key, e->evaluationFunction))
|
||||||
|
return e;
|
||||||
|
|
||||||
|
if (is_KXK<WHITE>(pos))
|
||||||
|
{
|
||||||
|
e->evaluationFunction = &EvaluateKXK[WHITE];
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_KXK<BLACK>(pos))
|
||||||
|
{
|
||||||
|
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(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)
|
||||||
|
{
|
||||||
|
e->evaluationFunction = &EvaluateKmmKm[pos.side_to_move()];
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OK, we didn't find any special evaluation function for the current
|
||||||
|
// material configuration. Is there a suitable scaling function?
|
||||||
|
//
|
||||||
|
// We face problems when there are several conflicting applicable
|
||||||
|
// scaling functions and we need to decide which one to use.
|
||||||
|
EndgameBase<ScaleFactor>* sf;
|
||||||
|
|
||||||
|
if (endgames.probe(key, sf))
|
||||||
|
{
|
||||||
|
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))
|
||||||
|
e->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
|
||||||
|
|
||||||
|
if (is_KBPsKs<BLACK>(pos))
|
||||||
|
e->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
|
||||||
|
|
||||||
|
if (is_KQKRPs<WHITE>(pos))
|
||||||
|
e->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];
|
||||||
|
|
||||||
|
else if (is_KQKRPs<BLACK>(pos))
|
||||||
|
e->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
|
||||||
|
|
||||||
|
Value npm_w = pos.non_pawn_material(WHITE);
|
||||||
|
Value npm_b = pos.non_pawn_material(BLACK);
|
||||||
|
|
||||||
|
if (npm_w + npm_b == VALUE_ZERO)
|
||||||
|
{
|
||||||
|
if (pos.piece_count(BLACK, PAWN) == 0)
|
||||||
|
{
|
||||||
|
assert(pos.piece_count(WHITE, PAWN) >= 2);
|
||||||
|
e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
|
||||||
|
}
|
||||||
|
else if (pos.piece_count(WHITE, PAWN) == 0)
|
||||||
|
{
|
||||||
|
assert(pos.piece_count(BLACK, PAWN) >= 2);
|
||||||
|
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.
|
||||||
|
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 <= BishopValueMg)
|
||||||
|
{
|
||||||
|
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 <= BishopValueMg)
|
||||||
|
{
|
||||||
|
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 * 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);
|
||||||
|
|
||||||
|
e->spaceWeight = minorPieceCount * minorPieceCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
|
||||||
|
// for the bishop pair "extended piece", this allow us to be more flexible
|
||||||
|
// in defining bishop pair bonuses.
|
||||||
|
const int pieceCount[COLOR_NB][PIECE_TYPE_NB] = {
|
||||||
|
{ pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
|
||||||
|
pos.piece_count(WHITE, BISHOP) , pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
|
||||||
|
{ 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) } };
|
||||||
|
|
||||||
|
e->value = (int16_t)((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Material::game_phase() calculates the phase given the current
|
||||||
/// position. Because the phase is strictly a function of the material, it
|
/// 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 game_phase(const Position& pos) {
|
||||||
|
|
||||||
Value npm = pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK);
|
Value npm = pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK);
|
||||||
|
|
||||||
@@ -284,3 +288,5 @@ Phase MaterialInfoTable::game_phase(const Position& pos) {
|
|||||||
: npm <= EndgameLimit ? PHASE_ENDGAME
|
: npm <= EndgameLimit ? PHASE_ENDGAME
|
||||||
: Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
|
: Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace Material
|
||||||
|
|||||||
+22
-69
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -21,104 +21,57 @@
|
|||||||
#define MATERIAL_H_INCLUDED
|
#define MATERIAL_H_INCLUDED
|
||||||
|
|
||||||
#include "endgame.h"
|
#include "endgame.h"
|
||||||
|
#include "misc.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "tt.h"
|
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
const int MaterialTableSize = 8192;
|
namespace Material {
|
||||||
|
|
||||||
/// Game phase
|
/// Material::Entry contains various information about a material configuration.
|
||||||
enum Phase {
|
/// It contains a material balance evaluation, a function pointer to a special
|
||||||
PHASE_ENDGAME = 0,
|
/// endgame evaluation function (which in most cases is NULL, meaning that the
|
||||||
PHASE_MIDGAME = 128
|
/// standard evaluation function will be used), and "scale factors".
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/// MaterialInfo 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
|
|
||||||
/// be used), and "scale factors" for black and white.
|
|
||||||
///
|
///
|
||||||
/// The scale factors are used to scale the evaluation score up or down.
|
/// The scale factors are used to scale the evaluation score up or down.
|
||||||
/// For instance, in KRB vs KR endgames, the score is scaled down by a factor
|
/// 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.
|
/// of 4, which will result in scores of absolute value less than one pawn.
|
||||||
|
|
||||||
class MaterialInfo {
|
struct Entry {
|
||||||
|
|
||||||
friend class MaterialInfoTable;
|
Score material_value() const { return make_score(value, value); }
|
||||||
|
int space_weight() const { return spaceWeight; }
|
||||||
public:
|
Phase game_phase() const { return gamePhase; }
|
||||||
Score material_value() const;
|
bool specialized_eval_exists() const { return evaluationFunction != NULL; }
|
||||||
|
Value evaluate(const Position& p) const { return (*evaluationFunction)(p); }
|
||||||
ScaleFactor scale_factor(const Position& pos, Color c) const;
|
ScaleFactor scale_factor(const Position& pos, Color c) const;
|
||||||
int space_weight() const;
|
|
||||||
Phase game_phase() const;
|
|
||||||
bool specialized_eval_exists() const;
|
|
||||||
Value evaluate(const Position& pos) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
Key key;
|
Key key;
|
||||||
int16_t value;
|
int16_t value;
|
||||||
uint8_t factor[2];
|
uint8_t factor[COLOR_NB];
|
||||||
EndgameBase<Value>* evaluationFunction;
|
EndgameBase<Value>* evaluationFunction;
|
||||||
EndgameBase<ScaleFactor>* scalingFunction[2];
|
EndgameBase<ScaleFactor>* scalingFunction[COLOR_NB];
|
||||||
int spaceWeight;
|
int spaceWeight;
|
||||||
Phase gamePhase;
|
Phase gamePhase;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
typedef HashTable<Entry, 8192> Table;
|
||||||
|
|
||||||
/// The MaterialInfoTable class represents a pawn hash table. The most important
|
Entry* probe(const Position& pos, Table& entries, Endgames& endgames);
|
||||||
/// method is material_info(), which returns a pointer to a MaterialInfo object.
|
Phase game_phase(const Position& pos);
|
||||||
|
|
||||||
class MaterialInfoTable : public SimpleHash<MaterialInfo, MaterialTableSize> {
|
/// Material::scale_factor takes a position and a color as input, and
|
||||||
public:
|
|
||||||
~MaterialInfoTable();
|
|
||||||
void init();
|
|
||||||
MaterialInfo* material_info(const Position& pos) const;
|
|
||||||
static Phase game_phase(const Position& pos);
|
|
||||||
|
|
||||||
private:
|
|
||||||
template<Color Us>
|
|
||||||
static int imbalance(const int pieceCount[][8]);
|
|
||||||
|
|
||||||
Endgames* funcs;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/// MaterialInfo::scale_factor takes a position and a color as input, and
|
|
||||||
/// returns a scale factor for the given color. We have to provide the
|
/// 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
|
/// 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
|
/// 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
|
/// the position. For instance, in KBP vs K endgames, a scaling function
|
||||||
/// which checks for draws with rook pawns and wrong-colored bishops.
|
/// which checks for draws with rook pawns and wrong-colored bishops.
|
||||||
|
|
||||||
inline ScaleFactor MaterialInfo::scale_factor(const Position& pos, Color c) const {
|
inline ScaleFactor Entry::scale_factor(const Position& pos, Color c) const {
|
||||||
|
|
||||||
if (!scalingFunction[c])
|
return !scalingFunction[c] || (*scalingFunction[c])(pos) == SCALE_FACTOR_NONE
|
||||||
return ScaleFactor(factor[c]);
|
? ScaleFactor(factor[c]) : (*scalingFunction[c])(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)(pos);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Score MaterialInfo::material_value() const {
|
|
||||||
return make_score(value, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int MaterialInfo::space_weight() const {
|
|
||||||
return spaceWeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Phase MaterialInfo::game_phase() const {
|
|
||||||
return gamePhase;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline bool MaterialInfo::specialized_eval_exists() const {
|
|
||||||
return evaluationFunction != NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // !defined(MATERIAL_H_INCLUDED)
|
#endif // !defined(MATERIAL_H_INCLUDED)
|
||||||
|
|||||||
+115
-72
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -17,52 +17,30 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
|
||||||
|
|
||||||
#define _CRT_SECURE_NO_DEPRECATE
|
|
||||||
#define NOMINMAX // disable macros min() and max()
|
|
||||||
#include <windows.h>
|
|
||||||
#include <sys/timeb.h>
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
# include <sys/time.h>
|
|
||||||
# include <sys/types.h>
|
|
||||||
# include <unistd.h>
|
|
||||||
# if defined(__hpux)
|
|
||||||
# include <sys/pstat.h>
|
|
||||||
# endif
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if !defined(NO_PREFETCH)
|
|
||||||
# include <xmmintrin.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cassert>
|
|
||||||
#include <cstdio>
|
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
#include "bitcount.h"
|
|
||||||
#include "misc.h"
|
#include "misc.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
|
|
||||||
|
#if defined(__hpux)
|
||||||
|
# include <sys/pstat.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
/// Version number. If Version is left empty, then Tag plus current
|
/// Version number. If Version is left empty, then Tag plus current
|
||||||
/// date (in the format YYMMDD) is used as a version number.
|
/// date, in the format DD-MM-YY, are used as a version number.
|
||||||
|
|
||||||
static const string Version = "2.2";
|
static const string Version = "3";
|
||||||
static const string Tag = "";
|
static const string Tag = "";
|
||||||
|
|
||||||
|
|
||||||
/// engine_info() returns the full name of the current Stockfish version.
|
/// engine_info() returns the full name of the current Stockfish version. This
|
||||||
/// This will be either "Stockfish YYMMDD" (where YYMMDD is the date when
|
/// will be either "Stockfish <Tag> DD-MM-YY" (where DD-MM-YY is the date when
|
||||||
/// the program was compiled) or "Stockfish <version number>", depending
|
/// the program was compiled) or "Stockfish <Version>", depending on whether
|
||||||
/// on whether Version is empty.
|
/// Version is empty.
|
||||||
|
|
||||||
const string engine_info(bool to_uci) {
|
const string engine_info(bool to_uci) {
|
||||||
|
|
||||||
@@ -73,25 +51,30 @@ const string engine_info(bool to_uci) {
|
|||||||
string month, day, year;
|
string month, day, year;
|
||||||
stringstream s, date(__DATE__); // From compiler, format is "Sep 21 2008"
|
stringstream s, date(__DATE__); // From compiler, format is "Sep 21 2008"
|
||||||
|
|
||||||
|
s << "Stockfish " << Version;
|
||||||
|
|
||||||
if (Version.empty())
|
if (Version.empty())
|
||||||
{
|
{
|
||||||
date >> month >> day >> year;
|
date >> month >> day >> year;
|
||||||
|
|
||||||
s << "Stockfish " << Tag
|
s << Tag << string(Tag.empty() ? "" : " ") << setfill('0') << setw(2) << day
|
||||||
<< setfill('0') << " " << year.substr(2)
|
<< "-" << setw(2) << (1 + months.find(month) / 4) << "-" << year.substr(2);
|
||||||
<< setw(2) << (1 + months.find(month) / 4)
|
|
||||||
<< setw(2) << day << cpu64 << popcnt;
|
|
||||||
}
|
}
|
||||||
else
|
|
||||||
s << "Stockfish " << Version << cpu64 << popcnt;
|
|
||||||
|
|
||||||
s << (to_uci ? "\nid author ": " by ")
|
s << cpu64 << popcnt << (to_uci ? "\nid author ": " by ")
|
||||||
<< "Tord Romstad, Marco Costalba and Joona Kiiski";
|
<< "Tord Romstad, Marco Costalba and Joona Kiiski";
|
||||||
|
|
||||||
return s.str();
|
return s.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Convert system time to milliseconds. That's all we need.
|
||||||
|
|
||||||
|
Time::point Time::now() {
|
||||||
|
sys_time_t t; system_time(&t); return time_to_msec(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Debug functions used mainly to collect run-time statistics
|
/// Debug functions used mainly to collect run-time statistics
|
||||||
|
|
||||||
static uint64_t hits[2], means[2];
|
static uint64_t hits[2], means[2];
|
||||||
@@ -112,39 +95,102 @@ void dbg_print() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// system_time() returns the current system time, measured in milliseconds
|
/// 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
|
||||||
|
|
||||||
int system_time() {
|
struct Tie: public streambuf { // MSVC requires splitted streambuf for cin and cout
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
Tie(streambuf* b, ofstream* f) : buf(b), file(f) {}
|
||||||
struct _timeb t;
|
|
||||||
_ftime(&t);
|
int sync() { return file->rdbuf()->pubsync(), buf->pubsync(); }
|
||||||
return int(t.time * 1000 + t.millitm);
|
int overflow(int c) { return log(buf->sputc((char)c), "<< "); }
|
||||||
#else
|
int underflow() { return buf->sgetc(); }
|
||||||
struct timeval t;
|
int uflow() { return log(buf->sbumpc(), ">> "); }
|
||||||
gettimeofday(&t, NULL);
|
|
||||||
return t.tv_sec * 1000 + t.tv_usec / 1000;
|
streambuf* buf;
|
||||||
#endif
|
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
|
/// cpu_count() tries to detect the number of CPU cores
|
||||||
|
|
||||||
int cpu_count() {
|
int cpu_count() {
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
#if defined(_WIN32) || defined(_WIN64)
|
||||||
SYSTEM_INFO s;
|
SYSTEM_INFO s;
|
||||||
GetSystemInfo(&s);
|
GetSystemInfo(&s);
|
||||||
return std::min(int(s.dwNumberOfProcessors), MAX_THREADS);
|
return s.dwNumberOfProcessors;
|
||||||
#else
|
#else
|
||||||
|
|
||||||
# if defined(_SC_NPROCESSORS_ONLN)
|
# if defined(_SC_NPROCESSORS_ONLN)
|
||||||
return std::min((int)sysconf(_SC_NPROCESSORS_ONLN), MAX_THREADS);
|
return sysconf(_SC_NPROCESSORS_ONLN);
|
||||||
# elif defined(__hpux)
|
# elif defined(__hpux)
|
||||||
struct pst_dynamic psd;
|
struct pst_dynamic psd;
|
||||||
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) == -1)
|
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) == -1)
|
||||||
return 1;
|
return 1;
|
||||||
return std::min((int)psd.psd_proc_cnt, MAX_THREADS);
|
return psd.psd_proc_cnt;
|
||||||
# else
|
# else
|
||||||
return 1;
|
return 1;
|
||||||
# endif
|
# endif
|
||||||
@@ -156,24 +202,16 @@ int cpu_count() {
|
|||||||
/// timed_wait() waits for msec milliseconds. It is mainly an helper to wrap
|
/// timed_wait() waits for msec milliseconds. It is mainly an helper to wrap
|
||||||
/// conversion from milliseconds to struct timespec, as used by pthreads.
|
/// conversion from milliseconds to struct timespec, as used by pthreads.
|
||||||
|
|
||||||
void timed_wait(WaitCondition* sleepCond, Lock* sleepLock, int msec) {
|
void timed_wait(WaitCondition& sleepCond, Lock& sleepLock, int msec) {
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
#if defined(_WIN32) || defined(_WIN64)
|
||||||
int tm = msec;
|
int tm = msec;
|
||||||
#else
|
#else
|
||||||
struct timeval t;
|
timespec ts, *tm = &ts;
|
||||||
struct timespec abstime, *tm = &abstime;
|
uint64_t ms = Time::now() + msec;
|
||||||
|
|
||||||
gettimeofday(&t, NULL);
|
ts.tv_sec = ms / 1000;
|
||||||
|
ts.tv_nsec = (ms % 1000) * 1000000LL;
|
||||||
abstime.tv_sec = t.tv_sec + (msec / 1000);
|
|
||||||
abstime.tv_nsec = (t.tv_usec + (msec % 1000) * 1000) * 1000;
|
|
||||||
|
|
||||||
if (abstime.tv_nsec > 1000000000LL)
|
|
||||||
{
|
|
||||||
abstime.tv_sec += 1;
|
|
||||||
abstime.tv_nsec -= 1000000000LL;
|
|
||||||
}
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
cond_timedwait(sleepCond, sleepLock, tm);
|
cond_timedwait(sleepCond, sleepLock, tm);
|
||||||
@@ -191,14 +229,19 @@ void prefetch(char*) {}
|
|||||||
|
|
||||||
void prefetch(char* addr) {
|
void prefetch(char* addr) {
|
||||||
|
|
||||||
# if defined(__INTEL_COMPILER) || defined(__ICL)
|
# if defined(__INTEL_COMPILER)
|
||||||
// This hack prevents prefetches to be optimized away by
|
// This hack prevents prefetches to be optimized away by
|
||||||
// Intel compiler. Both MSVC and gcc seems not affected.
|
// Intel compiler. Both MSVC and gcc seems not affected.
|
||||||
__asm__ ("");
|
__asm__ ("");
|
||||||
# endif
|
# endif
|
||||||
|
|
||||||
_mm_prefetch(addr, _MM_HINT_T2);
|
# if defined(__INTEL_COMPILER) || defined(_MSC_VER)
|
||||||
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
|
_mm_prefetch(addr, _MM_HINT_T0);
|
||||||
|
_mm_prefetch(addr+64, _MM_HINT_T0); // 64 bytes ahead
|
||||||
|
# else
|
||||||
|
__builtin_prefetch(addr);
|
||||||
|
__builtin_prefetch(addr+64);
|
||||||
|
# endif
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
+27
-8
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -22,29 +22,48 @@
|
|||||||
|
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "lock.h"
|
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
extern const std::string engine_info(bool to_uci = false);
|
extern const std::string engine_info(bool to_uci = false);
|
||||||
extern int system_time();
|
|
||||||
extern int cpu_count();
|
extern int cpu_count();
|
||||||
extern void timed_wait(WaitCondition*, Lock*, int);
|
extern void timed_wait(WaitCondition&, Lock&, int);
|
||||||
extern void prefetch(char* addr);
|
extern void prefetch(char* addr);
|
||||||
|
extern void start_logger(bool b);
|
||||||
|
|
||||||
extern void dbg_hit_on(bool b);
|
extern void dbg_hit_on(bool b);
|
||||||
extern void dbg_hit_on_c(bool c, bool b);
|
extern void dbg_hit_on_c(bool c, bool b);
|
||||||
extern void dbg_mean_of(int v);
|
extern void dbg_mean_of(int v);
|
||||||
extern void dbg_print();
|
extern void dbg_print();
|
||||||
|
|
||||||
class Position;
|
|
||||||
extern Move move_from_uci(const Position& pos, const std::string& str);
|
|
||||||
extern const std::string move_to_uci(Move m, bool chess960);
|
|
||||||
extern const std::string move_to_san(Position& pos, Move m);
|
|
||||||
|
|
||||||
struct Log : public std::ofstream {
|
struct Log : public std::ofstream {
|
||||||
Log(const std::string& f = "log.txt") : std::ofstream(f.c_str(), std::ios::out | std::ios::app) {}
|
Log(const std::string& f = "log.txt") : std::ofstream(f.c_str(), std::ios::out | std::ios::app) {}
|
||||||
~Log() { if (is_open()) close(); }
|
~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)
|
#endif // !defined(MISC_H_INCLUDED)
|
||||||
|
|||||||
-159
@@ -1,159 +0,0 @@
|
|||||||
/*
|
|
||||||
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 <cstring>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include "movegen.h"
|
|
||||||
#include "position.h"
|
|
||||||
|
|
||||||
using std::string;
|
|
||||||
|
|
||||||
/// 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. Instead internally Move is coded as "king captures rook".
|
|
||||||
|
|
||||||
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 (is_castle(m) && !chess960)
|
|
||||||
to = from + (file_of(to) == FILE_H ? Square(2) : -Square(2));
|
|
||||||
|
|
||||||
if (is_promotion(m))
|
|
||||||
promotion = char(tolower(piece_type_to_char(promotion_piece_type(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) {
|
|
||||||
|
|
||||||
for (MoveList<MV_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 move as input, where it is assumed
|
|
||||||
/// that the move is a legal move for the position. The return value is
|
|
||||||
/// a string containing the move in short algebraic notation.
|
|
||||||
|
|
||||||
const string move_to_san(Position& pos, Move m) {
|
|
||||||
|
|
||||||
if (m == MOVE_NONE)
|
|
||||||
return "(none)";
|
|
||||||
|
|
||||||
if (m == MOVE_NULL)
|
|
||||||
return "(null)";
|
|
||||||
|
|
||||||
assert(is_ok(m));
|
|
||||||
|
|
||||||
Bitboard attackers;
|
|
||||||
bool ambiguousMove, ambiguousFile, ambiguousRank;
|
|
||||||
Square sq, from = move_from(m);
|
|
||||||
Square to = move_to(m);
|
|
||||||
PieceType pt = type_of(pos.piece_on(from));
|
|
||||||
string san;
|
|
||||||
|
|
||||||
if (is_castle(m))
|
|
||||||
san = (move_to(m) < move_from(m) ? "O-O-O" : "O-O");
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (pt != PAWN)
|
|
||||||
{
|
|
||||||
san = piece_type_to_char(pt);
|
|
||||||
|
|
||||||
// Disambiguation if we have more then one piece with destination 'to'
|
|
||||||
// note that for pawns is not needed because starting file is explicit.
|
|
||||||
attackers = pos.attackers_to(to) & pos.pieces(pt, pos.side_to_move());
|
|
||||||
clear_bit(&attackers, from);
|
|
||||||
ambiguousMove = ambiguousFile = ambiguousRank = false;
|
|
||||||
|
|
||||||
while (attackers)
|
|
||||||
{
|
|
||||||
sq = pop_1st_bit(&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;
|
|
||||||
|
|
||||||
if (file_of(sq) == file_of(from))
|
|
||||||
ambiguousFile = true;
|
|
||||||
|
|
||||||
if (rank_of(sq) == rank_of(from))
|
|
||||||
ambiguousRank = true;
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pos.is_capture(m))
|
|
||||||
{
|
|
||||||
if (pt == PAWN)
|
|
||||||
san += file_to_char(file_of(from));
|
|
||||||
|
|
||||||
san += 'x';
|
|
||||||
}
|
|
||||||
|
|
||||||
san += square_to_string(to);
|
|
||||||
|
|
||||||
if (is_promotion(m))
|
|
||||||
{
|
|
||||||
san += '=';
|
|
||||||
san += piece_type_to_char(promotion_piece_type(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;
|
|
||||||
}
|
|
||||||
+337
-445
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -18,268 +18,380 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
#include "bitcount.h"
|
|
||||||
#include "movegen.h"
|
#include "movegen.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
|
|
||||||
// Simple macro to wrap a very common while loop, no facny, no flexibility,
|
/// Simple macro to wrap a very common while loop, no facny, no flexibility,
|
||||||
// hardcoded list name 'mlist' and from square 'from'.
|
/// hardcoded names 'mlist' and 'from'.
|
||||||
#define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
|
#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_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
|
|
||||||
|
|
||||||
|
/// 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 {
|
namespace {
|
||||||
|
|
||||||
enum CastlingSide {
|
template<CastlingSide Side, bool Checks, bool Chess960>
|
||||||
KING_SIDE,
|
MoveStack* generate_castle(const Position& pos, MoveStack* mlist, Color us) {
|
||||||
QUEEN_SIDE
|
|
||||||
};
|
|
||||||
|
|
||||||
template<CastlingSide>
|
if (pos.castle_impeded(us, Side) || !pos.can_castle(make_castle_right(us, Side)))
|
||||||
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 && Pt != PAWN);
|
|
||||||
|
|
||||||
Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
|
|
||||||
|
|
||||||
if (Pt == KING)
|
|
||||||
b &= ~QueenPseudoAttacks[pos.king_square(flip(pos.side_to_move()))];
|
|
||||||
|
|
||||||
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 && Pt != PAWN);
|
|
||||||
|
|
||||||
Bitboard checkSqs, b;
|
|
||||||
Square from;
|
|
||||||
const Square* pl = pos.piece_list(us, Pt);
|
|
||||||
|
|
||||||
if ((from = *pl++) == SQ_NONE)
|
|
||||||
return mlist;
|
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
|
assert(!pos.checkers());
|
||||||
{
|
|
||||||
if ( (Pt == QUEEN && !(QueenPseudoAttacks[from] & checkSqs))
|
|
||||||
|| (Pt == ROOK && !(RookPseudoAttacks[from] & checkSqs))
|
|
||||||
|| (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (dc && bit_is_set(dc, from))
|
const int K = Chess960 ? kto > kfrom ? -1 : 1
|
||||||
continue;
|
: Side == KING_SIDE ? -1 : 1;
|
||||||
|
|
||||||
b = pos.attacks_from<Pt>(from) & checkSqs;
|
for (Square s = kto; s != kfrom; s += (Square)K)
|
||||||
SERIALIZE_MOVES(b);
|
if (pos.attackers_to(s) & enemies)
|
||||||
|
return mlist;
|
||||||
|
|
||||||
} while ((from = *pl++) != 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;
|
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)
|
template<Square Delta>
|
||||||
: generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
|
inline Bitboard move_pawns(Bitboard p) {
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
|
|
||||||
: generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
|
|
||||||
}
|
|
||||||
|
|
||||||
template<PieceType Pt>
|
|
||||||
FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
|
|
||||||
|
|
||||||
Bitboard b;
|
|
||||||
Square from;
|
|
||||||
const Square* pl = pos.piece_list(us, Pt);
|
|
||||||
|
|
||||||
if (*pl != SQ_NONE)
|
|
||||||
{
|
|
||||||
do {
|
|
||||||
from = *pl;
|
|
||||||
b = pos.attacks_from<Pt>(from) & target;
|
|
||||||
SERIALIZE_MOVES(b);
|
|
||||||
} while (*++pl != SQ_NONE);
|
|
||||||
}
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<>
|
|
||||||
FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
|
|
||||||
|
|
||||||
Bitboard b;
|
|
||||||
Square from = pos.king_square(us);
|
|
||||||
|
|
||||||
b = pos.attacks_from<KING>(from) & target;
|
|
||||||
SERIALIZE_MOVES(b);
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
|
template<GenType Type, Square Delta>
|
||||||
/// promotions. Returns a pointer to the end of the move list.
|
inline MoveStack* generate_promotions(MoveStack* mlist, Bitboard pawnsOn7,
|
||||||
///
|
Bitboard target, const CheckInfo* ci) {
|
||||||
/// generate<MV_NON_CAPTURE> 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
|
|
||||||
/// non-captures. Returns a pointer to the end of the move list.
|
|
||||||
|
|
||||||
template<MoveType Type>
|
Bitboard b = move_pawns<Delta>(pawnsOn7) & target;
|
||||||
MoveStack* generate(const Position& pos, MoveStack* mlist) {
|
|
||||||
|
|
||||||
assert(!pos.in_check());
|
|
||||||
|
|
||||||
Color us = pos.side_to_move();
|
|
||||||
Bitboard target;
|
|
||||||
|
|
||||||
if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
|
|
||||||
target = pos.pieces(flip(us));
|
|
||||||
else if (Type == MV_NON_CAPTURE)
|
|
||||||
target = pos.empty_squares();
|
|
||||||
else
|
|
||||||
assert(false);
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
if (Type != MV_CAPTURE && pos.can_castle(us))
|
|
||||||
{
|
|
||||||
if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
|
|
||||||
mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
|
|
||||||
|
|
||||||
if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
|
|
||||||
mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
|
|
||||||
}
|
|
||||||
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
|
|
||||||
|
|
||||||
/// generate<MV_NON_CAPTURE_CHECK> 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) {
|
|
||||||
|
|
||||||
assert(!pos.in_check());
|
|
||||||
|
|
||||||
Bitboard b, dc;
|
|
||||||
Square from;
|
|
||||||
Color us = pos.side_to_move();
|
|
||||||
Square ksq = pos.king_square(flip(us));
|
|
||||||
|
|
||||||
assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
|
|
||||||
|
|
||||||
// Discovered non-capture checks
|
|
||||||
b = dc = pos.discovered_check_candidates();
|
|
||||||
|
|
||||||
while (b)
|
while (b)
|
||||||
{
|
{
|
||||||
from = pop_1st_bit(&b);
|
Square to = pop_lsb(&b);
|
||||||
switch (type_of(pos.piece_on(from)))
|
|
||||||
|
if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
||||||
|
(*mlist++).move = make<PROMOTION>(to - Delta, to, QUEEN);
|
||||||
|
|
||||||
|
if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
|
||||||
{
|
{
|
||||||
case PAWN: /* Will be generated togheter with pawns direct checks */ break;
|
(*mlist++).move = make<PROMOTION>(to - Delta, to, ROOK);
|
||||||
case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
|
(*mlist++).move = make<PROMOTION>(to - Delta, to, BISHOP);
|
||||||
case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
|
(*mlist++).move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Direct non-capture checks
|
// Knight-promotion is the only one that can give a direct check not
|
||||||
mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
|
// already included in the queen-promotion.
|
||||||
mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
|
if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ci->ksq))
|
||||||
mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
|
(*mlist++).move = make<PROMOTION>(to - Delta, to, KNIGHT);
|
||||||
mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
|
else
|
||||||
return generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
|
(void)ci; // Silence a warning under MSVC
|
||||||
|
}
|
||||||
|
|
||||||
|
return mlist;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template<GenType Type> FORCE_INLINE
|
||||||
|
MoveStack* generate_all(const Position& pos, MoveStack* mlist, Color us,
|
||||||
|
Bitboard target, const CheckInfo* ci = NULL) {
|
||||||
|
|
||||||
|
const bool Checks = Type == QUIET_CHECKS;
|
||||||
|
|
||||||
|
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, Checks>(pos, mlist, us, target, ci);
|
||||||
|
mlist = generate_moves<BISHOP, Checks>(pos, mlist, us, target, ci);
|
||||||
|
mlist = generate_moves<ROOK, Checks>(pos, mlist, us, target, ci);
|
||||||
|
mlist = generate_moves<QUEEN, Checks>(pos, mlist, us, target, ci);
|
||||||
|
|
||||||
|
if (Type != QUIET_CHECKS && Type != EVASIONS)
|
||||||
|
{
|
||||||
|
Square from = pos.king_square(us);
|
||||||
|
Bitboard b = pos.attacks_from<KING>(from) & target;
|
||||||
|
SERIALIZE(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(us))
|
||||||
|
{
|
||||||
|
if (pos.is_chess960())
|
||||||
|
{
|
||||||
|
mlist = generate_castle<KING_SIDE, Checks, true>(pos, mlist, us);
|
||||||
|
mlist = generate_castle<QUEEN_SIDE, Checks, true>(pos, mlist, us);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mlist = generate_castle<KING_SIDE, Checks, false>(pos, mlist, us);
|
||||||
|
mlist = generate_castle<QUEEN_SIDE, Checks, false>(pos, mlist, us);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return mlist;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
|
||||||
|
/// generate<CAPTURES> generates all pseudo-legal captures and queen
|
||||||
|
/// promotions. Returns a pointer to the end of the move list.
|
||||||
|
///
|
||||||
|
/// generate<QUIETS> generates all pseudo-legal non-captures and
|
||||||
|
/// underpromotions. Returns a pointer to the end of the move list.
|
||||||
|
///
|
||||||
|
/// generate<NON_EVASIONS> generates all pseudo-legal captures and
|
||||||
|
/// non-captures. Returns a pointer to the end of the move list.
|
||||||
|
|
||||||
|
template<GenType Type>
|
||||||
|
MoveStack* generate(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
|
assert(Type == CAPTURES || Type == QUIETS || Type == NON_EVASIONS);
|
||||||
|
assert(!pos.checkers());
|
||||||
|
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
|
||||||
|
Bitboard target = Type == CAPTURES ? pos.pieces(~us)
|
||||||
|
: Type == QUIETS ? ~pos.pieces()
|
||||||
|
: Type == NON_EVASIONS ? ~pos.pieces(us) : 0;
|
||||||
|
|
||||||
|
return generate_all<Type>(pos, mlist, us, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicit template instantiations
|
||||||
|
template MoveStack* generate<CAPTURES>(const Position&, MoveStack*);
|
||||||
|
template MoveStack* generate<QUIETS>(const Position&, MoveStack*);
|
||||||
|
template MoveStack* generate<NON_EVASIONS>(const Position&, MoveStack*);
|
||||||
|
|
||||||
|
|
||||||
|
/// 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<QUIET_CHECKS>(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
|
assert(!pos.checkers());
|
||||||
|
|
||||||
|
CheckInfo ci(pos);
|
||||||
|
Bitboard dc = ci.dcCandidates;
|
||||||
|
|
||||||
|
while (dc)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
return generate_all<QUIET_CHECKS>(pos, mlist, pos.side_to_move(), ~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.
|
/// to move is in check. Returns a pointer to the end of the move list.
|
||||||
template<>
|
template<>
|
||||||
MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
|
MoveStack* generate<EVASIONS>(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
assert(pos.in_check());
|
assert(pos.checkers());
|
||||||
|
|
||||||
Bitboard b, target;
|
|
||||||
Square from, checksq;
|
Square from, checksq;
|
||||||
int checkersCnt = 0;
|
int checkersCnt = 0;
|
||||||
Color us = pos.side_to_move();
|
Color us = pos.side_to_move();
|
||||||
Square ksq = pos.king_square(us);
|
Square ksq = pos.king_square(us);
|
||||||
Bitboard checkers = pos.checkers();
|
|
||||||
Bitboard sliderAttacks = 0;
|
Bitboard sliderAttacks = 0;
|
||||||
|
Bitboard b = pos.checkers();
|
||||||
|
|
||||||
assert(pos.piece_on(ksq) == make_piece(us, KING));
|
assert(pos.checkers());
|
||||||
assert(checkers);
|
|
||||||
|
|
||||||
// Find squares attacked by slider checkers, we will remove
|
// Find squares attacked by slider checkers, we will remove them from the king
|
||||||
// them from the king evasions set so to early skip known
|
// evasions so to skip known illegal moves avoiding useless legality check later.
|
||||||
// illegal moves and avoid an useless legality check later.
|
|
||||||
b = checkers;
|
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
checkersCnt++;
|
checkersCnt++;
|
||||||
checksq = pop_1st_bit(&b);
|
checksq = pop_lsb(&b);
|
||||||
|
|
||||||
assert(color_of(pos.piece_on(checksq)) == flip(us));
|
assert(color_of(pos.piece_on(checksq)) == ~us);
|
||||||
|
|
||||||
switch (type_of(pos.piece_on(checksq)))
|
switch (type_of(pos.piece_on(checksq)))
|
||||||
{
|
{
|
||||||
case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
|
case BISHOP: sliderAttacks |= PseudoAttacks[BISHOP][checksq]; break;
|
||||||
case ROOK: sliderAttacks |= RookPseudoAttacks[checksq]; break;
|
case ROOK: sliderAttacks |= PseudoAttacks[ROOK][checksq]; break;
|
||||||
case QUEEN:
|
case QUEEN:
|
||||||
// If queen and king are far we can safely remove all the squares attacked
|
// If queen and king are far or not on a diagonal line we can safely
|
||||||
// in the other direction becuase are not reachable by the king anyway.
|
// remove all the squares attacked in the other direction becuase are
|
||||||
if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
|
// not reachable by the king anyway.
|
||||||
sliderAttacks |= QueenPseudoAttacks[checksq];
|
if (between_bb(ksq, checksq) || !(PseudoAttacks[BISHOP][checksq] & ksq))
|
||||||
|
sliderAttacks |= PseudoAttacks[QUEEN][checksq];
|
||||||
|
|
||||||
// Otherwise, if king and queen are adjacent and on a diagonal line, we need to
|
// Otherwise we need to use real rook attacks to check if king is safe
|
||||||
// use real rook attacks to check if king is safe to move in the other direction.
|
// to move in the other direction. For example: king in B2, queen in A1
|
||||||
// For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
|
// a knight in B1, and we can safely move to C1.
|
||||||
else
|
else
|
||||||
sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
|
sliderAttacks |= PseudoAttacks[BISHOP][checksq] | pos.attacks_from<ROOK>(checksq);
|
||||||
|
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -289,255 +401,35 @@ MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
|
|||||||
// Generate evasions for king, capture and non capture moves
|
// Generate evasions for king, capture and non capture moves
|
||||||
b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
|
b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
|
||||||
from = ksq;
|
from = ksq;
|
||||||
SERIALIZE_MOVES(b);
|
SERIALIZE(b);
|
||||||
|
|
||||||
// Generate evasions for other pieces only if not double check
|
|
||||||
if (checkersCnt > 1)
|
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
|
// Generate blocking evasions or captures of the checking piece
|
||||||
// checker piece is possible.
|
Bitboard target = between_bb(checksq, ksq) | pos.checkers();
|
||||||
target = squares_between(checksq, ksq) | checkers;
|
|
||||||
|
|
||||||
mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
|
return generate_all<EVASIONS>(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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// generate<MV_LEGAL> computes a complete list of legal moves in the current position
|
/// generate<LEGAL> generates all the legal moves in the given position
|
||||||
|
|
||||||
template<>
|
template<>
|
||||||
MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
|
MoveStack* generate<LEGAL>(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
MoveStack *last, *cur = mlist;
|
MoveStack *end, *cur = mlist;
|
||||||
Bitboard pinned = pos.pinned_pieces();
|
Bitboard pinned = pos.pinned_pieces();
|
||||||
|
Square ksq = pos.king_square(pos.side_to_move());
|
||||||
|
|
||||||
last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
|
end = pos.checkers() ? generate<EVASIONS>(pos, mlist)
|
||||||
: generate<MV_NON_EVASION>(pos, mlist);
|
: generate<NON_EVASIONS>(pos, mlist);
|
||||||
|
while (cur != end)
|
||||||
// Remove illegal moves from the list
|
if ( (pinned || from_sq(cur->move) == ksq || type_of(cur->move) == ENPASSANT)
|
||||||
while (cur != last)
|
&& !pos.pl_move_is_legal(cur->move, pinned))
|
||||||
if (!pos.pl_move_is_legal(cur->move, pinned))
|
cur->move = (--end)->move;
|
||||||
cur->move = (--last)->move;
|
|
||||||
else
|
else
|
||||||
cur++;
|
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<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(Delta > 0 ? BLACK : WHITE)))
|
|
||||||
(*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 UP = (Us == WHITE ? DELTA_N : DELTA_S);
|
|
||||||
const Square RIGHT_UP = (Us == WHITE ? DELTA_NE : DELTA_SW);
|
|
||||||
const Square LEFT_UP = (Us == WHITE ? DELTA_NW : DELTA_SE);
|
|
||||||
|
|
||||||
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(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<UP>(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<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
|
|
||||||
mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
|
|
||||||
mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Standard captures
|
|
||||||
if (Type == MV_CAPTURE || Type == MV_EVASION)
|
|
||||||
{
|
|
||||||
mlist = generate_pawn_captures<Type, RIGHT_UP>(mlist, pawns, enemyPieces);
|
|
||||||
mlist = generate_pawn_captures<Type, LEFT_UP>(mlist, pawns, enemyPieces);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single and double pawn pushes
|
|
||||||
if (Type != MV_CAPTURE)
|
|
||||||
{
|
|
||||||
b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
|
|
||||||
b2 = move_pawns<UP>(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<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
|
|
||||||
dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
|
|
||||||
|
|
||||||
b1 |= dc1;
|
|
||||||
b2 |= dc2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
SERIALIZE_MOVES_D(b1, -UP);
|
|
||||||
SERIALIZE_MOVES_D(b2, -UP -UP);
|
|
||||||
}
|
|
||||||
|
|
||||||
// En passant captures
|
|
||||||
if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
|
|
||||||
{
|
|
||||||
assert(Us != WHITE || rank_of(pos.ep_square()) == RANK_6);
|
|
||||||
assert(Us != BLACK || rank_of(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() - UP))
|
|
||||||
return mlist;
|
|
||||||
|
|
||||||
b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
|
|
||||||
|
|
||||||
assert(b1);
|
|
||||||
|
|
||||||
while (b1)
|
|
||||||
{
|
|
||||||
to = pop_1st_bit(&b1);
|
|
||||||
(*mlist++).move = make_enpassant_move(to, pos.ep_square());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<CastlingSide Side>
|
|
||||||
MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
|
|
||||||
|
|
||||||
CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
|
|
||||||
Color them = flip(us);
|
|
||||||
|
|
||||||
// After castling, the rook and king's final positions are exactly the same
|
|
||||||
// in Chess960 as they would be in standard chess.
|
|
||||||
Square kfrom = pos.king_square(us);
|
|
||||||
Square rfrom = pos.castle_rook_square(f);
|
|
||||||
Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
|
|
||||||
Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
|
|
||||||
|
|
||||||
assert(!pos.in_check());
|
|
||||||
assert(pos.piece_on(kfrom) == make_piece(us, KING));
|
|
||||||
assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
|
|
||||||
|
|
||||||
// Unimpeded rule: All the squares between the king's initial and final squares
|
|
||||||
// (including the final square), and all the squares between the rook's initial
|
|
||||||
// and final squares (including the final square), must be vacant except for
|
|
||||||
// the king and castling rook.
|
|
||||||
for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
|
|
||||||
if ( (s != kfrom && s != rfrom && !pos.square_is_empty(s))
|
|
||||||
||(pos.attackers_to(s) & pos.pieces(them)))
|
|
||||||
return mlist;
|
|
||||||
|
|
||||||
for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
|
|
||||||
if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
|
|
||||||
return mlist;
|
|
||||||
|
|
||||||
// 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 (pos.is_chess960())
|
|
||||||
{
|
|
||||||
Bitboard occ = pos.occupied_squares();
|
|
||||||
clear_bit(&occ, rfrom);
|
|
||||||
if (pos.attackers_to(kto, occ) & pos.pieces(them))
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
(*mlist++).move = make_castle_move(kfrom, rfrom);
|
|
||||||
|
|
||||||
return mlist;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|||||||
+15
-12
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -22,31 +22,34 @@
|
|||||||
|
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
enum MoveType {
|
enum GenType {
|
||||||
MV_CAPTURE,
|
CAPTURES,
|
||||||
MV_NON_CAPTURE,
|
QUIETS,
|
||||||
MV_CHECK,
|
QUIET_CHECKS,
|
||||||
MV_NON_CAPTURE_CHECK,
|
EVASIONS,
|
||||||
MV_EVASION,
|
NON_EVASIONS,
|
||||||
MV_NON_EVASION,
|
LEGAL
|
||||||
MV_LEGAL
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class Position;
|
class Position;
|
||||||
|
|
||||||
template<MoveType>
|
template<GenType>
|
||||||
MoveStack* generate(const Position& pos, MoveStack* mlist);
|
MoveStack* generate(const Position& pos, MoveStack* mlist);
|
||||||
|
|
||||||
/// The MoveList struct is a simple wrapper around generate(), sometimes comes
|
/// The MoveList struct is a simple wrapper around generate(), sometimes comes
|
||||||
/// handy to use this class instead of the low level generate() function.
|
/// handy to use this class instead of the low level generate() function.
|
||||||
template<MoveType T>
|
template<GenType T>
|
||||||
struct MoveList {
|
struct MoveList {
|
||||||
|
|
||||||
explicit MoveList(const Position& pos) : cur(mlist), last(generate<T>(pos, mlist)) {}
|
explicit MoveList(const Position& pos) : cur(mlist), last(generate<T>(pos, mlist)) {}
|
||||||
void operator++() { cur++; }
|
void operator++() { cur++; }
|
||||||
bool end() const { return cur == last; }
|
bool end() const { return cur == last; }
|
||||||
Move move() const { return cur->move; }
|
Move move() const { return cur->move; }
|
||||||
int size() const { return int(last - mlist); }
|
size_t size() const { return last - mlist; }
|
||||||
|
bool contains(Move m) const {
|
||||||
|
for (const MoveStack* it(mlist); it != last; ++it) if (it->move == m) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
MoveStack mlist[MAX_MOVES];
|
MoveStack mlist[MAX_MOVES];
|
||||||
|
|||||||
+210
-232
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -18,223 +18,145 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
|
||||||
#include "movegen.h"
|
|
||||||
#include "movepick.h"
|
#include "movepick.h"
|
||||||
#include "search.h"
|
#include "thread.h"
|
||||||
#include "types.h"
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
enum MovegenPhase {
|
enum Sequencer {
|
||||||
PH_TT_MOVE, // Transposition table move
|
MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
|
||||||
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= captureThreshold (captureThreshold <= 0)
|
EVASION, EVASIONS_S2,
|
||||||
PH_GOOD_PROBCUT, // Queen promotions and captures with SEE values > captureThreshold (captureThreshold >= 0)
|
QSEARCH_0, CAPTURES_S3, QUIET_CHECKS_S3,
|
||||||
PH_KILLERS, // Killer moves from the current ply
|
QSEARCH_1, CAPTURES_S4,
|
||||||
PH_NONCAPTURES_1, // Non-captures and underpromotions with positive score
|
PROBCUT, CAPTURES_S5,
|
||||||
PH_NONCAPTURES_2, // Non-captures and underpromotions with non-positive score
|
RECAPTURE, CAPTURES_S6,
|
||||||
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < captureThreshold (captureThreshold <= 0)
|
STOP
|
||||||
PH_EVASIONS, // Check evasions
|
|
||||||
PH_QCAPTURES, // Captures in quiescence search
|
|
||||||
PH_QRECAPTURES, // Recaptures in quiescence search
|
|
||||||
PH_QCHECKS, // Non-capture checks in quiescence search
|
|
||||||
PH_STOP
|
|
||||||
};
|
};
|
||||||
|
|
||||||
CACHE_LINE_ALIGNMENT
|
// Our insertion sort, guaranteed to be stable, as is needed
|
||||||
const uint8_t MainSearchTable[] = { PH_TT_MOVE, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES_1, PH_NONCAPTURES_2, PH_BAD_CAPTURES, PH_STOP };
|
void insertion_sort(MoveStack* begin, MoveStack* end)
|
||||||
const uint8_t EvasionTable[] = { PH_TT_MOVE, PH_EVASIONS, PH_STOP };
|
{
|
||||||
const uint8_t QsearchWithChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_QCHECKS, PH_STOP };
|
MoveStack tmp, *p, *q;
|
||||||
const uint8_t QsearchWithoutChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_STOP };
|
|
||||||
const uint8_t QsearchRecapturesTable[] = { PH_TT_MOVE, PH_QRECAPTURES, PH_STOP };
|
for (p = begin + 1; p < end; ++p)
|
||||||
const uint8_t ProbCutTable[] = { PH_TT_MOVE, PH_GOOD_PROBCUT, PH_STOP };
|
{
|
||||||
|
tmp = *p;
|
||||||
|
for (q = p; q != begin && *(q-1) < tmp; --q)
|
||||||
|
*q = *(q-1);
|
||||||
|
*q = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Unary predicate used by std::partition to split positive scores from remaining
|
// 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.
|
// ones so to sort separately the two sets, and with the second sort delayed.
|
||||||
inline bool has_positive_score(const MoveStack& move) { return move.score > 0; }
|
inline bool has_positive_score(const MoveStack& ms) { return ms.score > 0; }
|
||||||
|
|
||||||
// Picks and pushes to the front the best move in range [firstMove, lastMove),
|
// 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
|
// it is faster than sorting all the moves in advance when moves are few, as
|
||||||
// normally are the possible captures.
|
// normally are the possible captures.
|
||||||
inline MoveStack* pick_best(MoveStack* firstMove, MoveStack* lastMove)
|
inline MoveStack* pick_best(MoveStack* begin, MoveStack* end)
|
||||||
{
|
{
|
||||||
std::swap(*firstMove, *std::max_element(firstMove, lastMove));
|
std::swap(*begin, *std::max_element(begin, end));
|
||||||
return firstMove;
|
return begin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Constructors for the MovePicker class. As arguments we pass information
|
|
||||||
|
/// Constructors of the MovePicker class. As arguments we pass information
|
||||||
/// to help it to return the presumably good moves first, to decide which
|
/// 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
|
/// moves to return (in the quiescence search, for instance, we only want to
|
||||||
/// search captures, promotions and some checks) and about how important good
|
/// search captures, promotions and some checks) and about how important good
|
||||||
/// move ordering is at the current node.
|
/// move ordering is at the current node.
|
||||||
|
|
||||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
|
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
|
||||||
Search::Stack* ss, Value beta) : pos(p), H(h), depth(d) {
|
Search::Stack* s, Value beta) : pos(p), Hist(h), depth(d) {
|
||||||
captureThreshold = 0;
|
|
||||||
badCaptures = moves + MAX_MOVES;
|
|
||||||
|
|
||||||
assert(d > DEPTH_ZERO);
|
assert(d > DEPTH_ZERO);
|
||||||
|
|
||||||
if (p.in_check())
|
captureThreshold = 0;
|
||||||
{
|
cur = end = moves;
|
||||||
killers[0].move = killers[1].move = MOVE_NONE;
|
endBadCaptures = moves + MAX_MOVES - 1;
|
||||||
phasePtr = EvasionTable;
|
ss = s;
|
||||||
}
|
|
||||||
|
if (p.checkers())
|
||||||
|
phase = EVASION;
|
||||||
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
phase = MAIN_SEARCH;
|
||||||
|
|
||||||
killers[0].move = ss->killers[0];
|
killers[0].move = ss->killers[0];
|
||||||
killers[1].move = ss->killers[1];
|
killers[1].move = ss->killers[1];
|
||||||
|
|
||||||
// Consider sligtly negative captures as good if at low depth and far from beta
|
// Consider sligtly negative captures as good if at low depth and far from beta
|
||||||
if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
|
if (ss && ss->staticEval < beta - PawnValueMg && d < 3 * ONE_PLY)
|
||||||
captureThreshold = -PawnValueMidgame;
|
captureThreshold = -PawnValueMg;
|
||||||
|
|
||||||
// Consider negative captures as good if still enough to reach beta
|
// Consider negative captures as good if still enough to reach beta
|
||||||
else if (ss && ss->eval > beta)
|
else if (ss && ss->staticEval > beta)
|
||||||
captureThreshold = beta - ss->eval;
|
captureThreshold = beta - ss->staticEval;
|
||||||
|
|
||||||
phasePtr = MainSearchTable;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||||
phasePtr += int(ttMove == MOVE_NONE) - 1;
|
end += (ttMove != MOVE_NONE);
|
||||||
go_next_phase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h, Square recaptureSq)
|
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
|
||||||
: pos(p), H(h) {
|
Square sq) : pos(p), Hist(h), cur(moves), end(moves) {
|
||||||
|
|
||||||
assert(d <= DEPTH_ZERO);
|
assert(d <= DEPTH_ZERO);
|
||||||
|
|
||||||
if (p.in_check())
|
if (p.checkers())
|
||||||
phasePtr = EvasionTable;
|
phase = EVASION;
|
||||||
else if (d >= DEPTH_QS_CHECKS)
|
|
||||||
phasePtr = QsearchWithChecksTable;
|
|
||||||
else if (d >= DEPTH_QS_RECAPTURES)
|
|
||||||
{
|
|
||||||
phasePtr = QsearchWithoutChecksTable;
|
|
||||||
|
|
||||||
// Skip TT move if is not a capture or a promotion, this avoids
|
else if (d > DEPTH_QS_NO_CHECKS)
|
||||||
// qsearch tree explosion due to a possible perpetual check or
|
phase = QSEARCH_0;
|
||||||
// similar rare cases when TT table is full.
|
|
||||||
if (ttm != MOVE_NONE && !pos.is_capture_or_promotion(ttm))
|
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;
|
ttm = MOVE_NONE;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
phasePtr = QsearchRecapturesTable;
|
phase = RECAPTURE;
|
||||||
recaptureSquare = recaptureSq;
|
recaptureSquare = sq;
|
||||||
ttm = MOVE_NONE;
|
ttm = MOVE_NONE;
|
||||||
}
|
}
|
||||||
|
|
||||||
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||||
phasePtr += int(ttMove == MOVE_NONE) - 1;
|
end += (ttMove != MOVE_NONE);
|
||||||
go_next_phase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType parentCapture)
|
MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType pt)
|
||||||
: pos(p), H(h) {
|
: pos(p), Hist(h), cur(moves), end(moves) {
|
||||||
|
|
||||||
assert (!pos.in_check());
|
assert(!pos.checkers());
|
||||||
|
|
||||||
// In ProbCut we consider only captures better than parent's move
|
phase = PROBCUT;
|
||||||
captureThreshold = PieceValueMidgame[Piece(parentCapture)];
|
|
||||||
phasePtr = ProbCutTable;
|
|
||||||
|
|
||||||
if ( ttm != MOVE_NONE
|
|
||||||
&& (!pos.is_capture(ttm) || pos.see(ttm) <= captureThreshold))
|
|
||||||
ttm = MOVE_NONE;
|
|
||||||
|
|
||||||
|
// 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);
|
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
|
||||||
phasePtr += int(ttMove == MOVE_NONE) - 1;
|
|
||||||
go_next_phase();
|
if (ttMove && (!pos.is_capture(ttMove) || pos.see(ttMove) <= captureThreshold))
|
||||||
|
ttMove = MOVE_NONE;
|
||||||
|
|
||||||
|
end += (ttMove != MOVE_NONE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// MovePicker::go_next_phase() generates, scores and sorts the next bunch
|
/// score() assign a numerical move ordering score to each move in a move list.
|
||||||
/// of moves when there are no more moves to try for the current phase.
|
/// The moves with highest scores will be picked first.
|
||||||
|
template<>
|
||||||
void MovePicker::go_next_phase() {
|
void MovePicker::score<CAPTURES>() {
|
||||||
|
|
||||||
curMove = moves;
|
|
||||||
phase = *(++phasePtr);
|
|
||||||
switch (phase) {
|
|
||||||
|
|
||||||
case PH_TT_MOVE:
|
|
||||||
lastMove = curMove + 1;
|
|
||||||
return;
|
|
||||||
|
|
||||||
case PH_GOOD_CAPTURES:
|
|
||||||
case PH_GOOD_PROBCUT:
|
|
||||||
lastMove = generate<MV_CAPTURE>(pos, moves);
|
|
||||||
score_captures();
|
|
||||||
return;
|
|
||||||
|
|
||||||
case PH_KILLERS:
|
|
||||||
curMove = killers;
|
|
||||||
lastMove = curMove + 2;
|
|
||||||
return;
|
|
||||||
|
|
||||||
case PH_NONCAPTURES_1:
|
|
||||||
lastNonCapture = lastMove = generate<MV_NON_CAPTURE>(pos, moves);
|
|
||||||
score_noncaptures();
|
|
||||||
lastMove = std::partition(curMove, lastMove, has_positive_score);
|
|
||||||
sort<MoveStack>(curMove, lastMove);
|
|
||||||
return;
|
|
||||||
|
|
||||||
case PH_NONCAPTURES_2:
|
|
||||||
curMove = lastMove;
|
|
||||||
lastMove = lastNonCapture;
|
|
||||||
if (depth >= 3 * ONE_PLY)
|
|
||||||
sort<MoveStack>(curMove, lastMove);
|
|
||||||
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_QRECAPTURES:
|
|
||||||
lastMove = generate<MV_CAPTURE>(pos, moves);
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// 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 next_move().
|
|
||||||
|
|
||||||
void MovePicker::score_captures() {
|
|
||||||
// Winning and equal captures in the main search are ordered by MVV/LVA.
|
// Winning and equal captures in the main search are ordered by MVV/LVA.
|
||||||
// Suprisingly, this appears to perform slightly better than SEE based
|
// Suprisingly, this appears to perform slightly better than SEE based
|
||||||
// move ordering. The reason is probably that in a position with a winning
|
// move ordering. The reason is probably that in a position with a winning
|
||||||
@@ -250,105 +172,152 @@ void MovePicker::score_captures() {
|
|||||||
// some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
|
// some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
|
||||||
Move m;
|
Move m;
|
||||||
|
|
||||||
// Use MVV/LVA ordering
|
for (MoveStack* it = moves; it != end; ++it)
|
||||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
|
||||||
{
|
{
|
||||||
m = cur->move;
|
m = it->move;
|
||||||
cur->score = PieceValueMidgame[pos.piece_on(move_to(m))]
|
it->score = PieceValue[MG][pos.piece_on(to_sq(m))]
|
||||||
- type_of(pos.piece_on(move_from(m)));
|
- type_of(pos.piece_moved(m));
|
||||||
|
|
||||||
if (is_promotion(m))
|
if (type_of(m) == PROMOTION)
|
||||||
cur->score += PieceValueMidgame[Piece(promotion_piece_type(m))];
|
it->score += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
|
||||||
|
|
||||||
|
else if (type_of(m) == ENPASSANT)
|
||||||
|
it->score += PieceValue[MG][PAWN];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void MovePicker::score_noncaptures() {
|
template<>
|
||||||
|
void MovePicker::score<QUIETS>() {
|
||||||
|
|
||||||
Move m;
|
Move m;
|
||||||
Square from;
|
|
||||||
|
|
||||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
for (MoveStack* it = moves; it != end; ++it)
|
||||||
{
|
{
|
||||||
m = cur->move;
|
m = it->move;
|
||||||
from = move_from(m);
|
it->score = Hist[pos.piece_moved(m)][to_sq(m)];
|
||||||
cur->score = H.value(pos.piece_on(from), move_to(m));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void MovePicker::score_evasions() {
|
template<>
|
||||||
// Try good captures ordered by MVV/LVA, then non-captures if
|
void MovePicker::score<EVASIONS>() {
|
||||||
// destination square is not under attack, ordered by history
|
// Try good captures ordered by MVV/LVA, then non-captures if destination square
|
||||||
// value, and at the end bad-captures and non-captures with a
|
// is not under attack, ordered by history value, then bad-captures and quiet
|
||||||
// negative SEE. This last group is ordered by the SEE score.
|
// moves with a negative SEE. This last group is ordered by the SEE score.
|
||||||
Move m;
|
Move m;
|
||||||
int seeScore;
|
int seeScore;
|
||||||
|
|
||||||
// Skip if we don't have at least two moves to order
|
for (MoveStack* it = moves; it != end; ++it)
|
||||||
if (lastMove < moves + 2)
|
{
|
||||||
|
m = it->move;
|
||||||
|
if ((seeScore = pos.see_sign(m)) < 0)
|
||||||
|
it->score = seeScore - History::Max; // 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::Max;
|
||||||
|
else
|
||||||
|
it->score = Hist[pos.piece_moved(m)][to_sq(m)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// 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;
|
return;
|
||||||
|
|
||||||
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
case KILLERS_S1:
|
||||||
{
|
cur = killers;
|
||||||
m = cur->move;
|
end = cur + 2;
|
||||||
if ((seeScore = pos.see_sign(m)) < 0)
|
return;
|
||||||
cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
|
|
||||||
else if (pos.is_capture(m))
|
case QUIETS_1_S1:
|
||||||
cur->score = PieceValueMidgame[pos.piece_on(move_to(m))]
|
endQuiets = end = generate<QUIETS>(pos, moves);
|
||||||
- type_of(pos.piece_on(move_from(m))) + History::MaxValue;
|
score<QUIETS>();
|
||||||
else
|
end = std::partition(cur, end, has_positive_score);
|
||||||
cur->score = H.value(pos.piece_on(move_from(m)), move_to(m));
|
insertion_sort(cur, end);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case QUIETS_2_S1:
|
||||||
|
cur = end;
|
||||||
|
end = endQuiets;
|
||||||
|
if (depth >= 3 * ONE_PLY)
|
||||||
|
insertion_sort(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);
|
||||||
|
if (end > moves + 1)
|
||||||
|
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::next_move() {
|
/// next_move() is the most important method of the MovePicker class. It returns
|
||||||
|
/// a new pseudo legal move every time 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 returning the ttMove if has already been searched previously.
|
||||||
|
template<>
|
||||||
|
Move MovePicker::next_move<false>() {
|
||||||
|
|
||||||
Move move;
|
Move move;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
while (curMove == lastMove)
|
while (cur == end)
|
||||||
go_next_phase();
|
generate_next();
|
||||||
|
|
||||||
switch (phase) {
|
switch (phase) {
|
||||||
|
|
||||||
case PH_TT_MOVE:
|
case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
|
||||||
curMove++;
|
cur++;
|
||||||
return ttMove;
|
return ttMove;
|
||||||
break;
|
|
||||||
|
|
||||||
case PH_GOOD_CAPTURES:
|
case CAPTURES_S1:
|
||||||
move = pick_best(curMove++, lastMove)->move;
|
move = pick_best(cur++, end)->move;
|
||||||
if (move != ttMove)
|
if (move != ttMove)
|
||||||
{
|
{
|
||||||
assert(captureThreshold <= 0); // Otherwise we must use see instead of see_sign
|
assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
|
||||||
|
|
||||||
// Check for a non negative SEE now
|
if (pos.see_sign(move) >= captureThreshold)
|
||||||
int seeValue = pos.see_sign(move);
|
|
||||||
if (seeValue >= captureThreshold)
|
|
||||||
return move;
|
return move;
|
||||||
|
|
||||||
// Losing capture, move it to the tail of the array
|
// Losing capture, move it to the tail of the array
|
||||||
(--badCaptures)->move = move;
|
(endBadCaptures--)->move = move;
|
||||||
badCaptures->score = seeValue;
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_GOOD_PROBCUT:
|
case KILLERS_S1:
|
||||||
move = pick_best(curMove++, lastMove)->move;
|
move = (cur++)->move;
|
||||||
if ( move != ttMove
|
|
||||||
&& pos.see(move) > captureThreshold)
|
|
||||||
return move;
|
|
||||||
break;
|
|
||||||
|
|
||||||
case PH_KILLERS:
|
|
||||||
move = (curMove++)->move;
|
|
||||||
if ( move != MOVE_NONE
|
if ( move != MOVE_NONE
|
||||||
&& pos.is_pseudo_legal(move)
|
&& pos.is_pseudo_legal(move)
|
||||||
&& move != ttMove
|
&& move != ttMove
|
||||||
@@ -356,44 +325,53 @@ Move MovePicker::next_move() {
|
|||||||
return move;
|
return move;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_NONCAPTURES_1:
|
case QUIETS_1_S1: case QUIETS_2_S1:
|
||||||
case PH_NONCAPTURES_2:
|
move = (cur++)->move;
|
||||||
move = (curMove++)->move;
|
|
||||||
if ( move != ttMove
|
if ( move != ttMove
|
||||||
&& move != killers[0].move
|
&& move != killers[0].move
|
||||||
&& move != killers[1].move)
|
&& move != killers[1].move)
|
||||||
return move;
|
return move;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_BAD_CAPTURES:
|
case BAD_CAPTURES_S1:
|
||||||
move = pick_best(curMove++, lastMove)->move;
|
return (cur--)->move;
|
||||||
return move;
|
|
||||||
|
|
||||||
case PH_EVASIONS:
|
case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
|
||||||
case PH_QCAPTURES:
|
move = pick_best(cur++, end)->move;
|
||||||
move = pick_best(curMove++, lastMove)->move;
|
|
||||||
if (move != ttMove)
|
if (move != ttMove)
|
||||||
return move;
|
return move;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_QRECAPTURES:
|
case CAPTURES_S5:
|
||||||
move = (curMove++)->move;
|
move = pick_best(cur++, end)->move;
|
||||||
if (move_to(move) == recaptureSquare)
|
if (move != ttMove && pos.see(move) > captureThreshold)
|
||||||
return move;
|
return move;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_QCHECKS:
|
case CAPTURES_S6:
|
||||||
move = (curMove++)->move;
|
move = pick_best(cur++, end)->move;
|
||||||
|
if (to_sq(move) == recaptureSquare)
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case QUIET_CHECKS_S3:
|
||||||
|
move = (cur++)->move;
|
||||||
if (move != ttMove)
|
if (move != ttMove)
|
||||||
return move;
|
return move;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PH_STOP:
|
case STOP:
|
||||||
return MOVE_NONE;
|
return MOVE_NONE;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
assert(false);
|
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 must be lock protected by the caller.
|
||||||
|
template<>
|
||||||
|
Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }
|
||||||
|
|||||||
+53
-19
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,18 +20,54 @@
|
|||||||
#if !defined MOVEPICK_H_INCLUDED
|
#if !defined MOVEPICK_H_INCLUDED
|
||||||
#define MOVEPICK_H_INCLUDED
|
#define MOVEPICK_H_INCLUDED
|
||||||
|
|
||||||
#include "history.h"
|
#include <algorithm> // For std::max
|
||||||
|
#include <cstring> // For memset
|
||||||
|
|
||||||
|
#include "movegen.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
/// MovePicker is a class which is used to pick one pseudo legal move at a time
|
|
||||||
/// from the current position. It is initialized with a Position object and a few
|
/// The Stats struct stores moves statistics. According to the template parameter
|
||||||
/// moves we have reason to believe are good. The most important method is
|
/// the class can store both History and Gains type statistics. History records
|
||||||
/// MovePicker::next_move(), which returns a new pseudo legal move each time
|
/// how often different moves have been successful or unsuccessful during the
|
||||||
/// it is called, until there are no moves left, when MOVE_NONE is returned.
|
/// current search and is used for reduction and move ordering decisions. Gains
|
||||||
/// In order to improve the efficiency of the alpha beta algorithm, MovePicker
|
/// records the move's best evaluation gain from one ply to the next and is used
|
||||||
/// attempts to return the moves which are most likely to get a cut-off first.
|
/// for pruning decisions. Entries are stored according only to moving piece and
|
||||||
|
/// destination square, in particular two moves with different origin but same
|
||||||
|
/// destination and same piece will be considered identical.
|
||||||
|
template<bool Gain>
|
||||||
|
struct Stats {
|
||||||
|
|
||||||
|
static const Value Max = Value(2000);
|
||||||
|
|
||||||
|
const Value* operator[](Piece p) const { return &table[p][0]; }
|
||||||
|
void clear() { memset(table, 0, sizeof(table)); }
|
||||||
|
|
||||||
|
void update(Piece p, Square to, Value v) {
|
||||||
|
|
||||||
|
if (Gain)
|
||||||
|
table[p][to] = std::max(v, table[p][to] - 1);
|
||||||
|
|
||||||
|
else if (abs(table[p][to] + v) < Max)
|
||||||
|
table[p][to] += v;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Value table[PIECE_NB][SQUARE_NB];
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef Stats<false> History;
|
||||||
|
typedef Stats<true> Gains;
|
||||||
|
|
||||||
|
|
||||||
|
/// 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 {
|
class MovePicker {
|
||||||
|
|
||||||
@@ -39,25 +75,23 @@ class MovePicker {
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
MovePicker(const Position&, Move, Depth, const History&, Search::Stack*, Value);
|
MovePicker(const Position&, Move, Depth, const History&, Search::Stack*, Value);
|
||||||
MovePicker(const Position&, Move, Depth, const History&, Square recaptureSq);
|
MovePicker(const Position&, Move, Depth, const History&, Square);
|
||||||
MovePicker(const Position&, Move, const History&, PieceType parentCapture);
|
MovePicker(const Position&, Move, const History&, PieceType);
|
||||||
Move next_move();
|
template<bool SpNode> Move next_move();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void score_captures();
|
template<GenType> void score();
|
||||||
void score_noncaptures();
|
void generate_next();
|
||||||
void score_evasions();
|
|
||||||
void go_next_phase();
|
|
||||||
|
|
||||||
const Position& pos;
|
const Position& pos;
|
||||||
const History& H;
|
const History& Hist;
|
||||||
|
Search::Stack* ss;
|
||||||
Depth depth;
|
Depth depth;
|
||||||
Move ttMove;
|
Move ttMove;
|
||||||
MoveStack killers[2];
|
MoveStack killers[2];
|
||||||
Square recaptureSquare;
|
Square recaptureSquare;
|
||||||
int captureThreshold, phase;
|
int captureThreshold, phase;
|
||||||
const uint8_t* phasePtr;
|
MoveStack *cur, *end, *endQuiets, *endBadCaptures;
|
||||||
MoveStack *curMove, *lastMove, *lastNonCapture, *badCaptures;
|
|
||||||
MoveStack moves[MAX_MOVES];
|
MoveStack moves[MAX_MOVES];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2013 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 <stack>
|
||||||
|
|
||||||
|
#include "movegen.h"
|
||||||
|
#include "notation.h"
|
||||||
|
#include "position.h"
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
static const char* PieceToChar[COLOR_NB] = { " 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[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(MoveList<LEGAL>(pos).contains(m));
|
||||||
|
|
||||||
|
Bitboard others, b;
|
||||||
|
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[WHITE][pt]; // Upper case
|
||||||
|
|
||||||
|
// Disambiguation if we have more then one piece of type 'pt' that can
|
||||||
|
// reach 'to' with a legal move.
|
||||||
|
others = b = (pos.attacks_from(pc, to) & pos.pieces(us, pt)) ^ from;
|
||||||
|
|
||||||
|
while (b)
|
||||||
|
{
|
||||||
|
Move move = make_move(pop_lsb(&b), to);
|
||||||
|
if (!pos.pl_move_is_legal(move, pos.pinned_pieces()))
|
||||||
|
others ^= from_sq(move);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (others)
|
||||||
|
{
|
||||||
|
if (!(others & file_bb(from)))
|
||||||
|
san += file_to_char(file_of(from));
|
||||||
|
|
||||||
|
else if (!(others & rank_bb(from)))
|
||||||
|
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[WHITE][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;
|
||||||
|
|
||||||
|
std::stack<StateInfo> st;
|
||||||
|
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;
|
||||||
|
|
||||||
|
st.push(StateInfo());
|
||||||
|
pos.do_move(*m++, st.top());
|
||||||
|
}
|
||||||
|
|
||||||
|
while (m != pv)
|
||||||
|
pos.undo_move(*--m);
|
||||||
|
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
@@ -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-2013 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)
|
||||||
+135
-83
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -26,95 +26,64 @@
|
|||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
|
#define V Value
|
||||||
#define S(mg, eg) make_score(mg, eg)
|
#define S(mg, eg) make_score(mg, eg)
|
||||||
|
|
||||||
// Doubled pawn penalty by opposed flag and file
|
// Doubled pawn penalty by opposed flag and file
|
||||||
const Score DoubledPawnPenalty[2][8] = {
|
const Score DoubledPawnPenalty[2][FILE_NB] = {
|
||||||
{ S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
{ S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
||||||
S(23, 48), S(23, 48), S(20, 48), S(13, 43) },
|
S(23, 48), S(23, 48), S(20, 48), S(13, 43) },
|
||||||
{ S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
{ S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
||||||
S(23, 48), S(23, 48), S(20, 48), S(13, 43) }};
|
S(23, 48), S(23, 48), S(20, 48), S(13, 43) }};
|
||||||
|
|
||||||
// Isolated pawn penalty by opposed flag and file
|
// Isolated pawn penalty by opposed flag and file
|
||||||
const Score IsolatedPawnPenalty[2][8] = {
|
const Score IsolatedPawnPenalty[2][FILE_NB] = {
|
||||||
{ S(37, 45), S(54, 52), S(60, 52), S(60, 52),
|
{ S(37, 45), S(54, 52), S(60, 52), S(60, 52),
|
||||||
S(60, 52), S(60, 52), S(54, 52), S(37, 45) },
|
S(60, 52), S(60, 52), S(54, 52), S(37, 45) },
|
||||||
{ S(25, 30), S(36, 35), S(40, 35), S(40, 35),
|
{ S(25, 30), S(36, 35), S(40, 35), S(40, 35),
|
||||||
S(40, 35), S(40, 35), S(36, 35), S(25, 30) }};
|
S(40, 35), S(40, 35), S(36, 35), S(25, 30) }};
|
||||||
|
|
||||||
// Backward pawn penalty by opposed flag and file
|
// Backward pawn penalty by opposed flag and file
|
||||||
const Score BackwardPawnPenalty[2][8] = {
|
const Score BackwardPawnPenalty[2][FILE_NB] = {
|
||||||
{ S(30, 42), S(43, 46), S(49, 46), S(49, 46),
|
{ S(30, 42), S(43, 46), S(49, 46), S(49, 46),
|
||||||
S(49, 46), S(49, 46), S(43, 46), S(30, 42) },
|
S(49, 46), S(49, 46), S(43, 46), S(30, 42) },
|
||||||
{ S(20, 28), S(29, 31), S(33, 31), S(33, 31),
|
{ S(20, 28), S(29, 31), S(33, 31), S(33, 31),
|
||||||
S(33, 31), S(33, 31), S(29, 31), S(20, 28) }};
|
S(33, 31), S(33, 31), S(29, 31), S(20, 28) }};
|
||||||
|
|
||||||
// Pawn chain membership bonus by file
|
// Pawn chain membership bonus by file
|
||||||
const Score ChainBonus[8] = {
|
const Score ChainBonus[FILE_NB] = {
|
||||||
S(11,-1), S(13,-1), S(13,-1), S(14,-1),
|
S(11,-1), S(13,-1), S(13,-1), S(14,-1),
|
||||||
S(14,-1), S(13,-1), S(13,-1), S(11,-1)
|
S(14,-1), S(13,-1), S(13,-1), S(11,-1)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Candidate passed pawn bonus by rank
|
// Candidate passed pawn bonus by rank
|
||||||
const Score CandidateBonus[8] = {
|
const Score CandidateBonus[RANK_NB] = {
|
||||||
S( 0, 0), S( 6, 13), S(6,13), S(14,29),
|
S( 0, 0), S( 6, 13), S(6,13), S(14,29),
|
||||||
S(34,68), S(83,166), S(0, 0), S( 0, 0)
|
S(34,68), S(83,166), S(0, 0), S( 0, 0)
|
||||||
};
|
};
|
||||||
|
|
||||||
const Score PawnStructureWeight = S(233, 201);
|
const Score PawnStructureWeight = S(233, 201);
|
||||||
|
|
||||||
|
// Weakness of our pawn shelter in front of the king indexed by [king pawn][rank]
|
||||||
|
const Value ShelterWeakness[2][RANK_NB] =
|
||||||
|
{ { 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) } };
|
||||||
|
|
||||||
|
// Danger of enemy pawns moving toward our king indexed by [pawn blocked][rank]
|
||||||
|
const Value StormDanger[2][RANK_NB] =
|
||||||
|
{ { 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 S
|
||||||
|
#undef V
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// PawnInfoTable::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.
|
|
||||||
|
|
||||||
PawnInfo* PawnInfoTable::pawn_info(const Position& pos) const {
|
|
||||||
|
|
||||||
Key key = pos.pawn_key();
|
|
||||||
PawnInfo* pi = probe(key);
|
|
||||||
|
|
||||||
// If pi->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;
|
|
||||||
|
|
||||||
// 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;
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
|
|
||||||
pi->value = apply_weight(pi->value, PawnStructureWeight);
|
|
||||||
|
|
||||||
return pi;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// PawnInfoTable::evaluate_pawns() evaluates each pawn of the given color
|
|
||||||
|
|
||||||
template<Color Us>
|
template<Color Us>
|
||||||
Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
Score evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||||
Bitboard theirPawns, PawnInfo* pi) {
|
Bitboard theirPawns, Pawns::Entry* e) {
|
||||||
|
|
||||||
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
|
|
||||||
@@ -135,32 +104,32 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
|||||||
r = rank_of(s);
|
r = rank_of(s);
|
||||||
|
|
||||||
// This file cannot be half open
|
// 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
|
// Our rank plus previous one. Used for chain detection
|
||||||
b = rank_bb(r) | rank_bb(Us == WHITE ? r - Rank(1) : r + Rank(1));
|
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
|
// Flag the pawn as passed, isolated, doubled or member of a pawn
|
||||||
// chain (but not the backward one).
|
// 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));
|
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
|
// Test for backward pawn
|
||||||
backward = false;
|
backward = false;
|
||||||
|
|
||||||
// If the pawn is passed, isolated, or member of a pawn chain it cannot
|
// 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.
|
// or if can capture an enemy pawn it cannot be backward either.
|
||||||
if ( !(passed | isolated | chain)
|
if ( !(passed | isolated | chain)
|
||||||
&& !(ourPawns & attack_span_mask(Them, s))
|
&& !(ourPawns & attack_span_mask(Them, s))
|
||||||
&& !(pos.attacks_from<PAWN>(s, Us) & theirPawns))
|
&& !(pos.attacks_from<PAWN>(s, Us) & theirPawns))
|
||||||
{
|
{
|
||||||
// We now know that there are no friendly pawns beside or behind this
|
// We now know that there are no friendly pawns beside or behind this
|
||||||
// pawn on neighboring files. We now check whether the pawn is
|
// pawn on adjacent files. We now check whether the pawn is
|
||||||
// backward by looking in the forward direction on the neighboring
|
// backward by looking in the forward direction on the adjacent
|
||||||
// files, and seeing whether we meet a friendly or an enemy pawn first.
|
// files, and seeing whether we meet a friendly or an enemy pawn first.
|
||||||
b = pos.attacks_from<PAWN>(s, Us);
|
b = pos.attacks_from<PAWN>(s, Us);
|
||||||
|
|
||||||
@@ -178,8 +147,8 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
|||||||
|
|
||||||
// A not passed pawn is a candidate to become passed if it is free to
|
// 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
|
// advance and if the number of friendly pawns beside or behind this
|
||||||
// pawn on neighboring files is higher or equal than the number of
|
// pawn on adjacent files is higher or equal than the number of
|
||||||
// enemy pawns in the forward direction on the neighboring files.
|
// enemy pawns in the forward direction on the adjacent files.
|
||||||
candidate = !(opposed | passed | backward | isolated)
|
candidate = !(opposed | passed | backward | isolated)
|
||||||
&& (b = attack_span_mask(Them, s + pawn_push(Us)) & ourPawns) != 0
|
&& (b = attack_span_mask(Them, s + pawn_push(Us)) & ourPawns) != 0
|
||||||
&& popcount<Max15>(b) >= popcount<Max15>(attack_span_mask(Us, s) & theirPawns);
|
&& popcount<Max15>(b) >= popcount<Max15>(attack_span_mask(Us, s) & theirPawns);
|
||||||
@@ -188,7 +157,7 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
|||||||
// full attack info to evaluate passed pawns. Only the frontmost passed
|
// full attack info to evaluate passed pawns. Only the frontmost passed
|
||||||
// pawn on each file is considered a true passed pawn.
|
// pawn on each file is considered a true passed pawn.
|
||||||
if (passed && !doubled)
|
if (passed && !doubled)
|
||||||
set_bit(&(pi->passedPawns[Us]), s);
|
e->passedPawns[Us] |= s;
|
||||||
|
|
||||||
// Score this pawn
|
// Score this pawn
|
||||||
if (isolated)
|
if (isolated)
|
||||||
@@ -206,35 +175,118 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
|||||||
if (candidate)
|
if (candidate)
|
||||||
value += CandidateBonus[relative_rank(Us, s)];
|
value += CandidateBonus[relative_rank(Us, s)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
e->pawnsOnSquares[Us][BLACK] = popcount<Max15>(ourPawns & BlackSquares);
|
||||||
|
e->pawnsOnSquares[Us][WHITE] = pos.piece_count(Us, PAWN) - e->pawnsOnSquares[Us][BLACK];
|
||||||
|
|
||||||
|
e->pawnsOnSquares[Them][BLACK] = popcount<Max15>(theirPawns & BlackSquares);
|
||||||
|
e->pawnsOnSquares[Them][WHITE] = pos.piece_count(Them, PAWN) - e->pawnsOnSquares[Them][BLACK];
|
||||||
|
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace Pawns {
|
||||||
|
|
||||||
|
/// probe() takes a position object as input, computes a Entry 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.
|
||||||
|
|
||||||
|
Entry* probe(const Position& pos, Table& entries) {
|
||||||
|
|
||||||
|
Key key = pos.pawn_key();
|
||||||
|
Entry* e = entries[key];
|
||||||
|
|
||||||
|
// 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 (e->key == key)
|
||||||
|
return e;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
e->value = evaluate_pawns<WHITE>(pos, wPawns, bPawns, e)
|
||||||
|
- evaluate_pawns<BLACK>(pos, bPawns, wPawns, e);
|
||||||
|
|
||||||
|
e->value = apply_weight(e->value, PawnStructureWeight);
|
||||||
|
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// PawnInfo::updateShelter() calculates and caches king shelter. It is called
|
/// Entry::shelter_storm() calculates shelter and storm penalties for the file
|
||||||
/// only when king square changes, about 20% of total king_shelter() calls.
|
/// the king is on, as well as the two adjacent files.
|
||||||
|
|
||||||
template<Color Us>
|
template<Color Us>
|
||||||
Score PawnInfo::updateShelter(const Position& pos, Square ksq) {
|
Value Entry::shelter_storm(const Position& pos, Square ksq) {
|
||||||
|
|
||||||
const int Shift = (Us == WHITE ? 8 : -8);
|
const Color Them = (Us == WHITE ? BLACK : WHITE);
|
||||||
|
|
||||||
Bitboard pawns;
|
Value safety = MaxSafetyBonus;
|
||||||
int r, shelter = 0;
|
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) ? FILE_B : (kf == FILE_H) ? FILE_G : kf;
|
||||||
|
|
||||||
|
for (int f = kf - 1; f <= kf + 1; f++)
|
||||||
{
|
{
|
||||||
pawns = pos.pieces(PAWN, Us) & this_and_neighboring_files_bb(file_of(ksq));
|
// Shelter penalty is higher for the pawn in front of the king
|
||||||
r = ksq & (7 << 3);
|
b = ourPawns & FileBB[f];
|
||||||
for (int i = 0; i < 3; i++)
|
rkUs = b ? rank_of(Us == WHITE ? lsb(b) : ~msb(b)) : RANK_1;
|
||||||
{
|
safety -= ShelterWeakness[f != kf][rkUs];
|
||||||
r += Shift;
|
|
||||||
shelter += BitCount8Bit[(pawns >> r) & 0xFF] << (6 - i);
|
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Entry::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 Entry::update_safety(const Position& pos, Square ksq) {
|
||||||
|
|
||||||
kingSquares[Us] = ksq;
|
kingSquares[Us] = ksq;
|
||||||
kingShelters[Us] = make_score(shelter, 0);
|
castleRights[Us] = pos.can_castle(Us);
|
||||||
return kingShelters[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
|
// Explicit template instantiation
|
||||||
template Score PawnInfo::updateShelter<WHITE>(const Position& pos, Square ksq);
|
template Score Entry::update_safety<WHITE>(const Position& pos, Square ksq);
|
||||||
template Score PawnInfo::updateShelter<BLACK>(const Position& pos, Square ksq);
|
template Score Entry::update_safety<BLACK>(const Position& pos, Square ksq);
|
||||||
|
|
||||||
|
} // namespace Pawns
|
||||||
|
|||||||
+35
-66
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,88 +20,57 @@
|
|||||||
#if !defined(PAWNS_H_INCLUDED)
|
#if !defined(PAWNS_H_INCLUDED)
|
||||||
#define PAWNS_H_INCLUDED
|
#define PAWNS_H_INCLUDED
|
||||||
|
|
||||||
|
#include "misc.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "tt.h"
|
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
const int PawnTableSize = 16384;
|
namespace Pawns {
|
||||||
|
|
||||||
/// PawnInfo is a class which contains various information about a pawn
|
/// Pawns::Entry contains various information about a pawn structure. Currently,
|
||||||
/// structure. Currently, it only includes a middle game and an end game
|
/// it only includes a middle game and end game pawn structure evaluation, and a
|
||||||
/// pawn structure evaluation, and a bitboard of passed pawns. We may want
|
/// bitboard of passed pawns. We may want to add further information in the future.
|
||||||
/// to add further information in the future. A lookup to the pawn hash
|
/// A lookup to the pawn hash table (performed by calling the probe function)
|
||||||
/// table (performed by calling the pawn_info method in a PawnInfoTable
|
/// returns a pointer to an Entry object.
|
||||||
/// object) returns a pointer to a PawnInfo object.
|
|
||||||
|
|
||||||
class PawnInfo {
|
struct Entry {
|
||||||
|
|
||||||
friend class PawnInfoTable;
|
Score pawns_value() const { return value; }
|
||||||
|
Bitboard pawn_attacks(Color c) const { return pawnAttacks[c]; }
|
||||||
public:
|
Bitboard passed_pawns(Color c) const { return passedPawns[c]; }
|
||||||
Score pawns_value() const;
|
int file_is_half_open(Color c, File f) const { return halfOpenFiles[c] & (1 << int(f)); }
|
||||||
Bitboard pawn_attacks(Color c) const;
|
int has_open_file_to_left(Color c, File f) const { return halfOpenFiles[c] & ((1 << int(f)) - 1); }
|
||||||
Bitboard passed_pawns(Color c) const;
|
int has_open_file_to_right(Color c, File f) const { return halfOpenFiles[c] & ~((1 << int(f+1)) - 1); }
|
||||||
int file_is_half_open(Color c, File f) const;
|
int pawns_on_same_color_squares(Color c, Square s) const { return pawnsOnSquares[c][!!(BlackSquares & s)]; }
|
||||||
int has_open_file_to_left(Color c, File f) const;
|
|
||||||
int has_open_file_to_right(Color c, File f) const;
|
|
||||||
|
|
||||||
template<Color Us>
|
template<Color Us>
|
||||||
Score king_shelter(const Position& pos, Square ksq);
|
Score king_safety(const Position& pos, Square ksq) {
|
||||||
|
|
||||||
|
return kingSquares[Us] == ksq && castleRights[Us] == pos.can_castle(Us)
|
||||||
|
? kingSafety[Us] : update_safety<Us>(pos, ksq);
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
|
||||||
template<Color Us>
|
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;
|
Key key;
|
||||||
Bitboard passedPawns[2];
|
Bitboard passedPawns[COLOR_NB];
|
||||||
Bitboard pawnAttacks[2];
|
Bitboard pawnAttacks[COLOR_NB];
|
||||||
Square kingSquares[2];
|
Square kingSquares[COLOR_NB];
|
||||||
|
int minKPdistance[COLOR_NB];
|
||||||
|
int castleRights[COLOR_NB];
|
||||||
Score value;
|
Score value;
|
||||||
int halfOpenFiles[2];
|
int halfOpenFiles[COLOR_NB];
|
||||||
Score kingShelters[2];
|
Score kingSafety[COLOR_NB];
|
||||||
|
int pawnsOnSquares[COLOR_NB][COLOR_NB];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
typedef HashTable<Entry, 16384> Table;
|
||||||
|
|
||||||
/// The PawnInfoTable class represents a pawn hash table. The most important
|
Entry* probe(const Position& pos, Table& entries);
|
||||||
/// method is pawn_info, which returns a pointer to a PawnInfo object.
|
|
||||||
|
|
||||||
class PawnInfoTable : public SimpleHash<PawnInfo, PawnTableSize> {
|
|
||||||
public:
|
|
||||||
PawnInfo* pawn_info(const Position& pos) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
template<Color Us>
|
|
||||||
static Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
inline Score PawnInfo::pawns_value() const {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard PawnInfo::pawn_attacks(Color c) const {
|
|
||||||
return pawnAttacks[c];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard PawnInfo::passed_pawns(Color c) const {
|
|
||||||
return passedPawns[c];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int PawnInfo::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 {
|
|
||||||
return halfOpenFiles[c] & ((1 << int(f)) - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int PawnInfo::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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // !defined(PAWNS_H_INCLUDED)
|
#endif // !defined(PAWNS_H_INCLUDED)
|
||||||
|
|||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2013 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>
|
||||||
|
# include <unistd.h> // Used by sysconf(_SC_NPROCESSORS_ONLN)
|
||||||
|
#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;
|
||||||
|
|
||||||
|
// On Windows 95 and 98 parameter lpThreadId my not be null
|
||||||
|
inline DWORD* dwWin9xKludge() { static DWORD dw; return &dw; }
|
||||||
|
|
||||||
|
# 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,dwWin9xKludge()), x != NULL)
|
||||||
|
# define thread_join(x) { WaitForSingleObject(x, INFINITE); CloseHandle(x); }
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // !defined(PLATFORM_H_INCLUDED)
|
||||||
+596
-805
File diff suppressed because it is too large
Load Diff
+129
-179
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -21,6 +21,7 @@
|
|||||||
#define POSITION_H_INCLUDED
|
#define POSITION_H_INCLUDED
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
@@ -29,6 +30,7 @@
|
|||||||
/// The checkInfo struct is initialized at c'tor time and keeps info used
|
/// The checkInfo struct is initialized at c'tor time and keeps info used
|
||||||
/// to detect if a move gives check.
|
/// to detect if a move gives check.
|
||||||
class Position;
|
class Position;
|
||||||
|
struct Thread;
|
||||||
|
|
||||||
struct CheckInfo {
|
struct CheckInfo {
|
||||||
|
|
||||||
@@ -36,20 +38,21 @@ struct CheckInfo {
|
|||||||
|
|
||||||
Bitboard dcCandidates;
|
Bitboard dcCandidates;
|
||||||
Bitboard pinned;
|
Bitboard pinned;
|
||||||
Bitboard checkSq[8];
|
Bitboard checkSq[PIECE_TYPE_NB];
|
||||||
|
Square ksq;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
/// The StateInfo struct stores information we need to restore a Position
|
/// The StateInfo struct stores information we need to restore a Position
|
||||||
/// object to its previous state when we retract a move. Whenever a move
|
/// object to its previous state when we retract a move. Whenever a move
|
||||||
/// is made on the board (by calling Position::do_move), an StateInfo object
|
/// is made on the board (by calling Position::do_move), a StateInfo object
|
||||||
/// must be passed as a parameter.
|
/// must be passed as a parameter.
|
||||||
|
|
||||||
struct StateInfo {
|
struct StateInfo {
|
||||||
Key pawnKey, materialKey;
|
Key pawnKey, materialKey;
|
||||||
Value npMaterial[2];
|
Value npMaterial[COLOR_NB];
|
||||||
int castleRights, rule50, pliesFromNull;
|
int castleRights, rule50, pliesFromNull;
|
||||||
Score value;
|
Score psqScore;
|
||||||
Square epSquare;
|
Square epSquare;
|
||||||
|
|
||||||
Key key;
|
Key key;
|
||||||
@@ -59,6 +62,11 @@ struct StateInfo {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// When making a move the current StateInfo up to 'key' excluded is copied to
|
||||||
|
/// the new one. Here we calculate the quad words (64bits) needed to be copied.
|
||||||
|
const size_t StateCopySize64 = offsetof(StateInfo, key) / sizeof(uint64_t) + 1;
|
||||||
|
|
||||||
|
|
||||||
/// The position data structure. A position consists of the following data:
|
/// The position data structure. A position consists of the following data:
|
||||||
///
|
///
|
||||||
/// * For each piece type, a bitboard representing the squares occupied
|
/// * For each piece type, a bitboard representing the squares occupied
|
||||||
@@ -82,64 +90,43 @@ struct StateInfo {
|
|||||||
/// * A counter for detecting 50 move rule draws.
|
/// * A counter for detecting 50 move rule draws.
|
||||||
|
|
||||||
class Position {
|
class Position {
|
||||||
|
|
||||||
// No copy c'tor or assignment operator allowed
|
|
||||||
Position(const Position&);
|
|
||||||
Position& operator=(const Position&);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
Position() {}
|
Position() {}
|
||||||
Position(const Position& pos, int th) { copy(pos, th); }
|
Position(const Position& p, Thread* t) { *this = p; thisThread = t; }
|
||||||
Position(const std::string& fen, bool isChess960, int th);
|
Position(const std::string& f, bool c960, Thread* t) { set(f, c960, t); }
|
||||||
|
Position& operator=(const Position&);
|
||||||
|
|
||||||
// Text input/output
|
// Text input/output
|
||||||
void copy(const Position& pos, int th);
|
void set(const std::string& fen, bool isChess960, Thread* th);
|
||||||
void from_fen(const std::string& fen, bool isChess960);
|
const std::string fen() const;
|
||||||
const std::string to_fen() const;
|
const std::string pretty(Move m = MOVE_NONE) const;
|
||||||
void print(Move m = MOVE_NONE) const;
|
|
||||||
|
|
||||||
// The piece on a given square
|
// Position representation
|
||||||
Piece piece_on(Square s) const;
|
Bitboard pieces() const;
|
||||||
bool square_is_empty(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(Color c) const;
|
|
||||||
Bitboard pieces(PieceType pt) 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) const;
|
||||||
Bitboard pieces(PieceType pt1, PieceType pt2, Color c) const;
|
Bitboard pieces(Color c) const;
|
||||||
|
Bitboard pieces(Color c, PieceType pt) const;
|
||||||
// Number of pieces of each color and type
|
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;
|
int piece_count(Color c, PieceType pt) const;
|
||||||
|
|
||||||
// The en passant square
|
// Castling
|
||||||
Square ep_square() const;
|
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
|
// Checking
|
||||||
Square king_square(Color c) const;
|
Bitboard checkers() const;
|
||||||
|
|
||||||
// Castling rights
|
|
||||||
bool can_castle(CastleRight f) const;
|
|
||||||
bool can_castle(Color c) const;
|
|
||||||
Square castle_rook_square(CastleRight f) const;
|
|
||||||
|
|
||||||
// Bitboards for pinned pieces and discovered check candidates
|
|
||||||
Bitboard discovered_check_candidates() const;
|
Bitboard discovered_check_candidates() const;
|
||||||
Bitboard pinned_pieces() const;
|
Bitboard pinned_pieces() const;
|
||||||
|
|
||||||
// Checking pieces and under check information
|
// Attacks to/from a given square
|
||||||
Bitboard checkers() const;
|
|
||||||
bool in_check() const;
|
|
||||||
|
|
||||||
// Piece lists
|
|
||||||
const Square* piece_list(Color c, PieceType pt) const;
|
|
||||||
|
|
||||||
// Information about attacks to or from a given square
|
|
||||||
Bitboard attackers_to(Square s) const;
|
Bitboard attackers_to(Square s) const;
|
||||||
Bitboard attackers_to(Square s, Bitboard occ) const;
|
Bitboard attackers_to(Square s, Bitboard occ) const;
|
||||||
Bitboard attacks_from(Piece p, Square s) const;
|
Bitboard attacks_from(Piece p, Square s) const;
|
||||||
@@ -149,27 +136,29 @@ public:
|
|||||||
|
|
||||||
// Properties of moves
|
// Properties of moves
|
||||||
bool move_gives_check(Move m, const CheckInfo& ci) const;
|
bool move_gives_check(Move m, const CheckInfo& ci) const;
|
||||||
bool move_attacks_square(Move m, Square s) const;
|
|
||||||
bool pl_move_is_legal(Move m, Bitboard pinned) const;
|
bool pl_move_is_legal(Move m, Bitboard pinned) const;
|
||||||
bool is_pseudo_legal(const Move m) const;
|
bool is_pseudo_legal(const Move m) const;
|
||||||
bool is_capture(Move m) const;
|
bool is_capture(Move m) const;
|
||||||
bool is_capture_or_promotion(Move m) const;
|
bool is_capture_or_promotion(Move m) const;
|
||||||
bool is_passed_pawn_push(Move m) const;
|
bool is_passed_pawn_push(Move m) const;
|
||||||
|
Piece piece_moved(Move m) const;
|
||||||
// Piece captured with previous moves
|
|
||||||
PieceType captured_piece_type() const;
|
PieceType captured_piece_type() const;
|
||||||
|
|
||||||
// Information about pawns
|
// Piece specific
|
||||||
bool pawn_is_passed(Color c, Square s) const;
|
bool pawn_is_passed(Color c, Square s) const;
|
||||||
|
bool pawn_on_7th(Color c) const;
|
||||||
|
bool opposite_bishops() const;
|
||||||
|
bool bishop_pair(Color c) const;
|
||||||
|
|
||||||
// Doing and undoing moves
|
// Doing and undoing moves
|
||||||
void do_move(Move m, StateInfo& st);
|
void do_move(Move m, StateInfo& st);
|
||||||
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
|
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
|
||||||
void undo_move(Move m);
|
void undo_move(Move m);
|
||||||
template<bool Do> void do_null_move(StateInfo& st);
|
void do_null_move(StateInfo& st);
|
||||||
|
void undo_null_move();
|
||||||
|
|
||||||
// Static exchange evaluation
|
// Static exchange evaluation
|
||||||
int see(Move m) const;
|
int see(Move m, int asymmThreshold = 0) const;
|
||||||
int see_sign(Move m) const;
|
int see_sign(Move m) const;
|
||||||
|
|
||||||
// Accessing hash keys
|
// Accessing hash keys
|
||||||
@@ -178,46 +167,32 @@ public:
|
|||||||
Key pawn_key() const;
|
Key pawn_key() const;
|
||||||
Key material_key() const;
|
Key material_key() const;
|
||||||
|
|
||||||
// Incremental evaluation
|
// Incremental piece-square evaluation
|
||||||
Score value() const;
|
Score psq_score() const;
|
||||||
|
Score psq_delta(Piece p, Square from, Square to) const;
|
||||||
Value non_pawn_material(Color c) const;
|
Value non_pawn_material(Color c) const;
|
||||||
Score pst_delta(Piece piece, Square from, Square to) const;
|
|
||||||
|
|
||||||
// Game termination checks
|
|
||||||
bool is_mate() const;
|
|
||||||
template<bool SkipRepetition> bool is_draw() const;
|
|
||||||
|
|
||||||
// Plies from start position to the beginning of search
|
|
||||||
int startpos_ply_counter() const;
|
|
||||||
|
|
||||||
// Other properties of the position
|
// Other properties of the position
|
||||||
bool opposite_colored_bishops() const;
|
Color side_to_move() const;
|
||||||
bool has_pawn_on_7th(Color c) const;
|
int game_ply() const;
|
||||||
bool is_chess960() const;
|
bool is_chess960() const;
|
||||||
|
Thread* this_thread() const;
|
||||||
// Current thread ID searching on the position
|
|
||||||
int thread() const;
|
|
||||||
|
|
||||||
int64_t nodes_searched() const;
|
int64_t nodes_searched() const;
|
||||||
void set_nodes_searched(int64_t n);
|
void set_nodes_searched(int64_t n);
|
||||||
|
bool is_draw() const;
|
||||||
|
|
||||||
// Position consistency check, for debugging
|
// Position consistency check, for debugging
|
||||||
bool pos_is_ok(int* failedStep = NULL) const;
|
bool pos_is_ok(int* failedStep = NULL) const;
|
||||||
void flip_me();
|
void flip();
|
||||||
|
|
||||||
// Global initialization
|
|
||||||
static void init();
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// Initialization helpers (used while setting up a position)
|
||||||
// Initialization helper functions (used while setting up a position)
|
|
||||||
void clear();
|
void clear();
|
||||||
void put_piece(Piece p, Square s);
|
void put_piece(Piece p, Square s);
|
||||||
void set_castle_right(Square ksq, Square rsq);
|
void set_castle_right(Color c, Square rfrom);
|
||||||
bool move_is_legal(const Move m) const;
|
|
||||||
|
|
||||||
// Helper template functions
|
// Helper functions
|
||||||
template<bool Do> void do_castle_move(Move m);
|
void do_castle(Square kfrom, Square kto, Square rfrom, Square rto);
|
||||||
template<bool FindPinned> Bitboard hidden_checkers() const;
|
template<bool FindPinned> Bitboard hidden_checkers() const;
|
||||||
|
|
||||||
// Computing hash keys from scratch (for initialization and debugging)
|
// Computing hash keys from scratch (for initialization and debugging)
|
||||||
@@ -226,43 +201,28 @@ private:
|
|||||||
Key compute_material_key() const;
|
Key compute_material_key() const;
|
||||||
|
|
||||||
// Computing incremental evaluation scores and material counts
|
// Computing incremental evaluation scores and material counts
|
||||||
Score pst(Piece p, Square s) const;
|
Score compute_psq_score() const;
|
||||||
Score compute_value() const;
|
|
||||||
Value compute_non_pawn_material(Color c) const;
|
Value compute_non_pawn_material(Color c) const;
|
||||||
|
|
||||||
// Board
|
// Board and pieces
|
||||||
Piece board[64]; // [square]
|
Piece board[SQUARE_NB];
|
||||||
|
Bitboard byTypeBB[PIECE_TYPE_NB];
|
||||||
// Bitboards
|
Bitboard byColorBB[COLOR_NB];
|
||||||
Bitboard byTypeBB[8]; // [pieceType]
|
int pieceCount[COLOR_NB][PIECE_TYPE_NB];
|
||||||
Bitboard byColorBB[2]; // [color]
|
Square pieceList[COLOR_NB][PIECE_TYPE_NB][16];
|
||||||
Bitboard occupied;
|
int index[SQUARE_NB];
|
||||||
|
|
||||||
// Piece counts
|
|
||||||
int pieceCount[2][8]; // [color][pieceType]
|
|
||||||
|
|
||||||
// Piece lists
|
|
||||||
Square pieceList[2][8][16]; // [color][pieceType][index]
|
|
||||||
int index[64]; // [square]
|
|
||||||
|
|
||||||
// Other info
|
// Other info
|
||||||
int castleRightsMask[64]; // [square]
|
int castleRightsMask[SQUARE_NB];
|
||||||
Square castleRookSquare[16]; // [castleRight]
|
Square castleRookSquare[COLOR_NB][CASTLING_SIDE_NB];
|
||||||
|
Bitboard castlePath[COLOR_NB][CASTLING_SIDE_NB];
|
||||||
StateInfo startState;
|
StateInfo startState;
|
||||||
int64_t nodes;
|
int64_t nodes;
|
||||||
int startPosPly;
|
int gamePly;
|
||||||
Color sideToMove;
|
Color sideToMove;
|
||||||
int threadID;
|
Thread* thisThread;
|
||||||
StateInfo* st;
|
StateInfo* st;
|
||||||
int chess960;
|
int chess960;
|
||||||
|
|
||||||
// Static variables
|
|
||||||
static Score pieceSquareTable[16][64]; // [piece][square]
|
|
||||||
static Key zobrist[2][8][64]; // [color][pieceType][square]/[piece count]
|
|
||||||
static Key zobEp[64]; // [square]
|
|
||||||
static Key zobCastle[16]; // [castleRight]
|
|
||||||
static Key zobSideToMove;
|
|
||||||
static Key zobExclusion;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
inline int64_t Position::nodes_searched() const {
|
inline int64_t Position::nodes_searched() const {
|
||||||
@@ -277,7 +237,11 @@ inline Piece Position::piece_on(Square s) const {
|
|||||||
return board[s];
|
return board[s];
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::square_is_empty(Square s) const {
|
inline Piece Position::piece_moved(Move m) const {
|
||||||
|
return board[from_sq(m)];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::is_empty(Square s) const {
|
||||||
return board[s] == NO_PIECE;
|
return board[s] == NO_PIECE;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,32 +249,28 @@ inline Color Position::side_to_move() const {
|
|||||||
return sideToMove;
|
return sideToMove;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::occupied_squares() const {
|
inline Bitboard Position::pieces() const {
|
||||||
return occupied;
|
return byTypeBB[ALL_PIECES];
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard Position::empty_squares() const {
|
|
||||||
return ~occupied;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard Position::pieces(Color c) const {
|
|
||||||
return byColorBB[c];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::pieces(PieceType pt) const {
|
inline Bitboard Position::pieces(PieceType pt) const {
|
||||||
return byTypeBB[pt];
|
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 {
|
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
|
||||||
return byTypeBB[pt1] | byTypeBB[pt2];
|
return byTypeBB[pt1] | byTypeBB[pt2];
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2, Color c) const {
|
inline Bitboard Position::pieces(Color c) const {
|
||||||
return (byTypeBB[pt1] | byTypeBB[pt2]) & byColorBB[c];
|
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 {
|
inline int Position::piece_count(Color c, PieceType pt) const {
|
||||||
@@ -329,16 +289,28 @@ inline Square Position::king_square(Color c) const {
|
|||||||
return pieceList[c][KING][0];
|
return pieceList[c][KING][0];
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::can_castle(CastleRight f) const {
|
inline int Position::can_castle(CastleRight f) const {
|
||||||
return st->castleRights & f;
|
return st->castleRights & f;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::can_castle(Color c) const {
|
inline int Position::can_castle(Color c) const {
|
||||||
return st->castleRights & ((WHITE_OO | WHITE_OOO) << c);
|
return st->castleRights & ((WHITE_OO | WHITE_OOO) << (2 * c));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square Position::castle_rook_square(CastleRight f) const {
|
inline bool Position::castle_impeded(Color c, CastlingSide s) const {
|
||||||
return castleRookSquare[f];
|
return byTypeBB[ALL_PIECES] & castlePath[c][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Square Position::castle_rook_square(Color c, CastlingSide s) const {
|
||||||
|
return castleRookSquare[c][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
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<>
|
template<>
|
||||||
@@ -346,42 +318,18 @@ inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
|
|||||||
return StepAttacksBB[make_piece(c, PAWN)][s];
|
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];
|
|
||||||
}
|
|
||||||
|
|
||||||
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::attacks_from(Piece p, Square s) const {
|
inline Bitboard Position::attacks_from(Piece p, Square s) const {
|
||||||
return attacks_from(p, s, occupied_squares());
|
return attacks_from(p, s, byTypeBB[ALL_PIECES]);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::attackers_to(Square s) const {
|
inline Bitboard Position::attackers_to(Square s) const {
|
||||||
return attackers_to(s, occupied_squares());
|
return attackers_to(s, byTypeBB[ALL_PIECES]);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::checkers() const {
|
inline Bitboard Position::checkers() const {
|
||||||
return st->checkersBB;
|
return st->checkersBB;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::in_check() const {
|
|
||||||
return st->checkersBB != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Bitboard Position::discovered_check_candidates() const {
|
inline Bitboard Position::discovered_check_candidates() const {
|
||||||
return hidden_checkers<false>();
|
return hidden_checkers<false>();
|
||||||
}
|
}
|
||||||
@@ -391,7 +339,7 @@ inline Bitboard Position::pinned_pieces() const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::pawn_is_passed(Color c, Square s) const {
|
inline bool Position::pawn_is_passed(Color c, Square s) const {
|
||||||
return !(pieces(PAWN, flip(c)) & passed_pawn_mask(c, s));
|
return !(pieces(~c, PAWN) & passed_pawn_mask(c, s));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Key Position::key() const {
|
inline Key Position::key() const {
|
||||||
@@ -399,7 +347,7 @@ inline Key Position::key() const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inline Key Position::exclusion_key() const {
|
inline Key Position::exclusion_key() const {
|
||||||
return st->key ^ zobExclusion;
|
return st->key ^ Zobrist::exclusion;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Key Position::pawn_key() const {
|
inline Key Position::pawn_key() const {
|
||||||
@@ -410,16 +358,12 @@ inline Key Position::material_key() const {
|
|||||||
return st->materialKey;
|
return st->materialKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Score Position::pst(Piece p, Square s) const {
|
inline Score Position::psq_delta(Piece p, Square from, Square to) const {
|
||||||
return pieceSquareTable[p][s];
|
return pieceSquareTable[p][to] - pieceSquareTable[p][from];
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Score Position::pst_delta(Piece piece, Square from, Square to) const {
|
inline Score Position::psq_score() const {
|
||||||
return pieceSquareTable[piece][to] - pieceSquareTable[piece][from];
|
return st->psqScore;
|
||||||
}
|
|
||||||
|
|
||||||
inline Score Position::value() const {
|
|
||||||
return st->value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Value Position::non_pawn_material(Color c) const {
|
inline Value Position::non_pawn_material(Color c) const {
|
||||||
@@ -428,23 +372,29 @@ inline Value Position::non_pawn_material(Color c) const {
|
|||||||
|
|
||||||
inline bool Position::is_passed_pawn_push(Move m) const {
|
inline bool Position::is_passed_pawn_push(Move m) const {
|
||||||
|
|
||||||
return board[move_from(m)] == make_piece(sideToMove, PAWN)
|
return type_of(piece_moved(m)) == PAWN
|
||||||
&& pawn_is_passed(sideToMove, move_to(m));
|
&& pawn_is_passed(sideToMove, to_sq(m));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline int Position::startpos_ply_counter() const {
|
inline int Position::game_ply() const {
|
||||||
return startPosPly + st->pliesFromNull; // HACK
|
return gamePly;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::opposite_colored_bishops() const {
|
inline bool Position::opposite_bishops() const {
|
||||||
|
|
||||||
return pieceCount[WHITE][BISHOP] == 1
|
return pieceCount[WHITE][BISHOP] == 1
|
||||||
&& pieceCount[BLACK][BISHOP] == 1
|
&& pieceCount[BLACK][BISHOP] == 1
|
||||||
&& opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
|
&& opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::has_pawn_on_7th(Color c) const {
|
inline bool Position::bishop_pair(Color c) const {
|
||||||
return pieces(PAWN, c) & rank_bb(relative_rank(c, RANK_7));
|
|
||||||
|
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 {
|
inline bool Position::is_chess960() const {
|
||||||
@@ -454,22 +404,22 @@ inline bool Position::is_chess960() const {
|
|||||||
inline bool Position::is_capture_or_promotion(Move m) const {
|
inline bool Position::is_capture_or_promotion(Move m) const {
|
||||||
|
|
||||||
assert(is_ok(m));
|
assert(is_ok(m));
|
||||||
return is_special(m) ? !is_castle(m) : !square_is_empty(move_to(m));
|
return type_of(m) ? type_of(m) != CASTLE : !is_empty(to_sq(m));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::is_capture(Move m) const {
|
inline bool Position::is_capture(Move m) const {
|
||||||
|
|
||||||
// Note that castle is coded as "king captures the rook"
|
// Note that castle is coded as "king captures the rook"
|
||||||
assert(is_ok(m));
|
assert(is_ok(m));
|
||||||
return (!square_is_empty(move_to(m)) && !is_castle(m)) || is_enpassant(m);
|
return (!is_empty(to_sq(m)) && type_of(m) != CASTLE) || type_of(m) == ENPASSANT;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline PieceType Position::captured_piece_type() const {
|
inline PieceType Position::captured_piece_type() const {
|
||||||
return st->capturedType;
|
return st->capturedType;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline int Position::thread() const {
|
inline Thread* Position::this_thread() const {
|
||||||
return threadID;
|
return thisThread;
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif // !defined(POSITION_H_INCLUDED)
|
#endif // !defined(POSITION_H_INCLUDED)
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -29,7 +29,7 @@
|
|||||||
/// a given square a (midgame, endgame) score pair is assigned. PSQT is defined
|
/// a given square a (midgame, endgame) score pair is assigned. PSQT is defined
|
||||||
/// for white side, for black side the tables are symmetric.
|
/// for white side, for black side the tables are symmetric.
|
||||||
|
|
||||||
static const Score PSQT[][64] = {
|
static const Score PSQT[][SQUARE_NB] = {
|
||||||
{ },
|
{ },
|
||||||
{ // Pawn
|
{ // 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( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0),
|
||||||
|
|||||||
+4
-6
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -61,17 +61,15 @@ class RKISS {
|
|||||||
return s.d = e + s.a;
|
return s.d = e + s.a;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Init seed and scramble a few rounds
|
public:
|
||||||
void raninit() {
|
RKISS(int seed = 73) {
|
||||||
|
|
||||||
s.a = 0xf1ea5eed;
|
s.a = 0xf1ea5eed;
|
||||||
s.b = s.c = s.d = 0xd4e12c77;
|
s.b = s.c = s.d = 0xd4e12c77;
|
||||||
for (int i = 0; i < 73; i++)
|
for (int i = 0; i < seed; i++) // Scramble a few rounds
|
||||||
rand64();
|
rand64();
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
|
||||||
RKISS() { raninit(); }
|
|
||||||
template<typename T> T rand() { return T(rand64()); }
|
template<typename T> T rand() { return T(rand64()); }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+834
-1026
File diff suppressed because it is too large
Load Diff
+41
-11
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -21,11 +21,14 @@
|
|||||||
#define SEARCH_H_INCLUDED
|
#define SEARCH_H_INCLUDED
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
#include <memory>
|
||||||
|
#include <stack>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "misc.h"
|
||||||
|
#include "position.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
class Position;
|
|
||||||
struct SplitPoint;
|
struct SplitPoint;
|
||||||
|
|
||||||
namespace Search {
|
namespace Search {
|
||||||
@@ -35,16 +38,38 @@ namespace Search {
|
|||||||
/// has its own array of Stack objects, indexed by the current ply.
|
/// has its own array of Stack objects, indexed by the current ply.
|
||||||
|
|
||||||
struct Stack {
|
struct Stack {
|
||||||
SplitPoint* sp;
|
SplitPoint* splitPoint;
|
||||||
int ply;
|
int ply;
|
||||||
Move currentMove;
|
Move currentMove;
|
||||||
Move excludedMove;
|
Move excludedMove;
|
||||||
Move bestMove;
|
|
||||||
Move killers[2];
|
Move killers[2];
|
||||||
Depth reduction;
|
Depth reduction;
|
||||||
Value eval;
|
Value staticEval;
|
||||||
Value evalMargin;
|
Value evalMargin;
|
||||||
int skipNullMove;
|
int skipNullMove;
|
||||||
|
int futilityMoveCount;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// 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(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; } // Ascending sort
|
||||||
|
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;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -55,9 +80,9 @@ struct Stack {
|
|||||||
struct LimitsType {
|
struct LimitsType {
|
||||||
|
|
||||||
LimitsType() { memset(this, 0, sizeof(LimitsType)); }
|
LimitsType() { memset(this, 0, sizeof(LimitsType)); }
|
||||||
bool useTimeManagement() const { return !(maxTime | maxDepth | maxNodes | infinite); }
|
bool use_time_management() const { return !(mate | movetime | depth | nodes | infinite); }
|
||||||
|
|
||||||
int time, increment, movesToGo, maxTime, maxDepth, maxNodes, infinite, ponder;
|
int time[COLOR_NB], inc[COLOR_NB], movestogo, depth, nodes, movetime, mate, infinite, ponder;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -68,15 +93,20 @@ struct SignalsType {
|
|||||||
bool stopOnPonderhit, firstRootMove, stop, failedLowAtRoot;
|
bool stopOnPonderhit, firstRootMove, stop, failedLowAtRoot;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
typedef std::auto_ptr<std::stack<StateInfo> > StateStackPtr;
|
||||||
|
|
||||||
extern volatile SignalsType Signals;
|
extern volatile SignalsType Signals;
|
||||||
extern LimitsType Limits;
|
extern LimitsType Limits;
|
||||||
extern std::vector<Move> SearchMoves;
|
extern std::vector<RootMove> RootMoves;
|
||||||
extern Position RootPosition;
|
extern Position RootPos;
|
||||||
|
extern Color RootColor;
|
||||||
|
extern Time::point SearchTime;
|
||||||
|
extern StateStackPtr SetupStates;
|
||||||
|
|
||||||
extern void init();
|
extern void init();
|
||||||
extern int64_t perft(Position& pos, Depth depth);
|
extern size_t perft(Position& pos, Depth depth);
|
||||||
extern void think();
|
extern void think();
|
||||||
|
|
||||||
} // namespace
|
} // namespace Search
|
||||||
|
|
||||||
#endif // !defined(SEARCH_H_INCLUDED)
|
#endif // !defined(SEARCH_H_INCLUDED)
|
||||||
|
|||||||
+261
-381
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -17,485 +17,365 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <algorithm> // For std::count
|
||||||
|
#include <cassert>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "movegen.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
#include "ucioption.h"
|
#include "ucioption.h"
|
||||||
|
|
||||||
using namespace Search;
|
using namespace Search;
|
||||||
|
|
||||||
ThreadsManager Threads; // Global object
|
ThreadPool Threads; // Global object
|
||||||
|
|
||||||
namespace { extern "C" {
|
namespace { extern "C" {
|
||||||
|
|
||||||
// start_routine() is the C function which is called when a new thread
|
// start_routine() is the C function which is called when a new thread
|
||||||
// is launched. It simply calls idle_loop() of the supplied thread. The first
|
// is launched. It is a wrapper to the virtual function idle_loop().
|
||||||
// and last thread are special. First one is the main search thread while the
|
|
||||||
// last one mimics a timer, they run in main_loop() and timer_loop().
|
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
long start_routine(Thread* th) { th->idle_loop(); return 0; }
|
||||||
DWORD WINAPI start_routine(LPVOID thread) {
|
|
||||||
#else
|
|
||||||
void* start_routine(void* thread) {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Thread* th = (Thread*)thread;
|
|
||||||
|
|
||||||
if (th->threadID == 0)
|
|
||||||
th->main_loop();
|
|
||||||
|
|
||||||
else if (th->threadID == MAX_THREADS)
|
|
||||||
th->timer_loop();
|
|
||||||
|
|
||||||
else
|
|
||||||
th->idle_loop(NULL);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
} }
|
} }
|
||||||
|
|
||||||
|
|
||||||
// wake_up() wakes up the thread, normally at the beginning of the search or,
|
// Thread c'tor starts a newly-created thread of execution that will call
|
||||||
// if "sleeping threads" is used, when there is some work to do.
|
// the the virtual function idle_loop(), going immediately to sleep.
|
||||||
|
|
||||||
void Thread::wake_up() {
|
Thread::Thread() /* : splitPoints() */ { // Value-initialization bug in MSVC
|
||||||
|
|
||||||
lock_grab(&sleepLock);
|
searching = exit = false;
|
||||||
cond_signal(&sleepCond);
|
maxPly = splitPointsSize = 0;
|
||||||
lock_release(&sleepLock);
|
activeSplitPoint = NULL;
|
||||||
|
activePosition = NULL;
|
||||||
|
idx = Threads.size();
|
||||||
|
|
||||||
|
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 current
|
// Thread d'tor waits for thread termination before to return
|
||||||
// active split point, or in some ancestor of the split point.
|
|
||||||
|
Thread::~Thread() {
|
||||||
|
|
||||||
|
exit = true; // Search must be already finished
|
||||||
|
notify_one();
|
||||||
|
thread_join(handle); // Wait for thread termination
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// TimerThread::idle_loop() is where the timer thread waits msec milliseconds
|
||||||
|
// and then calls check_time(). If msec is 0 thread sleeps until is woken up.
|
||||||
|
extern void check_time();
|
||||||
|
|
||||||
|
void TimerThread::idle_loop() {
|
||||||
|
|
||||||
|
while (!exit)
|
||||||
|
{
|
||||||
|
mutex.lock();
|
||||||
|
|
||||||
|
if (!exit)
|
||||||
|
sleepCondition.wait_for(mutex, msec ? msec : INT_MAX);
|
||||||
|
|
||||||
|
mutex.unlock();
|
||||||
|
|
||||||
|
if (msec)
|
||||||
|
check_time();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// MainThread::idle_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 MainThread::idle_loop() {
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
mutex.lock();
|
||||||
|
|
||||||
|
thinking = false;
|
||||||
|
|
||||||
|
while (!thinking && !exit)
|
||||||
|
{
|
||||||
|
Threads.sleepCondition.notify_one(); // Wake up UI thread if needed
|
||||||
|
sleepCondition.wait(mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
mutex.unlock();
|
||||||
|
|
||||||
|
if (exit)
|
||||||
|
return;
|
||||||
|
|
||||||
|
searching = true;
|
||||||
|
|
||||||
|
Search::think();
|
||||||
|
|
||||||
|
assert(searching);
|
||||||
|
|
||||||
|
searching = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Thread::notify_one() wakes up the thread when there is some search to do
|
||||||
|
|
||||||
|
void Thread::notify_one() {
|
||||||
|
|
||||||
|
mutex.lock();
|
||||||
|
sleepCondition.notify_one();
|
||||||
|
mutex.unlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Thread::wait_for() set the thread to sleep until condition 'b' turns true
|
||||||
|
|
||||||
|
void Thread::wait_for(volatile const bool& b) {
|
||||||
|
|
||||||
|
mutex.lock();
|
||||||
|
while (!b) 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 {
|
bool Thread::cutoff_occurred() const {
|
||||||
|
|
||||||
for (SplitPoint* sp = splitPoint; sp; sp = sp->parent)
|
for (SplitPoint* sp = activeSplitPoint; sp; sp = sp->parentSplitPoint)
|
||||||
if (sp->is_betaCutoff)
|
if (sp->cutoff)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// is_available_to() checks whether the thread is available to help the thread with
|
// Thread::is_available_to() checks whether the thread is available to help the
|
||||||
// threadID "master" at a split point. An obvious requirement is that thread must be
|
// thread 'master' at a split point. An obvious requirement is that thread must
|
||||||
// idle. With more than two threads, this is not by itself sufficient: If the thread
|
// be idle. With more than two threads, this is not sufficient: If the thread is
|
||||||
// is the master of some active split point, it is only available as a slave to the
|
// the master of some split point, it is only available as a slave to the slaves
|
||||||
// threads which are busy searching the split point at the top of "slave"'s split
|
// which are busy searching the split point at the top of slaves split point
|
||||||
// point stack (the "helpful master concept" in YBWC terminology).
|
// 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 (is_searching)
|
if (searching)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Make a local copy to be sure doesn't become zero under our feet while
|
// 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.
|
// testing next condition and so leading to an out of bound access.
|
||||||
int localActiveSplitPoints = activeSplitPoints;
|
int size = splitPointsSize;
|
||||||
|
|
||||||
// No active split points means that the thread is available as a slave for any
|
// No split points means that the thread is available as a slave for any
|
||||||
// other thread otherwise apply the "helpful master" concept if possible.
|
// other thread otherwise apply the "helpful master" concept if possible.
|
||||||
if ( !localActiveSplitPoints
|
return !size || (splitPoints[size - 1].slavesMask & (1ULL << master->idx));
|
||||||
|| splitPoints[localActiveSplitPoints - 1].is_slave[master])
|
|
||||||
return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// read_uci_options() updates number of active threads and other parameters
|
// init() is called at startup to create and launch requested threads, that will
|
||||||
// according to the UCI options values. It is called before to start a new search.
|
// go immediately to sleep due to 'sleepWhileIdle' set to true. 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() {
|
||||||
|
|
||||||
|
sleepWhileIdle = true;
|
||||||
|
timer = new TimerThread();
|
||||||
|
push_back(new MainThread());
|
||||||
|
read_uci_options();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// exit() cleanly terminates the threads before the program exits
|
||||||
|
|
||||||
|
void ThreadPool::exit() {
|
||||||
|
|
||||||
|
delete timer; // As first because check_time() accesses threads data
|
||||||
|
|
||||||
|
for (iterator it = begin(); it != end(); ++it)
|
||||||
|
delete *it;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
|
||||||
|
void ThreadPool::read_uci_options() {
|
||||||
|
|
||||||
maxThreadsPerSplitPoint = Options["Max Threads per Split Point"];
|
maxThreadsPerSplitPoint = Options["Max Threads per Split Point"];
|
||||||
minimumSplitDepth = Options["Min Split Depth"] * ONE_PLY;
|
minimumSplitDepth = Options["Min Split Depth"] * ONE_PLY;
|
||||||
useSleepingThreads = Options["Use Sleeping Threads"];
|
size_t requested = Options["Threads"];
|
||||||
|
|
||||||
set_size(Options["Threads"]);
|
assert(requested > 0);
|
||||||
}
|
|
||||||
|
|
||||||
|
while (size() < requested)
|
||||||
|
push_back(new Thread());
|
||||||
|
|
||||||
// set_size() changes the number of active threads and raises do_sleep flag for
|
while (size() > requested)
|
||||||
// all the unused threads that will go immediately to sleep.
|
|
||||||
|
|
||||||
void ThreadsManager::set_size(int cnt) {
|
|
||||||
|
|
||||||
assert(cnt > 0 && cnt <= MAX_THREADS);
|
|
||||||
|
|
||||||
activeThreads = cnt;
|
|
||||||
|
|
||||||
for (int i = 1; i < MAX_THREADS; i++) // Ignore main thread
|
|
||||||
if (i < activeThreads)
|
|
||||||
{
|
{
|
||||||
// Dynamically allocate pawn and material hash tables according to the
|
delete back();
|
||||||
// number of active threads. This avoids preallocating memory for all
|
pop_back();
|
||||||
// possible threads if only few are used.
|
|
||||||
threads[i].pawnTable.init();
|
|
||||||
threads[i].materialTable.init();
|
|
||||||
|
|
||||||
threads[i].do_sleep = false;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
threads[i].do_sleep = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// init() is called during startup. Initializes locks and condition variables
|
|
||||||
// and launches all threads sending them immediately to sleep.
|
|
||||||
|
|
||||||
void ThreadsManager::init() {
|
|
||||||
|
|
||||||
// Initialize sleep condition and lock used by thread manager
|
|
||||||
cond_init(&sleepCond);
|
|
||||||
lock_init(&threadsLock);
|
|
||||||
|
|
||||||
// Initialize thread's sleep conditions and split point locks
|
|
||||||
for (int i = 0; i <= MAX_THREADS; i++)
|
|
||||||
{
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allocate main thread tables to call evaluate() also when not searching
|
|
||||||
threads[0].pawnTable.init();
|
|
||||||
threads[0].materialTable.init();
|
|
||||||
|
|
||||||
// Create and launch all the threads, threads will go immediately to sleep
|
|
||||||
for (int i = 0; i <= MAX_THREADS; i++)
|
|
||||||
{
|
|
||||||
threads[i].is_searching = false;
|
|
||||||
threads[i].do_sleep = true;
|
|
||||||
threads[i].threadID = i;
|
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
|
||||||
threads[i].handle = CreateThread(NULL, 0, start_routine, &threads[i], 0, NULL);
|
|
||||||
bool ok = (threads[i].handle != NULL);
|
|
||||||
#else
|
|
||||||
bool ok = !pthread_create(&threads[i].handle, NULL, start_routine, &threads[i]);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!ok)
|
|
||||||
{
|
|
||||||
std::cerr << "Failed to create thread number " << i << std::endl;
|
|
||||||
::exit(EXIT_FAILURE);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// exit() is called to cleanly terminate the threads when the program finishes
|
// slave_available() tries to find an idle thread which is available as a slave
|
||||||
|
// for the thread 'master'.
|
||||||
|
|
||||||
void ThreadsManager::exit() {
|
Thread* ThreadPool::available_slave(Thread* master) const {
|
||||||
|
|
||||||
for (int i = 0; i <= MAX_THREADS; i++)
|
for (const_iterator it = begin(); it != end(); ++it)
|
||||||
{
|
if ((*it)->is_available_to(master))
|
||||||
threads[i].do_terminate = true; // Search must be already finished
|
return *it;
|
||||||
threads[i].wake_up();
|
|
||||||
|
|
||||||
// Wait for thread termination
|
return NULL;
|
||||||
#if defined(_MSC_VER)
|
|
||||||
WaitForSingleObject(threads[i].handle, 0);
|
|
||||||
CloseHandle(threads[i].handle);
|
|
||||||
#else
|
|
||||||
pthread_join(threads[i].handle, NULL);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Now we can safely destroy associated 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));
|
|
||||||
}
|
|
||||||
|
|
||||||
lock_destroy(&threadsLock);
|
|
||||||
cond_destroy(&sleepCond);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// available_slave_exists() tries to find an idle thread which is available as
|
|
||||||
// a slave for the thread with threadID 'master'.
|
|
||||||
|
|
||||||
bool ThreadsManager::available_slave_exists(int master) const {
|
|
||||||
|
|
||||||
assert(master >= 0 && master < activeThreads);
|
|
||||||
|
|
||||||
for (int i = 0; i < activeThreads; i++)
|
|
||||||
if (threads[i].is_available_to(master))
|
|
||||||
return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// split_point_finished() checks if all the slave threads of a given split
|
|
||||||
// point have finished searching.
|
|
||||||
|
|
||||||
bool ThreadsManager::split_point_finished(SplitPoint* sp) const {
|
|
||||||
|
|
||||||
for (int i = 0; i < activeThreads; i++)
|
|
||||||
if (sp->is_slave[i])
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// split() does the actual work of distributing the work at a node between
|
// 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
|
// 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
|
// (because no idle threads are available), the function immediately returns.
|
||||||
// point objects), the function immediately returns. If splitting is possible, a
|
// If splitting is possible, a SplitPoint object is initialized with all the
|
||||||
// SplitPoint object is initialized with all the data that must be copied to the
|
// data that must be copied to the helper threads and then helper threads are
|
||||||
// helper threads and then helper threads are told that they have been assigned
|
// told that they have been assigned work. This will cause them to instantly
|
||||||
// work. This will cause them to instantly leave their idle loops and call
|
// leave their idle loops and call search(). When all threads have returned from
|
||||||
// search(). When all threads have returned from search() then split() returns.
|
// search() then split() returns.
|
||||||
|
|
||||||
template <bool Fake>
|
template <bool Fake>
|
||||||
Value ThreadsManager::split(Position& pos, Stack* ss, Value alpha, Value beta,
|
void Thread::split(Position& pos, Stack* ss, Value alpha, Value beta, Value* bestValue,
|
||||||
Value bestValue, Depth depth, Move threatMove,
|
Move* bestMove, Depth depth, Move threatMove, int moveCount,
|
||||||
int moveCount, MovePicker* mp, int nodeType) {
|
MovePicker* movePicker, int nodeType) {
|
||||||
|
|
||||||
assert(pos.pos_is_ok());
|
assert(pos.pos_is_ok());
|
||||||
assert(bestValue > -VALUE_INFINITE);
|
assert(*bestValue <= alpha && alpha < beta && beta <= VALUE_INFINITE);
|
||||||
assert(bestValue <= alpha);
|
assert(*bestValue > -VALUE_INFINITE);
|
||||||
assert(alpha < beta);
|
assert(depth >= Threads.minimumSplitDepth);
|
||||||
assert(beta <= VALUE_INFINITE);
|
assert(searching);
|
||||||
assert(depth > DEPTH_ZERO);
|
assert(splitPointsSize < MAX_SPLITPOINTS_PER_THREAD);
|
||||||
assert(pos.thread() >= 0 && pos.thread() < activeThreads);
|
|
||||||
assert(activeThreads > 1);
|
|
||||||
|
|
||||||
int i, master = pos.thread();
|
|
||||||
Thread& masterThread = threads[master];
|
|
||||||
|
|
||||||
// If we already have too many active split points, don't split
|
|
||||||
if (masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
|
|
||||||
return bestValue;
|
|
||||||
|
|
||||||
// Pick the next available split point from the split point stack
|
// Pick the next available split point from the split point stack
|
||||||
SplitPoint* sp = &masterThread.splitPoints[masterThread.activeSplitPoints];
|
SplitPoint& sp = splitPoints[splitPointsSize];
|
||||||
|
|
||||||
// Initialize the split point
|
sp.masterThread = this;
|
||||||
sp->parent = masterThread.splitPoint;
|
sp.parentSplitPoint = activeSplitPoint;
|
||||||
sp->master = master;
|
sp.slavesMask = 1ULL << idx;
|
||||||
sp->is_betaCutoff = false;
|
sp.depth = depth;
|
||||||
sp->depth = depth;
|
sp.bestValue = *bestValue;
|
||||||
sp->threatMove = threatMove;
|
sp.bestMove = *bestMove;
|
||||||
sp->alpha = alpha;
|
sp.threatMove = threatMove;
|
||||||
sp->beta = beta;
|
sp.alpha = alpha;
|
||||||
sp->nodeType = nodeType;
|
sp.beta = beta;
|
||||||
sp->bestValue = bestValue;
|
sp.nodeType = nodeType;
|
||||||
sp->mp = mp;
|
sp.movePicker = movePicker;
|
||||||
sp->moveCount = moveCount;
|
sp.moveCount = moveCount;
|
||||||
sp->pos = &pos;
|
sp.pos = &pos;
|
||||||
sp->nodes = 0;
|
sp.nodes = 0;
|
||||||
sp->ss = ss;
|
sp.cutoff = false;
|
||||||
|
sp.ss = ss;
|
||||||
for (i = 0; i < activeThreads; i++)
|
|
||||||
sp->is_slave[i] = false;
|
|
||||||
|
|
||||||
// If we are here it means we are not available
|
|
||||||
assert(masterThread.is_searching);
|
|
||||||
|
|
||||||
int workersCnt = 1; // At least the master is included
|
|
||||||
|
|
||||||
// Try to allocate available threads and ask them to start searching setting
|
// 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
|
// 'searching' flag. This must be done under lock protection to avoid concurrent
|
||||||
// allocation of the same slave by another master.
|
// allocation of the same slave by another master.
|
||||||
lock_grab(&threadsLock);
|
Threads.mutex.lock();
|
||||||
|
sp.mutex.lock();
|
||||||
|
|
||||||
for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
|
splitPointsSize++;
|
||||||
if (threads[i].is_available_to(master))
|
activeSplitPoint = &sp;
|
||||||
|
activePosition = NULL;
|
||||||
|
|
||||||
|
size_t slavesCnt = 1; // This thread is always included
|
||||||
|
Thread* slave;
|
||||||
|
|
||||||
|
while ( (slave = Threads.available_slave(this)) != NULL
|
||||||
|
&& ++slavesCnt <= Threads.maxThreadsPerSplitPoint && !Fake)
|
||||||
{
|
{
|
||||||
workersCnt++;
|
sp.slavesMask |= 1ULL << slave->idx;
|
||||||
sp->is_slave[i] = true;
|
slave->activeSplitPoint = &sp;
|
||||||
threads[i].splitPoint = sp;
|
slave->searching = true; // Slave leaves idle_loop()
|
||||||
|
slave->notify_one(); // Could be sleeping
|
||||||
// This makes the slave to exit from idle_loop()
|
|
||||||
threads[i].is_searching = true;
|
|
||||||
|
|
||||||
if (useSleepingThreads)
|
|
||||||
threads[i].wake_up();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lock_release(&threadsLock);
|
|
||||||
|
|
||||||
// We failed to allocate even one slave, return
|
|
||||||
if (!Fake && workersCnt == 1)
|
|
||||||
return bestValue;
|
|
||||||
|
|
||||||
masterThread.splitPoint = sp;
|
|
||||||
masterThread.activeSplitPoints++;
|
|
||||||
|
|
||||||
// Everything is set up. The master thread enters the idle loop, from which
|
// 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.
|
// it will instantly launch a search, because its 'searching' flag is set.
|
||||||
// We pass the split point as a parameter to the idle loop, which means that
|
// The thread will return from the idle loop when all slaves have finished
|
||||||
// the thread will return from the idle loop when all slaves have finished
|
|
||||||
// their work at this split point.
|
// their work at this split point.
|
||||||
masterThread.idle_loop(sp);
|
if (slavesCnt > 1 || Fake)
|
||||||
|
{
|
||||||
|
sp.mutex.unlock();
|
||||||
|
Threads.mutex.unlock();
|
||||||
|
|
||||||
|
Thread::idle_loop(); // Force a call to base class idle_loop()
|
||||||
|
|
||||||
// In helpful master concept a master can help only a sub-tree of its split
|
// 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.
|
// point, and because here is all finished is not possible master is booked.
|
||||||
assert(!masterThread.is_searching);
|
assert(!searching);
|
||||||
|
assert(!activePosition);
|
||||||
|
|
||||||
// We have returned from the idle loop, which means that all threads are
|
// We have returned from the idle loop, which means that all threads are
|
||||||
// finished. Note that changing state and decreasing activeSplitPoints is done
|
// finished. Note that setting 'searching' and decreasing splitPointsSize is
|
||||||
// under lock protection to avoid a race with Thread::is_available_to().
|
// done under lock protection to avoid a race with Thread::is_available_to().
|
||||||
lock_grab(&threadsLock);
|
Threads.mutex.lock();
|
||||||
|
sp.mutex.lock();
|
||||||
|
}
|
||||||
|
|
||||||
masterThread.is_searching = true;
|
searching = true;
|
||||||
masterThread.activeSplitPoints--;
|
splitPointsSize--;
|
||||||
|
activeSplitPoint = sp.parentSplitPoint;
|
||||||
|
activePosition = &pos;
|
||||||
|
pos.set_nodes_searched(pos.nodes_searched() + sp.nodes);
|
||||||
|
*bestMove = sp.bestMove;
|
||||||
|
*bestValue = sp.bestValue;
|
||||||
|
|
||||||
lock_release(&threadsLock);
|
sp.mutex.unlock();
|
||||||
|
Threads.mutex.unlock();
|
||||||
masterThread.splitPoint = sp->parent;
|
|
||||||
pos.set_nodes_searched(pos.nodes_searched() + sp->nodes);
|
|
||||||
|
|
||||||
return sp->bestValue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explicit template instantiations
|
// Explicit template instantiations
|
||||||
template Value ThreadsManager::split<false>(Position&, Stack*, Value, Value, Value, Depth, Move, int, MovePicker*, int);
|
template void Thread::split<false>(Position&, Stack*, Value, Value, Value*, Move*, Depth, Move, int, MovePicker*, int);
|
||||||
template Value ThreadsManager::split<true>(Position&, Stack*, Value, Value, Value, Depth, Move, int, MovePicker*, int);
|
template void Thread::split< true>(Position&, Stack*, Value, Value, Value*, Move*, Depth, Move, int, MovePicker*, int);
|
||||||
|
|
||||||
|
|
||||||
// Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
|
// wait_for_think_finished() waits for main thread to go to sleep then returns
|
||||||
// then calls do_timer_event(). If maxPly is 0 thread sleeps until is woken up.
|
|
||||||
extern void do_timer_event();
|
|
||||||
|
|
||||||
void Thread::timer_loop() {
|
void ThreadPool::wait_for_think_finished() {
|
||||||
|
|
||||||
while (!do_terminate)
|
MainThread* t = main_thread();
|
||||||
{
|
t->mutex.lock();
|
||||||
lock_grab(&sleepLock);
|
while (t->thinking) sleepCondition.wait(t->mutex);
|
||||||
timed_wait(&sleepCond, &sleepLock, maxPly ? maxPly : INT_MAX);
|
t->mutex.unlock();
|
||||||
lock_release(&sleepLock);
|
|
||||||
do_timer_event();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ThreadsManager::set_timer() is used to set the timer to trigger after msec
|
// start_thinking() wakes up the main thread sleeping in MainThread::idle_loop()
|
||||||
// milliseconds. If msec is 0 then timer is stopped.
|
// so to start a new search, then returns immediately.
|
||||||
|
|
||||||
void ThreadsManager::set_timer(int msec) {
|
void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
|
||||||
|
const std::vector<Move>& searchMoves, StateStackPtr& states) {
|
||||||
|
wait_for_think_finished();
|
||||||
|
|
||||||
Thread& timer = threads[MAX_THREADS];
|
SearchTime = Time::now(); // As early as possible
|
||||||
|
|
||||||
lock_grab(&timer.sleepLock);
|
Signals.stopOnPonderhit = Signals.firstRootMove = false;
|
||||||
timer.maxPly = msec;
|
Signals.stop = Signals.failedLowAtRoot = false;
|
||||||
cond_signal(&timer.sleepCond); // Wake up and restart the timer
|
|
||||||
lock_release(&timer.sleepLock);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
RootPos = pos;
|
||||||
// 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)
|
|
||||||
{
|
|
||||||
lock_grab(&sleepLock);
|
|
||||||
|
|
||||||
do_sleep = true; // Always return to sleep after a search
|
|
||||||
is_searching = false;
|
|
||||||
|
|
||||||
while (do_sleep && !do_terminate)
|
|
||||||
{
|
|
||||||
cond_signal(&Threads.sleepCond); // Wake up UI thread if needed
|
|
||||||
cond_wait(&sleepCond, &sleepLock);
|
|
||||||
}
|
|
||||||
|
|
||||||
is_searching = true;
|
|
||||||
|
|
||||||
lock_release(&sleepLock);
|
|
||||||
|
|
||||||
if (do_terminate)
|
|
||||||
return;
|
|
||||||
|
|
||||||
think(); // This is the search entry point
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ThreadsManager::start_thinking() is used by UI thread to wake up the main
|
|
||||||
// thread parked in main_loop() and starting a new search. If asyncMode is true
|
|
||||||
// then function returns immediately, otherwise caller is blocked waiting for
|
|
||||||
// the search to finish.
|
|
||||||
|
|
||||||
void ThreadsManager::start_thinking(const Position& pos, const LimitsType& limits,
|
|
||||||
const std::vector<Move>& searchMoves, bool asyncMode) {
|
|
||||||
Thread& main = threads[0];
|
|
||||||
|
|
||||||
lock_grab(&main.sleepLock);
|
|
||||||
|
|
||||||
// Wait main thread has finished before to launch a new search
|
|
||||||
while (!main.do_sleep)
|
|
||||||
cond_wait(&sleepCond, &main.sleepLock);
|
|
||||||
|
|
||||||
// Copy input arguments to initialize the search
|
|
||||||
RootPosition.copy(pos, 0);
|
|
||||||
Limits = limits;
|
Limits = limits;
|
||||||
SearchMoves = searchMoves;
|
SetupStates = states; // Ownership transfer here
|
||||||
|
RootMoves.clear();
|
||||||
|
|
||||||
// Reset signals before to start the new search
|
for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
|
||||||
memset((void*)&Signals, 0, sizeof(Signals));
|
if ( searchMoves.empty()
|
||||||
|
|| std::count(searchMoves.begin(), searchMoves.end(), ml.move()))
|
||||||
|
RootMoves.push_back(RootMove(ml.move()));
|
||||||
|
|
||||||
main.do_sleep = false;
|
main_thread()->thinking = true;
|
||||||
cond_signal(&main.sleepCond); // Wake up main thread and start searching
|
main_thread()->notify_one(); // Starts main thread
|
||||||
|
|
||||||
if (!asyncMode)
|
|
||||||
cond_wait(&sleepCond, &main.sleepLock);
|
|
||||||
|
|
||||||
lock_release(&main.sleepLock);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ThreadsManager::stop_thinking() is used by UI thread to raise a stop request
|
|
||||||
// and to wait for the main thread finishing the search. Needed to wait exiting
|
|
||||||
// and terminate the threads after a 'quit' command.
|
|
||||||
|
|
||||||
void ThreadsManager::stop_thinking() {
|
|
||||||
|
|
||||||
Thread& main = threads[0];
|
|
||||||
|
|
||||||
Search::Signals.stop = true;
|
|
||||||
|
|
||||||
lock_grab(&main.sleepLock);
|
|
||||||
|
|
||||||
cond_signal(&main.sleepCond); // In case is waiting for stop or ponderhit
|
|
||||||
|
|
||||||
while (!main.do_sleep)
|
|
||||||
cond_wait(&sleepCond, &main.sleepLock);
|
|
||||||
|
|
||||||
lock_release(&main.sleepLock);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// ThreadsManager::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 ThreadsManager::wait_for_stop_or_ponderhit() {
|
|
||||||
|
|
||||||
Signals.stopOnPonderhit = true;
|
|
||||||
|
|
||||||
Thread& main = threads[0];
|
|
||||||
|
|
||||||
lock_grab(&main.sleepLock);
|
|
||||||
|
|
||||||
while (!Signals.stop)
|
|
||||||
cond_wait(&main.sleepCond, &main.sleepLock);
|
|
||||||
|
|
||||||
lock_release(&main.sleepLock);
|
|
||||||
}
|
}
|
||||||
|
|||||||
+95
-70
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,42 +20,68 @@
|
|||||||
#if !defined(THREAD_H_INCLUDED)
|
#if !defined(THREAD_H_INCLUDED)
|
||||||
#define THREAD_H_INCLUDED
|
#define THREAD_H_INCLUDED
|
||||||
|
|
||||||
#include <cstring>
|
#include <vector>
|
||||||
|
|
||||||
#include "lock.h"
|
|
||||||
#include "material.h"
|
#include "material.h"
|
||||||
#include "movepick.h"
|
#include "movepick.h"
|
||||||
#include "pawns.h"
|
#include "pawns.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
|
|
||||||
const int MAX_THREADS = 32;
|
const int MAX_THREADS = 64; // Because SplitPoint::slavesMask is a uint64_t
|
||||||
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Thread;
|
||||||
|
|
||||||
struct SplitPoint {
|
struct SplitPoint {
|
||||||
|
|
||||||
// Const data after splitPoint has been setup
|
// Const data after split point has been setup
|
||||||
SplitPoint* parent;
|
|
||||||
const Position* pos;
|
const Position* pos;
|
||||||
|
const Search::Stack* ss;
|
||||||
|
Thread* masterThread;
|
||||||
Depth depth;
|
Depth depth;
|
||||||
Value beta;
|
Value beta;
|
||||||
int nodeType;
|
int nodeType;
|
||||||
int ply;
|
|
||||||
int master;
|
|
||||||
Move threatMove;
|
Move threatMove;
|
||||||
|
|
||||||
// Const pointers to shared data
|
// Const pointers to shared data
|
||||||
MovePicker* mp;
|
MovePicker* movePicker;
|
||||||
Search::Stack* ss;
|
SplitPoint* parentSplitPoint;
|
||||||
|
|
||||||
// Shared data
|
// Shared data
|
||||||
Lock lock;
|
Mutex mutex;
|
||||||
|
volatile uint64_t slavesMask;
|
||||||
volatile int64_t nodes;
|
volatile int64_t nodes;
|
||||||
volatile Value alpha;
|
volatile Value alpha;
|
||||||
volatile Value bestValue;
|
volatile Value bestValue;
|
||||||
|
volatile Move bestMove;
|
||||||
volatile int moveCount;
|
volatile int moveCount;
|
||||||
volatile bool is_betaCutoff;
|
volatile bool cutoff;
|
||||||
volatile bool is_slave[MAX_THREADS];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -66,77 +92,76 @@ struct SplitPoint {
|
|||||||
|
|
||||||
struct Thread {
|
struct Thread {
|
||||||
|
|
||||||
void wake_up();
|
Thread();
|
||||||
|
virtual ~Thread();
|
||||||
|
|
||||||
|
virtual void idle_loop();
|
||||||
|
void notify_one();
|
||||||
bool cutoff_occurred() const;
|
bool cutoff_occurred() const;
|
||||||
bool is_available_to(int master) const;
|
bool is_available_to(Thread* master) const;
|
||||||
void idle_loop(SplitPoint* sp);
|
void wait_for(volatile const bool& b);
|
||||||
void main_loop();
|
|
||||||
void timer_loop();
|
|
||||||
|
|
||||||
SplitPoint splitPoints[MAX_ACTIVE_SPLIT_POINTS];
|
template <bool Fake>
|
||||||
MaterialInfoTable materialTable;
|
void split(Position& pos, Search::Stack* ss, Value alpha, Value beta, Value* bestValue, Move* bestMove,
|
||||||
PawnInfoTable pawnTable;
|
Depth depth, Move threatMove, int moveCount, MovePicker* movePicker, int nodeType);
|
||||||
int threadID;
|
|
||||||
|
SplitPoint splitPoints[MAX_SPLITPOINTS_PER_THREAD];
|
||||||
|
Material::Table materialTable;
|
||||||
|
Endgames endgames;
|
||||||
|
Pawns::Table pawnsTable;
|
||||||
|
Position* activePosition;
|
||||||
|
size_t idx;
|
||||||
int maxPly;
|
int maxPly;
|
||||||
Lock sleepLock;
|
Mutex mutex;
|
||||||
WaitCondition sleepCond;
|
ConditionVariable sleepCondition;
|
||||||
SplitPoint* volatile splitPoint;
|
NativeHandle handle;
|
||||||
volatile int activeSplitPoints;
|
SplitPoint* volatile activeSplitPoint;
|
||||||
volatile bool is_searching;
|
volatile int splitPointsSize;
|
||||||
volatile bool do_sleep;
|
volatile bool searching;
|
||||||
volatile bool do_terminate;
|
volatile bool exit;
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
|
||||||
HANDLE handle;
|
|
||||||
#else
|
|
||||||
pthread_t handle;
|
|
||||||
#endif
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
/// ThreadsManager class handles all the threads related stuff like init, starting,
|
/// MainThread and TimerThread are sublassed from Thread to characterize the two
|
||||||
|
/// special threads: the main one and the recurring timer.
|
||||||
|
|
||||||
|
struct MainThread : public Thread {
|
||||||
|
MainThread() : thinking(true) {} // Avoid a race with start_thinking()
|
||||||
|
virtual void idle_loop();
|
||||||
|
volatile bool thinking;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TimerThread : public Thread {
|
||||||
|
TimerThread() : msec(0) {}
|
||||||
|
virtual void idle_loop();
|
||||||
|
int msec;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// ThreadPool struct handles all the threads related stuff like init, starting,
|
||||||
/// parking and, the most important, launching a slave thread at a split point.
|
/// 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.
|
/// All the access to shared thread data is done through this class.
|
||||||
|
|
||||||
class ThreadsManager {
|
struct ThreadPool : public std::vector<Thread*> {
|
||||||
/* 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();
|
|
||||||
|
|
||||||
bool use_sleeping_threads() const { return useSleepingThreads; }
|
void init(); // No c'tor and d'tor, threads rely on globals that should
|
||||||
int min_split_depth() const { return minimumSplitDepth; }
|
void exit(); // be initialized and valid during the whole thread lifetime.
|
||||||
int size() const { return activeThreads; }
|
|
||||||
|
|
||||||
void set_size(int cnt);
|
MainThread* main_thread() { return static_cast<MainThread*>((*this)[0]); }
|
||||||
void read_uci_options();
|
void read_uci_options();
|
||||||
bool available_slave_exists(int master) const;
|
Thread* available_slave(Thread* master) const;
|
||||||
bool split_point_finished(SplitPoint* sp) const;
|
void wait_for_think_finished();
|
||||||
void set_timer(int msec);
|
void start_thinking(const Position&, const Search::LimitsType&,
|
||||||
void wait_for_stop_or_ponderhit();
|
const std::vector<Move>&, Search::StateStackPtr&);
|
||||||
void stop_thinking();
|
|
||||||
void start_thinking(const Position& pos, const Search::LimitsType& limits,
|
|
||||||
const std::vector<Move>& searchMoves, bool asyncMode);
|
|
||||||
|
|
||||||
template <bool Fake>
|
bool sleepWhileIdle;
|
||||||
Value split(Position& pos, Search::Stack* ss, Value alpha, Value beta, Value bestValue,
|
|
||||||
Depth depth, Move threatMove, int moveCount, MovePicker* mp, int nodeType);
|
|
||||||
private:
|
|
||||||
friend struct Thread;
|
|
||||||
|
|
||||||
Thread threads[MAX_THREADS + 1]; // Last one is used as a timer
|
|
||||||
Lock threadsLock;
|
|
||||||
Depth minimumSplitDepth;
|
Depth minimumSplitDepth;
|
||||||
int maxThreadsPerSplitPoint;
|
size_t maxThreadsPerSplitPoint;
|
||||||
int activeThreads;
|
Mutex mutex;
|
||||||
bool useSleepingThreads;
|
ConditionVariable sleepCondition;
|
||||||
WaitCondition sleepCond;
|
TimerThread* timer;
|
||||||
};
|
};
|
||||||
|
|
||||||
extern ThreadsManager Threads;
|
extern ThreadPool Threads;
|
||||||
|
|
||||||
#endif // !defined(THREAD_H_INCLUDED)
|
#endif // !defined(THREAD_H_INCLUDED)
|
||||||
|
|||||||
+13
-13
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,7 +20,6 @@
|
|||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
#include "misc.h"
|
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "timeman.h"
|
#include "timeman.h"
|
||||||
#include "ucioption.h"
|
#include "ucioption.h"
|
||||||
@@ -30,7 +29,7 @@ namespace {
|
|||||||
/// Constants
|
/// Constants
|
||||||
|
|
||||||
const int MoveHorizon = 50; // Plan time management at most this many moves ahead
|
const int MoveHorizon = 50; // Plan time management at most this many moves ahead
|
||||||
const float MaxRatio = 3.0f; // When in trouble, we can step over reserved time with this ratio
|
const float MaxRatio = 7.0f; // When in trouble, we can step over reserved time with this ratio
|
||||||
const float StealRatio = 0.33f; // However we must not steal time from remaining moves over this ratio
|
const float StealRatio = 0.33f; // However we must not steal time from remaining moves over this ratio
|
||||||
|
|
||||||
|
|
||||||
@@ -73,7 +72,7 @@ namespace {
|
|||||||
enum TimeType { OptimumTime, MaxTime };
|
enum TimeType { OptimumTime, MaxTime };
|
||||||
|
|
||||||
template<TimeType>
|
template<TimeType>
|
||||||
int remaining(int myTime, int movesToGo, int fullMoveNumber);
|
int remaining(int myTime, int movesToGo, int fullMoveNumber, int slowMover);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -84,7 +83,7 @@ void TimeManager::pv_instability(int curChanges, int prevChanges) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void TimeManager::init(const Search::LimitsType& limits, int currentPly)
|
void TimeManager::init(const Search::LimitsType& limits, int currentPly, Color us)
|
||||||
{
|
{
|
||||||
/* We support four different kind of time controls:
|
/* We support four different kind of time controls:
|
||||||
|
|
||||||
@@ -108,25 +107,26 @@ void TimeManager::init(const Search::LimitsType& limits, int currentPly)
|
|||||||
int emergencyBaseTime = Options["Emergency Base Time"];
|
int emergencyBaseTime = Options["Emergency Base Time"];
|
||||||
int emergencyMoveTime = Options["Emergency Move Time"];
|
int emergencyMoveTime = Options["Emergency Move Time"];
|
||||||
int minThinkingTime = Options["Minimum Thinking Time"];
|
int minThinkingTime = Options["Minimum Thinking Time"];
|
||||||
|
int slowMover = Options["Slow Mover"];
|
||||||
|
|
||||||
// Initialize to maximum values but unstablePVExtraTime that is reset
|
// Initialize to maximum values but unstablePVExtraTime that is reset
|
||||||
unstablePVExtraTime = 0;
|
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
|
// 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.
|
// minimum of calculated search time values. Usually the greatest hypMTG gives the minimum values.
|
||||||
for (hypMTG = 1; hypMTG <= (limits.movesToGo ? std::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
|
// Calculate thinking time for hypothetic "moves to go"-value
|
||||||
hypMyTime = limits.time
|
hypMyTime = limits.time[us]
|
||||||
+ limits.increment * (hypMTG - 1)
|
+ limits.inc[us] * (hypMTG - 1)
|
||||||
- emergencyBaseTime
|
- emergencyBaseTime
|
||||||
- emergencyMoveTime * std::min(hypMTG, emergencyMoveHorizon);
|
- emergencyMoveTime * std::min(hypMTG, emergencyMoveHorizon);
|
||||||
|
|
||||||
hypMyTime = std::max(hypMyTime, 0);
|
hypMyTime = std::max(hypMyTime, 0);
|
||||||
|
|
||||||
t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, currentPly);
|
t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, currentPly, slowMover);
|
||||||
t2 = minThinkingTime + remaining<MaxTime>(hypMyTime, hypMTG, currentPly);
|
t2 = minThinkingTime + remaining<MaxTime>(hypMyTime, hypMTG, currentPly, slowMover);
|
||||||
|
|
||||||
optimumSearchTime = std::min(optimumSearchTime, t1);
|
optimumSearchTime = std::min(optimumSearchTime, t1);
|
||||||
maximumSearchTime = std::min(maximumSearchTime, t2);
|
maximumSearchTime = std::min(maximumSearchTime, t2);
|
||||||
@@ -143,12 +143,12 @@ void TimeManager::init(const Search::LimitsType& limits, int currentPly)
|
|||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
template<TimeType T>
|
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 TMaxRatio = (T == OptimumTime ? 1 : MaxRatio);
|
||||||
const float TStealRatio = (T == OptimumTime ? 0 : StealRatio);
|
const float TStealRatio = (T == OptimumTime ? 0 : StealRatio);
|
||||||
|
|
||||||
int thisMoveImportance = move_importance(currentPly);
|
int thisMoveImportance = move_importance(currentPly) * slowMover / 100;
|
||||||
int otherMovesImportance = 0;
|
int otherMovesImportance = 0;
|
||||||
|
|
||||||
for (int i = 1; i < movesToGo; i++)
|
for (int i = 1; i < movesToGo; i++)
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
|
|
||||||
class TimeManager {
|
class TimeManager {
|
||||||
public:
|
public:
|
||||||
void init(const Search::LimitsType& limits, int currentPly);
|
void init(const Search::LimitsType& limits, int currentPly, Color us);
|
||||||
void pv_instability(int curChanges, int prevChanges);
|
void pv_instability(int curChanges, int prevChanges);
|
||||||
int available_time() const { return optimumSearchTime + unstablePVExtraTime; }
|
int available_time() const { return optimumSearchTime + unstablePVExtraTime; }
|
||||||
int maximum_time() const { return maximumSearchTime; }
|
int maximum_time() const { return maximumSearchTime; }
|
||||||
|
|||||||
+28
-50
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,49 +20,37 @@
|
|||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "bitboard.h"
|
||||||
#include "tt.h"
|
#include "tt.h"
|
||||||
|
|
||||||
TranspositionTable TT; // Our global transposition table
|
TranspositionTable TT; // Our global transposition table
|
||||||
|
|
||||||
TranspositionTable::TranspositionTable() {
|
|
||||||
|
|
||||||
size = generation = 0;
|
|
||||||
entries = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
TranspositionTable::~TranspositionTable() {
|
|
||||||
|
|
||||||
delete [] entries;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// TranspositionTable::set_size() sets the size of the transposition table,
|
/// 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 clusters and each cluster consists of ClusterSize number of TTEntry.
|
||||||
|
|
||||||
void TranspositionTable::set_size(size_t mbSize) {
|
void TranspositionTable::set_size(size_t mbSize) {
|
||||||
|
|
||||||
size_t newSize = 1024;
|
assert(msb((mbSize << 20) / sizeof(TTEntry)) < 32);
|
||||||
|
|
||||||
// Transposition table consists of clusters and each cluster consists
|
uint32_t size = ClusterSize << msb((mbSize << 20) / sizeof(TTEntry[ClusterSize]));
|
||||||
// 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;
|
|
||||||
|
|
||||||
if (newSize == size)
|
if (hashMask == size - ClusterSize)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
size = newSize;
|
hashMask = size - ClusterSize;
|
||||||
delete [] entries;
|
delete [] table;
|
||||||
entries = new (std::nothrow) TTCluster[size];
|
table = new (std::nothrow) TTEntry[size];
|
||||||
if (!entries)
|
|
||||||
|
if (!table)
|
||||||
{
|
{
|
||||||
std::cerr << "Failed to allocate " << mbSize
|
std::cerr << "Failed to allocate " << mbSize
|
||||||
<< "MB for transposition table." << std::endl;
|
<< "MB for transposition table." << std::endl;
|
||||||
exit(EXIT_FAILURE);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
clear();
|
|
||||||
|
clear(); // Operator new is not guaranteed to initialize memory to zero
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -72,7 +60,7 @@ void TranspositionTable::set_size(size_t mbSize) {
|
|||||||
|
|
||||||
void TranspositionTable::clear() {
|
void TranspositionTable::clear() {
|
||||||
|
|
||||||
memset(entries, 0, size * sizeof(TTCluster));
|
memset(table, 0, (hashMask + ClusterSize) * sizeof(TTEntry));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -84,35 +72,35 @@ void TranspositionTable::clear() {
|
|||||||
/// more valuable than a TTEntry t2 if t1 is from the current search and t2 is from
|
/// 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.
|
/// 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 key, Value v, Bound t, Depth d, Move m, Value statV, Value kingD) {
|
||||||
|
|
||||||
int c1, c2, c3;
|
int c1, c2, c3;
|
||||||
TTEntry *tte, *replace;
|
TTEntry *tte, *replace;
|
||||||
uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key inside the cluster
|
uint32_t key32 = key >> 32; // Use the high 32 bits as key inside the cluster
|
||||||
|
|
||||||
tte = replace = first_entry(posKey);
|
tte = replace = first_entry(key);
|
||||||
|
|
||||||
for (int i = 0; i < ClusterSize; i++, tte++)
|
for (unsigned i = 0; i < ClusterSize; i++, tte++)
|
||||||
{
|
{
|
||||||
if (!tte->key() || tte->key() == posKey32) // Empty or overwrite old
|
if (!tte->key() || tte->key() == key32) // Empty or overwrite old
|
||||||
{
|
{
|
||||||
// Preserve any existing ttMove
|
// Preserve any existing ttMove
|
||||||
if (m == MOVE_NONE)
|
if (m == MOVE_NONE)
|
||||||
m = tte->move();
|
m = tte->move();
|
||||||
|
|
||||||
tte->save(posKey32, v, t, d, m, generation, statV, kingD);
|
tte->save(key32, v, t, d, m, generation, statV, kingD);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implement replace strategy
|
// Implement replace strategy
|
||||||
c1 = (replace->generation() == generation ? 2 : 0);
|
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);
|
c3 = (tte->depth() < replace->depth() ? 1 : 0);
|
||||||
|
|
||||||
if (c1 + c2 + c3 > 0)
|
if (c1 + c2 + c3 > 0)
|
||||||
replace = tte;
|
replace = tte;
|
||||||
}
|
}
|
||||||
replace->save(posKey32, v, t, d, m, generation, statV, kingD);
|
replace->save(key32, v, t, d, m, generation, statV, kingD);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -120,24 +108,14 @@ void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d,
|
|||||||
/// transposition table. Returns a pointer to the TTEntry or NULL if
|
/// transposition table. Returns a pointer to the TTEntry or NULL if
|
||||||
/// position is not found.
|
/// position is not found.
|
||||||
|
|
||||||
TTEntry* TranspositionTable::probe(const Key posKey) const {
|
TTEntry* TranspositionTable::probe(const Key key) const {
|
||||||
|
|
||||||
uint32_t posKey32 = posKey >> 32;
|
TTEntry* tte = first_entry(key);
|
||||||
TTEntry* tte = first_entry(posKey);
|
uint32_t key32 = key >> 32;
|
||||||
|
|
||||||
for (int i = 0; i < ClusterSize; i++, tte++)
|
for (unsigned i = 0; i < ClusterSize; i++, tte++)
|
||||||
if (tte->key() == posKey32)
|
if (tte->key() == key32)
|
||||||
return tte;
|
return tte;
|
||||||
|
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// TranspositionTable::new_search() is called at the beginning of every new
|
|
||||||
/// search. It increments the "generation" variable, which is used to
|
|
||||||
/// distinguish transposition table entries from previous searches from
|
|
||||||
/// entries from the current search.
|
|
||||||
|
|
||||||
void TranspositionTable::new_search() {
|
|
||||||
generation++;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,12 +20,9 @@
|
|||||||
#if !defined(TT_H_INCLUDED)
|
#if !defined(TT_H_INCLUDED)
|
||||||
#define TT_H_INCLUDED
|
#define TT_H_INCLUDED
|
||||||
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
#include "misc.h"
|
#include "misc.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
|
|
||||||
/// The TTEntry is the class of transposition table entries
|
/// The TTEntry is the class of transposition table entries
|
||||||
///
|
///
|
||||||
/// A TTEntry needs 128 bits to be stored
|
/// A TTEntry needs 128 bits to be stored
|
||||||
@@ -47,16 +44,16 @@
|
|||||||
class TTEntry {
|
class TTEntry {
|
||||||
|
|
||||||
public:
|
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 ev, Value em) {
|
||||||
|
|
||||||
key32 = (uint32_t)k;
|
key32 = (uint32_t)k;
|
||||||
move16 = (uint16_t)m;
|
move16 = (uint16_t)m;
|
||||||
valueType = (uint8_t)t;
|
bound = (uint8_t)b;
|
||||||
generation8 = (uint8_t)g;
|
generation8 = (uint8_t)g;
|
||||||
value16 = (int16_t)v;
|
value16 = (int16_t)v;
|
||||||
depth16 = (int16_t)d;
|
depth16 = (int16_t)d;
|
||||||
staticValue = (int16_t)statV;
|
evalValue = (int16_t)ev;
|
||||||
staticMargin = (int16_t)statM;
|
evalMargin = (int16_t)em;
|
||||||
}
|
}
|
||||||
void set_generation(int g) { generation8 = (uint8_t)g; }
|
void set_generation(int g) { generation8 = (uint8_t)g; }
|
||||||
|
|
||||||
@@ -64,54 +61,43 @@ public:
|
|||||||
Depth depth() const { return (Depth)depth16; }
|
Depth depth() const { return (Depth)depth16; }
|
||||||
Move move() const { return (Move)move16; }
|
Move move() const { return (Move)move16; }
|
||||||
Value value() const { return (Value)value16; }
|
Value value() const { return (Value)value16; }
|
||||||
ValueType type() const { return (ValueType)valueType; }
|
Bound type() const { return (Bound)bound; }
|
||||||
int generation() const { return (int)generation8; }
|
int generation() const { return (int)generation8; }
|
||||||
Value static_value() const { return (Value)staticValue; }
|
Value eval_value() const { return (Value)evalValue; }
|
||||||
Value static_value_margin() const { return (Value)staticMargin; }
|
Value eval_margin() const { return (Value)evalMargin; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
uint32_t key32;
|
uint32_t key32;
|
||||||
uint16_t move16;
|
uint16_t move16;
|
||||||
uint8_t valueType, generation8;
|
uint8_t bound, generation8;
|
||||||
int16_t value16, depth16, staticValue, staticMargin;
|
int16_t value16, depth16, evalValue, evalMargin;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
/// This is the number of TTEntry slots for each cluster
|
/// A TranspositionTable consists of a power of 2 number of clusters and each
|
||||||
const int ClusterSize = 4;
|
/// cluster consists of ClusterSize number of TTEntry. Each non-empty entry
|
||||||
|
/// contains information of exactly one position. Size of a cluster shall not be
|
||||||
|
/// bigger than a cache line size. In case it is less, it should be padded to
|
||||||
/// TTCluster consists of ClusterSize number of TTEntries. Size of TTCluster
|
/// guarantee always aligned accesses.
|
||||||
/// must not be bigger than a cache line size. In case it is less, it should
|
|
||||||
/// be padded to guarantee always aligned accesses.
|
|
||||||
|
|
||||||
struct TTCluster {
|
|
||||||
TTEntry data[ClusterSize];
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/// The transposition table class. This is basically just a huge array containing
|
|
||||||
/// TTCluster objects, and a few methods for writing and reading entries.
|
|
||||||
|
|
||||||
class TranspositionTable {
|
class TranspositionTable {
|
||||||
|
|
||||||
TranspositionTable(const TranspositionTable&);
|
static const unsigned ClusterSize = 4; // A cluster is 64 Bytes
|
||||||
TranspositionTable& operator=(const TranspositionTable&);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
TranspositionTable();
|
~TranspositionTable() { delete [] table; }
|
||||||
~TranspositionTable();
|
void new_search() { generation++; }
|
||||||
|
|
||||||
|
TTEntry* probe(const Key key) const;
|
||||||
|
TTEntry* first_entry(const Key key) const;
|
||||||
|
void refresh(const TTEntry* tte) const;
|
||||||
void set_size(size_t mbSize);
|
void set_size(size_t mbSize);
|
||||||
void clear();
|
void clear();
|
||||||
void store(const Key posKey, Value v, ValueType type, Depth d, Move m, Value statV, Value kingD);
|
void store(const Key key, 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;
|
|
||||||
void refresh(const TTEntry* tte) const;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
size_t size;
|
uint32_t hashMask;
|
||||||
TTCluster* entries;
|
TTEntry* table;
|
||||||
uint8_t generation; // Size must be not bigger then TTEntry::generation8
|
uint8_t generation; // Size must be not bigger then TTEntry::generation8
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -122,9 +108,9 @@ extern TranspositionTable TT;
|
|||||||
/// a cluster given a position. The lowest order bits of the key are used to
|
/// a cluster given a position. The lowest order bits of the key are used to
|
||||||
/// get the index of the cluster.
|
/// get the index of the cluster.
|
||||||
|
|
||||||
inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
|
inline TTEntry* TranspositionTable::first_entry(const Key key) const {
|
||||||
|
|
||||||
return entries[((uint32_t)posKey) & (size - 1)].data;
|
return table + ((uint32_t)key & hashMask);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -136,38 +122,4 @@ inline void TranspositionTable::refresh(const TTEntry* tte) const {
|
|||||||
const_cast<TTEntry*>(tte)->set_generation(generation);
|
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)
|
#endif // !defined(TT_H_INCLUDED)
|
||||||
|
|||||||
+118
-138
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -34,37 +34,15 @@
|
|||||||
/// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
|
/// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
|
||||||
/// | only in 64-bit mode. For compiling requires hardware with
|
/// | only in 64-bit mode. For compiling requires hardware with
|
||||||
/// | popcnt support.
|
/// | popcnt support.
|
||||||
///
|
|
||||||
/// -DOLD_LOCKS | 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.
|
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cctype>
|
||||||
#include <climits>
|
#include <climits>
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
#include "platform.h"
|
||||||
|
|
||||||
// Disable some silly and noisy warning from MSVC compiler
|
#if defined(_WIN64) && !defined(IS_64BIT)
|
||||||
#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'
|
|
||||||
|
|
||||||
// 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(_WIN64)
|
|
||||||
# include <intrin.h> // MSVC popcnt and bsfq instrinsics
|
# include <intrin.h> // MSVC popcnt and bsfq instrinsics
|
||||||
# define IS_64BIT
|
# define IS_64BIT
|
||||||
# define USE_BSFQ
|
# define USE_BSFQ
|
||||||
@@ -74,6 +52,10 @@ typedef unsigned __int64 uint64_t;
|
|||||||
# include <nmmintrin.h> // Intel header for _mm_popcnt_u64() intrinsic
|
# include <nmmintrin.h> // Intel header for _mm_popcnt_u64() intrinsic
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
# if !defined(NO_PREFETCH) && (defined(__INTEL_COMPILER) || defined(_MSC_VER))
|
||||||
|
# include <xmmintrin.h> // Intel and Microsoft header for _mm_prefetch()
|
||||||
|
# endif
|
||||||
|
|
||||||
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
|
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
|
||||||
# define CACHE_LINE_ALIGNMENT __declspec(align(64))
|
# define CACHE_LINE_ALIGNMENT __declspec(align(64))
|
||||||
#else
|
#else
|
||||||
@@ -103,7 +85,7 @@ const bool Is64Bit = false;
|
|||||||
typedef uint64_t Key;
|
typedef uint64_t Key;
|
||||||
typedef uint64_t Bitboard;
|
typedef uint64_t Bitboard;
|
||||||
|
|
||||||
const int MAX_MOVES = 256;
|
const int MAX_MOVES = 192;
|
||||||
const int MAX_PLY = 100;
|
const int MAX_PLY = 100;
|
||||||
const int MAX_PLY_PLUS_2 = MAX_PLY + 2;
|
const int MAX_PLY_PLUS_2 = MAX_PLY + 2;
|
||||||
|
|
||||||
@@ -142,22 +124,33 @@ enum Move {
|
|||||||
MOVE_NULL = 65
|
MOVE_NULL = 65
|
||||||
};
|
};
|
||||||
|
|
||||||
struct MoveStack {
|
enum MoveType {
|
||||||
Move move;
|
NORMAL = 0,
|
||||||
int score;
|
PROMOTION = 1 << 14,
|
||||||
|
ENPASSANT = 2 << 14,
|
||||||
|
CASTLE = 3 << 14
|
||||||
};
|
};
|
||||||
|
|
||||||
inline bool operator<(const MoveStack& f, const MoveStack& s) {
|
enum CastleRight { // Defined as in PolyGlot book hash key
|
||||||
return f.score < s.score;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum CastleRight {
|
|
||||||
CASTLES_NONE = 0,
|
CASTLES_NONE = 0,
|
||||||
WHITE_OO = 1,
|
WHITE_OO = 1,
|
||||||
BLACK_OO = 2,
|
WHITE_OOO = 2,
|
||||||
WHITE_OOO = 4,
|
BLACK_OO = 4,
|
||||||
BLACK_OOO = 8,
|
BLACK_OOO = 8,
|
||||||
ALL_CASTLES = 15
|
ALL_CASTLES = 15,
|
||||||
|
CASTLE_RIGHT_NB = 16
|
||||||
|
};
|
||||||
|
|
||||||
|
enum CastlingSide {
|
||||||
|
KING_SIDE,
|
||||||
|
QUEEN_SIDE,
|
||||||
|
CASTLING_SIDE_NB = 2
|
||||||
|
};
|
||||||
|
|
||||||
|
enum Phase {
|
||||||
|
PHASE_ENDGAME = 0,
|
||||||
|
PHASE_MIDGAME = 128,
|
||||||
|
MG = 0, EG = 1, PHASE_NB = 2
|
||||||
};
|
};
|
||||||
|
|
||||||
enum ScaleFactor {
|
enum ScaleFactor {
|
||||||
@@ -167,11 +160,11 @@ enum ScaleFactor {
|
|||||||
SCALE_FACTOR_NONE = 255
|
SCALE_FACTOR_NONE = 255
|
||||||
};
|
};
|
||||||
|
|
||||||
enum ValueType {
|
enum Bound {
|
||||||
VALUE_TYPE_NONE = 0,
|
BOUND_NONE = 0,
|
||||||
VALUE_TYPE_UPPER = 1,
|
BOUND_UPPER = 1,
|
||||||
VALUE_TYPE_LOWER = 2,
|
BOUND_LOWER = 2,
|
||||||
VALUE_TYPE_EXACT = VALUE_TYPE_UPPER | VALUE_TYPE_LOWER
|
BOUND_EXACT = BOUND_UPPER | BOUND_LOWER
|
||||||
};
|
};
|
||||||
|
|
||||||
enum Value {
|
enum Value {
|
||||||
@@ -186,22 +179,30 @@ enum Value {
|
|||||||
VALUE_MATED_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_P = INT_MAX,
|
||||||
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN
|
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN,
|
||||||
|
|
||||||
|
PawnValueMg = 198, PawnValueEg = 258,
|
||||||
|
KnightValueMg = 817, KnightValueEg = 846,
|
||||||
|
BishopValueMg = 836, BishopValueEg = 857,
|
||||||
|
RookValueMg = 1270, RookValueEg = 1278,
|
||||||
|
QueenValueMg = 2521, QueenValueEg = 2558
|
||||||
};
|
};
|
||||||
|
|
||||||
enum PieceType {
|
enum PieceType {
|
||||||
NO_PIECE_TYPE = 0,
|
NO_PIECE_TYPE = 0, ALL_PIECES = 0,
|
||||||
PAWN = 1, KNIGHT = 2, BISHOP = 3, ROOK = 4, QUEEN = 5, KING = 6
|
PAWN = 1, KNIGHT = 2, BISHOP = 3, ROOK = 4, QUEEN = 5, KING = 6,
|
||||||
|
PIECE_TYPE_NB = 8
|
||||||
};
|
};
|
||||||
|
|
||||||
enum Piece {
|
enum Piece {
|
||||||
NO_PIECE = 16, // color_of(NO_PIECE) == NO_COLOR
|
NO_PIECE = 0,
|
||||||
W_PAWN = 1, W_KNIGHT = 2, W_BISHOP = 3, W_ROOK = 4, W_QUEEN = 5, W_KING = 6,
|
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
|
B_PAWN = 9, B_KNIGHT = 10, B_BISHOP = 11, B_ROOK = 12, B_QUEEN = 13, B_KING = 14,
|
||||||
|
PIECE_NB = 16
|
||||||
};
|
};
|
||||||
|
|
||||||
enum Color {
|
enum Color {
|
||||||
WHITE, BLACK, NO_COLOR
|
WHITE, BLACK, NO_COLOR, COLOR_NB = 2
|
||||||
};
|
};
|
||||||
|
|
||||||
enum Depth {
|
enum Depth {
|
||||||
@@ -211,7 +212,7 @@ enum Depth {
|
|||||||
DEPTH_ZERO = 0 * ONE_PLY,
|
DEPTH_ZERO = 0 * ONE_PLY,
|
||||||
DEPTH_QS_CHECKS = -1 * ONE_PLY,
|
DEPTH_QS_CHECKS = -1 * ONE_PLY,
|
||||||
DEPTH_QS_NO_CHECKS = -2 * ONE_PLY,
|
DEPTH_QS_NO_CHECKS = -2 * ONE_PLY,
|
||||||
DEPTH_QS_RECAPTURES = -4 * ONE_PLY,
|
DEPTH_QS_RECAPTURES = -5 * ONE_PLY,
|
||||||
|
|
||||||
DEPTH_NONE = -127 * ONE_PLY
|
DEPTH_NONE = -127 * ONE_PLY
|
||||||
};
|
};
|
||||||
@@ -227,6 +228,8 @@ enum Square {
|
|||||||
SQ_A8, SQ_B8, SQ_C8, SQ_D8, SQ_E8, SQ_F8, SQ_G8, SQ_H8,
|
SQ_A8, SQ_B8, SQ_C8, SQ_D8, SQ_E8, SQ_F8, SQ_G8, SQ_H8,
|
||||||
SQ_NONE,
|
SQ_NONE,
|
||||||
|
|
||||||
|
SQUARE_NB = 64,
|
||||||
|
|
||||||
DELTA_N = 8,
|
DELTA_N = 8,
|
||||||
DELTA_E = 1,
|
DELTA_E = 1,
|
||||||
DELTA_S = -8,
|
DELTA_S = -8,
|
||||||
@@ -241,11 +244,11 @@ enum Square {
|
|||||||
};
|
};
|
||||||
|
|
||||||
enum File {
|
enum File {
|
||||||
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H
|
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, FILE_NB = 8
|
||||||
};
|
};
|
||||||
|
|
||||||
enum Rank {
|
enum Rank {
|
||||||
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8
|
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_NB = 8
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -321,23 +324,52 @@ inline Score operator/(Score s, int i) {
|
|||||||
return make_score(mg_value(s) / i, eg_value(s) / i);
|
return make_score(mg_value(s) / i, eg_value(s) / i);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
|
||||||
#undef ENABLE_OPERATORS_ON
|
#undef ENABLE_OPERATORS_ON
|
||||||
#undef ENABLE_SAFE_OPERATORS_ON
|
#undef ENABLE_SAFE_OPERATORS_ON
|
||||||
|
|
||||||
const Value PawnValueMidgame = Value(0x0C6);
|
namespace Zobrist {
|
||||||
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);
|
|
||||||
|
|
||||||
extern const Value PieceValueMidgame[17];
|
extern Key psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
|
||||||
extern const Value PieceValueEndgame[17];
|
extern Key enpassant[FILE_NB];
|
||||||
extern int SquareDistance[64][64];
|
extern Key castle[CASTLE_RIGHT_NB];
|
||||||
|
extern Key side;
|
||||||
|
extern Key exclusion;
|
||||||
|
|
||||||
|
void init();
|
||||||
|
}
|
||||||
|
|
||||||
|
CACHE_LINE_ALIGNMENT
|
||||||
|
|
||||||
|
extern Score pieceSquareTable[PIECE_NB][SQUARE_NB];
|
||||||
|
extern Value PieceValue[PHASE_NB][PIECE_NB];
|
||||||
|
extern int SquareDistance[SQUARE_NB][SQUARE_NB];
|
||||||
|
|
||||||
|
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) {
|
inline Value mate_in(int ply) {
|
||||||
return VALUE_MATE - ply;
|
return VALUE_MATE - ply;
|
||||||
@@ -351,23 +383,20 @@ inline Piece make_piece(Color c, PieceType pt) {
|
|||||||
return Piece((c << 3) | pt);
|
return Piece((c << 3) | pt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline CastleRight make_castle_right(Color c, CastlingSide s) {
|
||||||
|
return CastleRight(WHITE_OO << ((s == QUEEN_SIDE) + 2 * c));
|
||||||
|
}
|
||||||
|
|
||||||
inline PieceType type_of(Piece p) {
|
inline PieceType type_of(Piece p) {
|
||||||
return PieceType(p & 7);
|
return PieceType(p & 7);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Color color_of(Piece p) {
|
inline Color color_of(Piece p) {
|
||||||
|
assert(p != NO_PIECE);
|
||||||
return Color(p >> 3);
|
return Color(p >> 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Color flip(Color c) {
|
inline bool is_ok(Square s) {
|
||||||
return Color(c ^ 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Square make_square(File f, Rank r) {
|
|
||||||
return Square((r << 3) | f);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline bool square_is_ok(Square s) {
|
|
||||||
return s >= SQ_A1 && s <= SQ_H8;
|
return s >= SQ_A1 && s <= SQ_H8;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,12 +408,8 @@ inline Rank rank_of(Square s) {
|
|||||||
return Rank(s >> 3);
|
return Rank(s >> 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square flip(Square s) {
|
|
||||||
return Square(s ^ 56);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Square mirror(Square s) {
|
inline Square mirror(Square s) {
|
||||||
return Square(s ^ 7);
|
return Square(s ^ 7); // Horizontal flip SQ_A1 -> SQ_H1
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square relative_square(Color c, Square s) {
|
inline Square relative_square(Color c, Square s) {
|
||||||
@@ -400,7 +425,7 @@ inline Rank relative_rank(Color c, Square s) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
inline bool opposite_colors(Square s1, Square s2) {
|
inline bool opposite_colors(Square s1, Square s2) {
|
||||||
int s = s1 ^ s2;
|
int s = int(s1) ^ int(s2);
|
||||||
return ((s >> 3) ^ s) & 1;
|
return ((s >> 3) ^ s) & 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -416,47 +441,31 @@ inline int square_distance(Square s1, Square s2) {
|
|||||||
return SquareDistance[s1][s2];
|
return SquareDistance[s1][s2];
|
||||||
}
|
}
|
||||||
|
|
||||||
inline char piece_type_to_char(PieceType pt) {
|
inline char file_to_char(File f, bool tolower = true) {
|
||||||
return " PNBRQK"[pt];
|
return char(f - FILE_A + (tolower ? 'a' : 'A'));
|
||||||
}
|
|
||||||
|
|
||||||
inline char file_to_char(File f) {
|
|
||||||
return char(f - FILE_A + int('a'));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline char rank_to_char(Rank r) {
|
inline char rank_to_char(Rank r) {
|
||||||
return char(r - RANK_1 + int('1'));
|
return char(r - RANK_1 + '1');
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square pawn_push(Color c) {
|
inline Square pawn_push(Color c) {
|
||||||
return c == WHITE ? DELTA_N : DELTA_S;
|
return c == WHITE ? DELTA_N : DELTA_S;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square move_from(Move m) {
|
inline Square from_sq(Move m) {
|
||||||
return Square((m >> 6) & 0x3F);
|
return Square((m >> 6) & 0x3F);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square move_to(Move m) {
|
inline Square to_sq(Move m) {
|
||||||
return Square(m & 0x3F);
|
return Square(m & 0x3F);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool is_special(Move m) {
|
inline MoveType type_of(Move m) {
|
||||||
return m & (3 << 14);
|
return MoveType(m & (3 << 14));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool is_promotion(Move m) {
|
inline PieceType promotion_type(Move m) {
|
||||||
return (m & (3 << 14)) == (1 << 14);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int is_enpassant(Move m) {
|
|
||||||
return (m & (3 << 14)) == (2 << 14);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int is_castle(Move m) {
|
|
||||||
return (m & (3 << 14)) == (3 << 14);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline PieceType promotion_piece_type(Move m) {
|
|
||||||
return PieceType(((m >> 12) & 3) + 2);
|
return PieceType(((m >> 12) & 3) + 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -464,20 +473,13 @@ inline Move make_move(Square from, Square to) {
|
|||||||
return Move(to | (from << 6));
|
return Move(to | (from << 6));
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Move make_promotion_move(Square from, Square to, PieceType promotion) {
|
template<MoveType T>
|
||||||
return Move(to | (from << 6) | (1 << 14) | ((promotion - 2) << 12)) ;
|
inline Move make(Square from, Square to, PieceType pt = KNIGHT) {
|
||||||
}
|
return Move(to | (from << 6) | T | ((pt - KNIGHT) << 12));
|
||||||
|
|
||||||
inline Move make_enpassant_move(Square from, Square to) {
|
|
||||||
return Move(to | (from << 6) | (2 << 14));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Move make_castle_move(Square from, Square to) {
|
|
||||||
return Move(to | (from << 6) | (3 << 14));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool is_ok(Move m) {
|
inline bool is_ok(Move m) {
|
||||||
return move_from(m) != move_to(m); // Catches also MOVE_NULL and MOVE_NONE
|
return from_sq(m) != to_sq(m); // Catches also MOVE_NULL and MOVE_NONE
|
||||||
}
|
}
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -487,26 +489,4 @@ inline const std::string square_to_string(Square s) {
|
|||||||
return ch;
|
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 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // !defined(TYPES_H_INCLUDED)
|
#endif // !defined(TYPES_H_INCLUDED)
|
||||||
|
|||||||
+84
-131
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -17,13 +17,13 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <iomanip>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "evaluate.h"
|
#include "evaluate.h"
|
||||||
#include "misc.h"
|
#include "notation.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
@@ -31,20 +31,20 @@
|
|||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
|
extern void benchmark(const Position& pos, istream& is);
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
// FEN string of the initial position, normal chess
|
// FEN string of the initial position, normal chess
|
||||||
const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||||
|
|
||||||
// Keep track of position keys along the setup moves (from start position to the
|
// Keep track of position keys along the setup moves (from start position to the
|
||||||
// position just before to start searching). This is needed by draw detection
|
// position just before to start searching). Needed by repetition draw detection.
|
||||||
// where, due to 50 moves rule, we need to check at most 100 plies back.
|
Search::StateStackPtr SetupStates;
|
||||||
StateInfo StateRingBuf[102], *SetupState = StateRingBuf;
|
|
||||||
|
|
||||||
void set_option(istringstream& up);
|
void set_option(istringstream& up);
|
||||||
void set_position(Position& pos, istringstream& up);
|
void set_position(Position& pos, istringstream& up);
|
||||||
void go(Position& pos, istringstream& up);
|
void go(const Position& pos, istringstream& up);
|
||||||
void perft(Position& pos, istringstream& up);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -53,85 +53,79 @@ namespace {
|
|||||||
/// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
|
/// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
|
||||||
/// commands, the function also supports a few debug commands.
|
/// commands, the function also supports a few debug commands.
|
||||||
|
|
||||||
void uci_loop() {
|
void UCI::loop(const string& args) {
|
||||||
|
|
||||||
Position pos(StartFEN, false, 0); // The root position
|
Position pos(StartFEN, false, Threads.main_thread()); // The root position
|
||||||
string cmd, token;
|
string token, cmd = args;
|
||||||
|
|
||||||
while (token != "quit")
|
do {
|
||||||
{
|
if (args.empty() && !getline(cin, cmd)) // Block here waiting for input
|
||||||
if (!getline(cin, cmd)) // Block here waiting for input
|
|
||||||
cmd = "quit";
|
cmd = "quit";
|
||||||
|
|
||||||
istringstream is(cmd);
|
istringstream is(cmd);
|
||||||
|
|
||||||
is >> skipws >> token;
|
is >> skipws >> token;
|
||||||
|
|
||||||
if (token == "quit" || token == "stop")
|
if (token == "quit" || token == "stop" || token == "ponderhit")
|
||||||
Threads.stop_thinking();
|
|
||||||
|
|
||||||
else if (token == "ponderhit")
|
|
||||||
{
|
{
|
||||||
// The opponent has played the expected move. GUI sends "ponderhit" if
|
// GUI sends 'ponderhit' to tell us to ponder on the same move the
|
||||||
// we were told to ponder on the same move the opponent has played. We
|
// opponent has played. In case Signals.stopOnPonderhit is set we are
|
||||||
// should continue searching but switching from pondering to normal search.
|
// waiting for 'ponderhit' to stop the search (for instance because we
|
||||||
|
// already ran out of time), otherwise we should continue searching but
|
||||||
|
// switching from pondering to normal search.
|
||||||
|
if (token != "ponderhit" || Search::Signals.stopOnPonderhit)
|
||||||
|
{
|
||||||
|
Search::Signals.stop = true;
|
||||||
|
Threads.main_thread()->notify_one(); // Could be sleeping
|
||||||
|
}
|
||||||
|
else
|
||||||
Search::Limits.ponder = false;
|
Search::Limits.ponder = false;
|
||||||
|
|
||||||
if (Search::Signals.stopOnPonderhit)
|
|
||||||
Threads.stop_thinking();
|
|
||||||
}
|
}
|
||||||
|
else if (token == "perft" && (is >> token)) // Read perft depth
|
||||||
else if (token == "go")
|
|
||||||
go(pos, is);
|
|
||||||
|
|
||||||
else if (token == "ucinewgame")
|
|
||||||
pos.from_fen(StartFEN, false);
|
|
||||||
|
|
||||||
else if (token == "isready")
|
|
||||||
cout << "readyok" << endl;
|
|
||||||
|
|
||||||
else if (token == "position")
|
|
||||||
set_position(pos, is);
|
|
||||||
|
|
||||||
else if (token == "setoption")
|
|
||||||
set_option(is);
|
|
||||||
|
|
||||||
else if (token == "perft")
|
|
||||||
perft(pos, is);
|
|
||||||
|
|
||||||
else if (token == "d")
|
|
||||||
pos.print();
|
|
||||||
|
|
||||||
else if (token == "flip")
|
|
||||||
pos.flip_me();
|
|
||||||
|
|
||||||
else if (token == "eval")
|
|
||||||
{
|
{
|
||||||
read_evaluation_uci_options(pos.side_to_move());
|
stringstream ss;
|
||||||
cout << trace_evaluate(pos) << endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
ss << Options["Hash"] << " "
|
||||||
|
<< Options["Threads"] << " " << token << " current perft";
|
||||||
|
|
||||||
|
benchmark(pos, ss);
|
||||||
|
}
|
||||||
else if (token == "key")
|
else if (token == "key")
|
||||||
cout << "key: " << hex << pos.key()
|
sync_cout << hex << uppercase << setfill('0')
|
||||||
<< "\nmaterial key: " << pos.material_key()
|
<< "position key: " << setw(16) << pos.key()
|
||||||
<< "\npawn key: " << pos.pawn_key() << endl;
|
<< "\nmaterial key: " << setw(16) << pos.material_key()
|
||||||
|
<< "\npawn key: " << setw(16) << pos.pawn_key()
|
||||||
|
<< dec << sync_endl;
|
||||||
|
|
||||||
else if (token == "uci")
|
else if (token == "uci")
|
||||||
cout << "id name " << engine_info(true)
|
sync_cout << "id name " << engine_info(true)
|
||||||
<< "\n" << Options
|
<< "\n" << Options
|
||||||
<< "\nuciok" << endl;
|
<< "\nuciok" << sync_endl;
|
||||||
|
|
||||||
|
else if (token == "ucinewgame") { /* Avoid returning "Unknown command" */ }
|
||||||
|
else if (token == "go") go(pos, is);
|
||||||
|
else if (token == "position") set_position(pos, is);
|
||||||
|
else if (token == "setoption") set_option(is);
|
||||||
|
else if (token == "flip") pos.flip();
|
||||||
|
else if (token == "bench") benchmark(pos, is);
|
||||||
|
else if (token == "d") sync_cout << pos.pretty() << sync_endl;
|
||||||
|
else if (token == "isready") sync_cout << "readyok" << sync_endl;
|
||||||
|
else if (token == "eval") sync_cout << Eval::trace(pos) << sync_endl;
|
||||||
else
|
else
|
||||||
cout << "Unknown command: " << cmd << endl;
|
sync_cout << "Unknown command: " << cmd << sync_endl;
|
||||||
}
|
|
||||||
|
} while (token != "quit" && args.empty()); // Args have one-shot behaviour
|
||||||
|
|
||||||
|
Threads.wait_for_think_finished(); // Cannot quit while search is running
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
// set_position() is called when engine receives the "position" UCI
|
// set_position() is called when engine receives the "position" UCI command.
|
||||||
// command. The function sets up the position described in the given
|
// The function sets up the position described in the given fen string ("fen")
|
||||||
// fen string ("fen") or the starting position ("startpos") and then
|
// or the starting position ("startpos") and then makes the moves given in the
|
||||||
// makes the moves given in the following move list ("moves").
|
// following move list ("moves").
|
||||||
|
|
||||||
void set_position(Position& pos, istringstream& is) {
|
void set_position(Position& pos, istringstream& is) {
|
||||||
|
|
||||||
@@ -151,16 +145,14 @@ namespace {
|
|||||||
else
|
else
|
||||||
return;
|
return;
|
||||||
|
|
||||||
pos.from_fen(fen, Options["UCI_Chess960"]);
|
pos.set(fen, Options["UCI_Chess960"], Threads.main_thread());
|
||||||
|
SetupStates = Search::StateStackPtr(new std::stack<StateInfo>());
|
||||||
|
|
||||||
// Parse move list (if any)
|
// Parse move list (if any)
|
||||||
while (is >> token && (m = move_from_uci(pos, token)) != MOVE_NONE)
|
while (is >> token && (m = move_from_uci(pos, token)) != MOVE_NONE)
|
||||||
{
|
{
|
||||||
pos.do_move(m, *SetupState);
|
SetupStates->push(StateInfo());
|
||||||
|
pos.do_move(m, SetupStates->top());
|
||||||
// Increment pointer to StateRingBuf circular buffer
|
|
||||||
if (++SetupState - StateRingBuf >= 102)
|
|
||||||
SetupState = StateRingBuf;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,81 +174,42 @@ namespace {
|
|||||||
while (is >> token)
|
while (is >> token)
|
||||||
value += string(" ", !value.empty()) + token;
|
value += string(" ", !value.empty()) + token;
|
||||||
|
|
||||||
if (!Options.count(name))
|
if (Options.count(name))
|
||||||
cout << "No such option: " << name << endl;
|
|
||||||
|
|
||||||
else if (value.empty()) // UCI buttons don't have a value
|
|
||||||
Options[name] = true;
|
|
||||||
|
|
||||||
else
|
|
||||||
Options[name] = value;
|
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
|
// 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 thinking time and other parameters from the input string, and starts
|
||||||
// the main searching thread.
|
// the search.
|
||||||
|
|
||||||
void go(Position& pos, istringstream& is) {
|
void go(const Position& pos, istringstream& is) {
|
||||||
|
|
||||||
string token;
|
|
||||||
Search::LimitsType limits;
|
Search::LimitsType limits;
|
||||||
std::vector<Move> searchMoves;
|
vector<Move> searchMoves;
|
||||||
int time[] = { 0, 0 }, inc[] = { 0, 0 };
|
string token;
|
||||||
|
|
||||||
while (is >> token)
|
while (is >> token)
|
||||||
{
|
{
|
||||||
if (token == "infinite")
|
if (token == "searchmoves")
|
||||||
limits.infinite = true;
|
|
||||||
else if (token == "ponder")
|
|
||||||
limits.ponder = true;
|
|
||||||
else if (token == "wtime")
|
|
||||||
is >> time[WHITE];
|
|
||||||
else if (token == "btime")
|
|
||||||
is >> time[BLACK];
|
|
||||||
else if (token == "winc")
|
|
||||||
is >> inc[WHITE];
|
|
||||||
else if (token == "binc")
|
|
||||||
is >> inc[BLACK];
|
|
||||||
else if (token == "movestogo")
|
|
||||||
is >> limits.movesToGo;
|
|
||||||
else if (token == "depth")
|
|
||||||
is >> limits.maxDepth;
|
|
||||||
else if (token == "nodes")
|
|
||||||
is >> limits.maxNodes;
|
|
||||||
else if (token == "movetime")
|
|
||||||
is >> limits.maxTime;
|
|
||||||
else if (token == "searchmoves")
|
|
||||||
while (is >> token)
|
while (is >> token)
|
||||||
searchMoves.push_back(move_from_uci(pos, token));
|
searchMoves.push_back(move_from_uci(pos, token));
|
||||||
|
|
||||||
|
else 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 == "mate") is >> limits.mate;
|
||||||
|
else if (token == "infinite") limits.infinite = true;
|
||||||
|
else if (token == "ponder") limits.ponder = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
limits.time = time[pos.side_to_move()];
|
Threads.start_thinking(pos, limits, searchMoves, SetupStates);
|
||||||
limits.increment = inc[pos.side_to_move()];
|
|
||||||
|
|
||||||
Threads.start_thinking(pos, limits, searchMoves, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// perft() is called when engine receives the "perft" command. The function
|
|
||||||
// calls perft() with the required search depth then prints counted leaf nodes
|
|
||||||
// and elapsed time.
|
|
||||||
|
|
||||||
void perft(Position& pos, istringstream& is) {
|
|
||||||
|
|
||||||
int depth, time;
|
|
||||||
|
|
||||||
if (!(is >> depth))
|
|
||||||
return;
|
|
||||||
|
|
||||||
time = system_time();
|
|
||||||
|
|
||||||
int64_t n = Search::perft(pos, depth * ONE_PLY);
|
|
||||||
|
|
||||||
time = system_time() - time;
|
|
||||||
|
|
||||||
std::cout << "\nNodes " << n
|
|
||||||
<< "\nTime (ms) " << time
|
|
||||||
<< "\nNodes/second " << int(n / (time / 1000.0)) << std::endl;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-49
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -18,74 +18,90 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstdlib>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include "evaluate.h"
|
||||||
#include "misc.h"
|
#include "misc.h"
|
||||||
#include "thread.h"
|
#include "thread.h"
|
||||||
|
#include "tt.h"
|
||||||
#include "ucioption.h"
|
#include "ucioption.h"
|
||||||
|
|
||||||
using std::string;
|
using std::string;
|
||||||
|
|
||||||
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
|
||||||
static bool ci_less(char c1, char c2) { return tolower(c1) < tolower(c2); }
|
bool ci_less(char c1, char c2) { return tolower(c1) < tolower(c2); }
|
||||||
|
|
||||||
bool CaseInsensitiveLess::operator() (const string& s1, const string& s2) const {
|
bool CaseInsensitiveLess::operator() (const string& s1, const string& s2) const {
|
||||||
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ci_less);
|
return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ci_less);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// OptionsMap c'tor initializes the UCI options to their hard coded default
|
/// init() initializes the UCI options to their hard coded default values
|
||||||
/// values and initializes the default value of "Threads" and "Min Split Depth"
|
/// and initializes the default value of "Threads" and "Min Split Depth"
|
||||||
/// parameters according to the number of CPU cores detected.
|
/// parameters according to the number of CPU cores detected.
|
||||||
|
|
||||||
OptionsMap::OptionsMap() {
|
void init(OptionsMap& o) {
|
||||||
|
|
||||||
int cpus = std::min(cpu_count(), MAX_THREADS);
|
int cpus = std::min(cpu_count(), MAX_THREADS);
|
||||||
int msd = cpus < 8 ? 4 : 7;
|
int msd = cpus < 8 ? 4 : 7;
|
||||||
OptionsMap& o = *this;
|
|
||||||
|
|
||||||
o["Use Search Log"] = UCIOption(false);
|
o["Use Debug Log"] = Option(false, on_logger);
|
||||||
o["Search Log Filename"] = UCIOption("SearchLog.txt");
|
o["Use Search Log"] = Option(false);
|
||||||
o["Book File"] = UCIOption("book.bin");
|
o["Search Log Filename"] = Option("SearchLog.txt");
|
||||||
o["Best Book Move"] = UCIOption(false);
|
o["Book File"] = Option("book.bin");
|
||||||
o["Mobility (Middle Game)"] = UCIOption(100, 0, 200);
|
o["Best Book Move"] = Option(false);
|
||||||
o["Mobility (Endgame)"] = UCIOption(100, 0, 200);
|
o["Contempt Factor"] = Option(0, -50, 50);
|
||||||
o["Passed Pawns (Middle Game)"] = UCIOption(100, 0, 200);
|
o["Mobility (Middle Game)"] = Option(100, 0, 200, on_eval);
|
||||||
o["Passed Pawns (Endgame)"] = UCIOption(100, 0, 200);
|
o["Mobility (Endgame)"] = Option(100, 0, 200, on_eval);
|
||||||
o["Space"] = UCIOption(100, 0, 200);
|
o["Passed Pawns (Middle Game)"] = Option(100, 0, 200, on_eval);
|
||||||
o["Aggressiveness"] = UCIOption(100, 0, 200);
|
o["Passed Pawns (Endgame)"] = Option(100, 0, 200, on_eval);
|
||||||
o["Cowardice"] = UCIOption(100, 0, 200);
|
o["Space"] = Option(100, 0, 200, on_eval);
|
||||||
o["Min Split Depth"] = UCIOption(msd, 4, 7);
|
o["Aggressiveness"] = Option(100, 0, 200, on_eval);
|
||||||
o["Max Threads per Split Point"] = UCIOption(5, 4, 8);
|
o["Cowardice"] = Option(100, 0, 200, on_eval);
|
||||||
o["Threads"] = UCIOption(cpus, 1, MAX_THREADS);
|
o["Min Split Depth"] = Option(msd, 4, 12, on_threads);
|
||||||
o["Use Sleeping Threads"] = UCIOption(false);
|
o["Max Threads per Split Point"] = Option(5, 4, 8, on_threads);
|
||||||
o["Hash"] = UCIOption(32, 4, 8192);
|
o["Threads"] = Option(cpus, 1, MAX_THREADS, on_threads);
|
||||||
o["Clear Hash"] = UCIOption(false, "button");
|
o["Use Sleeping Threads"] = Option(false);
|
||||||
o["Ponder"] = UCIOption(true);
|
o["Hash"] = Option(32, 1, 8192, on_hash_size);
|
||||||
o["OwnBook"] = UCIOption(true);
|
o["Clear Hash"] = Option(on_clear_hash);
|
||||||
o["MultiPV"] = UCIOption(1, 1, 500);
|
o["Ponder"] = Option(true);
|
||||||
o["Skill Level"] = UCIOption(20, 0, 20);
|
o["OwnBook"] = Option(false);
|
||||||
o["Emergency Move Horizon"] = UCIOption(40, 0, 50);
|
o["MultiPV"] = Option(1, 1, 500);
|
||||||
o["Emergency Base Time"] = UCIOption(200, 0, 30000);
|
o["Skill Level"] = Option(20, 0, 20);
|
||||||
o["Emergency Move Time"] = UCIOption(70, 0, 5000);
|
o["Emergency Move Horizon"] = Option(40, 0, 50);
|
||||||
o["Minimum Thinking Time"] = UCIOption(20, 0, 5000);
|
o["Emergency Base Time"] = Option(200, 0, 30000);
|
||||||
o["UCI_Chess960"] = UCIOption(false);
|
o["Emergency Move Time"] = Option(70, 0, 5000);
|
||||||
o["UCI_AnalyseMode"] = UCIOption(false);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// operator<<() is used to output all the UCI options in chronological insertion
|
/// operator<<() is used to print all the options default values in chronological
|
||||||
/// order (the idx field) and in the format defined by the UCI protocol.
|
/// insertion order (the idx field) and in the format defined by the UCI protocol.
|
||||||
|
|
||||||
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
||||||
|
|
||||||
for (size_t idx = 0; idx < om.size(); idx++)
|
for (size_t idx = 0; idx < om.size(); idx++)
|
||||||
for (OptionsMap::const_iterator it = om.begin(); it != om.end(); ++it)
|
for (OptionsMap::const_iterator it = om.begin(); it != om.end(); ++it)
|
||||||
if (it->second.idx == idx)
|
if (it->second.idx == idx)
|
||||||
{
|
{
|
||||||
const UCIOption& o = it->second;
|
const Option& o = it->second;
|
||||||
os << "\noption name " << it->first << " type " << o.type;
|
os << "\noption name " << it->first << " type " << o.type;
|
||||||
|
|
||||||
if (o.type != "button")
|
if (o.type != "button")
|
||||||
@@ -100,28 +116,52 @@ std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// UCIOption class c'tors
|
/// Option c'tors and conversion operators
|
||||||
|
|
||||||
UCIOption::UCIOption(const char* v) : type("string"), min(0), max(0), idx(Options.size())
|
Option::Option(const char* v, Fn* f) : type("string"), min(0), max(0), idx(Options.size()), on_change(f)
|
||||||
{ defaultValue = currentValue = v; }
|
{ defaultValue = currentValue = v; }
|
||||||
|
|
||||||
UCIOption::UCIOption(bool v, string t) : type(t), min(0), max(0), idx(Options.size())
|
Option::Option(bool v, Fn* f) : type("check"), min(0), max(0), idx(Options.size()), on_change(f)
|
||||||
{ defaultValue = currentValue = (v ? "true" : "false"); }
|
{ defaultValue = currentValue = (v ? "true" : "false"); }
|
||||||
|
|
||||||
UCIOption::UCIOption(int v, int minv, int maxv) : type("spin"), min(minv), max(maxv), idx(Options.size())
|
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(); }
|
{ std::ostringstream ss; ss << v; defaultValue = currentValue = ss.str(); }
|
||||||
|
|
||||||
|
|
||||||
/// UCIOption::operator=() updates currentValue. Normally it's up to the GUI to
|
Option::operator int() const {
|
||||||
/// check for option's limits, but we could receive the new value directly from
|
assert(type == "check" || type == "spin");
|
||||||
/// the user by teminal window, so let's check the bounds anyway.
|
return (type == "spin" ? atoi(currentValue.c_str()) : currentValue == "true");
|
||||||
|
}
|
||||||
|
|
||||||
void UCIOption::operator=(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());
|
assert(!type.empty());
|
||||||
|
|
||||||
if ( !v.empty()
|
if ( (type != "button" && v.empty())
|
||||||
&& (type == "check" || type == "button") == (v == "true" || v == "false")
|
|| (type == "check" && v != "true" && v != "false")
|
||||||
&& (type != "spin" || (atoi(v.c_str()) >= min && atoi(v.c_str()) <= max)))
|
|| (type == "spin" && (atoi(v.c_str()) < min || atoi(v.c_str()) > max)))
|
||||||
|
return *this;
|
||||||
|
|
||||||
|
if (type != "button")
|
||||||
currentValue = v;
|
currentValue = v;
|
||||||
|
|
||||||
|
if (on_change)
|
||||||
|
(*on_change)(*this);
|
||||||
|
|
||||||
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace UCI
|
||||||
|
|||||||
+29
-34
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
|
Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
|
||||||
|
|
||||||
Stockfish is free software: you can redistribute it and/or modify
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU General Public License as published by
|
it under the terms of the GNU General Public License as published by
|
||||||
@@ -20,33 +20,35 @@
|
|||||||
#if !defined(UCIOPTION_H_INCLUDED)
|
#if !defined(UCIOPTION_H_INCLUDED)
|
||||||
#define UCIOPTION_H_INCLUDED
|
#define UCIOPTION_H_INCLUDED
|
||||||
|
|
||||||
#include <cassert>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
struct OptionsMap;
|
namespace UCI {
|
||||||
|
|
||||||
|
class Option;
|
||||||
|
|
||||||
|
/// 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&);
|
||||||
|
|
||||||
/// UCIOption class implements an option as defined by UCI protocol
|
|
||||||
class UCIOption {
|
|
||||||
public:
|
public:
|
||||||
UCIOption() {} // Required by std::map::operator[]
|
Option(Fn* = NULL);
|
||||||
UCIOption(const char* v);
|
Option(bool v, Fn* = NULL);
|
||||||
UCIOption(bool v, std::string type = "check");
|
Option(const char* v, Fn* = NULL);
|
||||||
UCIOption(int v, int min, int max);
|
Option(int v, int min, int max, Fn* = NULL);
|
||||||
|
|
||||||
void operator=(const std::string& v);
|
Option& operator=(const std::string& v);
|
||||||
void operator=(bool v) { *this = std::string(v ? "true" : "false"); }
|
operator int() const;
|
||||||
|
operator std::string() const;
|
||||||
operator int() const {
|
|
||||||
assert(type == "check" || type == "button" || type == "spin");
|
|
||||||
return (type == "spin" ? atoi(currentValue.c_str()) : currentValue == "true");
|
|
||||||
}
|
|
||||||
|
|
||||||
operator std::string() const {
|
|
||||||
assert(type == "string");
|
|
||||||
return currentValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
|
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
|
||||||
@@ -54,21 +56,14 @@ private:
|
|||||||
std::string defaultValue, currentValue, type;
|
std::string defaultValue, currentValue, type;
|
||||||
int min, max;
|
int min, max;
|
||||||
size_t idx;
|
size_t idx;
|
||||||
|
Fn* on_change;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
void init(OptionsMap&);
|
||||||
|
void loop(const std::string&);
|
||||||
|
|
||||||
/// Custom comparator because UCI options should be case insensitive
|
} // namespace UCI
|
||||||
struct CaseInsensitiveLess {
|
|
||||||
bool operator() (const std::string&, const std::string&) const;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
extern UCI::OptionsMap Options;
|
||||||
/// Our options container is actually a map with a customized c'tor
|
|
||||||
struct OptionsMap : public std::map<std::string, UCIOption, CaseInsensitiveLess> {
|
|
||||||
OptionsMap();
|
|
||||||
};
|
|
||||||
|
|
||||||
extern std::ostream& operator<<(std::ostream&, const OptionsMap&);
|
|
||||||
extern OptionsMap Options;
|
|
||||||
|
|
||||||
#endif // !defined(UCIOPTION_H_INCLUDED)
|
#endif // !defined(UCIOPTION_H_INCLUDED)
|
||||||
|
|||||||
Reference in New Issue
Block a user